I have a need to add a header to each request to the server.
I do it this using _midleware like this:
export async function middleware(req: NextRequest): Promise<NextResponse> {
req.headers.append('x-custom-header', '1337');
return NextResponse.next();
}
If I do console.log(req.headers) I see that the request header has been added:
BaseHeaders [Headers] {
[Symbol(map)]: {
accept: [ '*/*' ],
'accept-encoding': [ 'gzip, deflate, br' ],
'accept-language': [ 'en-GB,en-US;q=0.9,en;q=0.8' ],
'cache-control': [ 'no-cache' ],
connection: [ 'keep-alive' ],
cookie: ...,
host: ...,
pragma: [ 'no-cache' ],
referer: ...,
...,
'x-custom-header': [ '1337' ]
}
}
However, this does not modify the request: there is no request header in the browser.
Why is the request not modified? Are there alternative ways to modify request headers in Next.js?
Looks like starting from Next.js v13.0.0 it is now possible to modify request headers: https://nextjs.org/docs/advanced-features/middleware#setting-headers
Here's a code snippet from the documentation:
// 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
}
This is what worked for me. The header is changed in middleware and reflected in getServerSideProps.
export async function middleware(request: NextRequest) : Promise<NextResponse> {
const response = NextResponse.next()
response.headers.append("key", "value")
return response
}
//inside page
export const getServerSideProps = wrapper.getServerSideProps(store => async (context) => {
//the headers are changed here
console.log(context.res.getHeaders())
return {
props: {}
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With