Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs for request headers overrides in middleware #41546

Merged
merged 3 commits into from Oct 19, 2022
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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({
balazsorban44 marked this conversation as resolved.
Show resolved Hide resolved
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:** Please 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.
balazsorban44 marked this conversation as resolved.
Show resolved Hide resolved

## Related

<div class="card">
Expand Down