From 3f7e922a402dcffad2f1f200606f5d7370d4c3bf Mon Sep 17 00:00:00 2001 From: Seiya Nuta Date: Wed, 19 Oct 2022 22:46:03 +0900 Subject: [PATCH] Docs for request headers overrides in middleware (#41546) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/advanced-features/middleware.md | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/advanced-features/middleware.md b/docs/advanced-features/middleware.md index 24955cfa1936..4e719de1a13b 100644 --- a/docs/advanced-features/middleware.md +++ b/docs/advanced-features/middleware.md @@ -140,6 +140,7 @@ The [`NextResponse`](#nextresponse) API allows you to: - `redirect` the incoming request to a different URL - `rewrite` the response by displaying a given URL +- Set request headers for API Routes, `getServerSideProps`, and `rewrite` destinations - Set response cookies - Set response headers @@ -177,6 +178,37 @@ export function middleware(request: NextRequest) { } ``` +## Setting Headers + +You can set request and response headers using the `NextResponse` API. + +```ts +// middleware.ts + +import { NextResponse } from 'next/server' +import type { NextRequest } from 'next/server' + +export function middleware(request: NextRequest) { + // Clone the request headers and set a new header `x-hello-from-middleware1` + const requestHeaders = new Headers(request.headers) + requestHeaders.set('x-hello-from-middleware1', 'hello') + + // You can also set request headers in NextResponse.rewrite + const response = NextResponse.next({ + request: { + // New request headers + headers: requestHeaders, + }, + }) + + // Set a new response header `x-hello-from-middleware2` + response.headers.set('x-hello-from-middleware2', 'hello') + return response +} +``` + +> **Note:** Avoid setting large headers as it might cause [431 Request Header Fields Too Large](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/431) error depending on your backend web server configuration. + ## Related