Skip to content

Commit

Permalink
Docs for request headers overrides in middleware (#41546)
Browse files Browse the repository at this point in the history
Co-authored-by: Balázs Orbán <info@balazsorban.com>
  • Loading branch information
nuta and balazsorban44 committed Oct 19, 2022
1 parent d27185b commit 3f7e922
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions docs/advanced-features/middleware.md
Expand Up @@ -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

Expand Down Expand Up @@ -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

<div class="card">
Expand Down

0 comments on commit 3f7e922

Please sign in to comment.