-
Notifications
You must be signed in to change notification settings - Fork 30.3k
Description
What is the documentation issue?
The Middleware documentation explains how to modify request headers using NextResponse.next({ request: { headers } }), but it doesn't cover how to compose multiple middleware that each need to forward request headers.
When using multiple middleware (e.g., authentication + i18n), each may need to forward internal request headers:
- Auth middleware forwards x-session-id, x-user-id
- i18n middleware forwards x-locale
There's no documented pattern for merging these forwarded headers. The current examples show single middleware only. This leads developers to either:
- Mutate request.headers directly (not documented/supported)
- Parse internal x-middleware-* headers (brittle)
- Give up on composition
The docs should include a recommended pattern for this common use case.
Is there any context that might help us understand?
Example use case:
// auth-middleware.ts
export function withAuth(request) {
const headers = new Headers(request.headers);
headers.set('x-session-id', 'abc');
return NextResponse.next({ request: { headers } });
}
// i18n-middleware.ts
export function withLocale(request) {
const headers = new Headers(request.headers);
headers.set('x-locale', 'en');
return NextResponse.next({ request: { headers } });
}
// middleware.ts - How to compose these?
export function middleware(request) {
const authRes = withAuth(request);
const i18nRes = withLocale(request);
// ❌ No documented way to merge forwarded request headers
// Currently must choose: authRes OR i18nRes, not both
}Current workarounds:
- Mutating
request.headersbefore calling other middleware (works but not documented/guaranteed) - Parsing internal
x-middleware-override-headers(brittle, depends on implementation details)
Why this matters:
- Middleware composition is essential for real apps
- Auth + i18n is a classic combination
- The lack of a pattern pushes complexity to userland
- Library authors (AuthKit, next-intl, etc.) can't provide clean composition helpers
Requested addition:
Document a recommended pattern for merging forwarded request headers, or note that this is a current limitation and suggest the least-brittle workaround.
Does the docs page already exist? Please link to it.
https://nextjs.org/docs/app/building-your-application/routing/middleware#setting-headers
The "Setting Headers" section shows the basic usage but doesn't address composition.