Modyfing request headers in middleware

In some cases we might want to add, modify, or delete request headers from clients to change behavior or pass data to API Routes or getServerSideProps. To modify to the request headers specify the new headers (see Headers API) in request.headers parameter of NextResponse.next() or NextResponse.rewrite().

Only available since Next.js v13.0.0.

// You can use headers API:
// https://developer.mozilla.org/en-US/docs/Web/API/Headers 
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-hello-from-middleware1', 'hello')
requestHeaders.set('x-hello-from-middleware2', 'world!')
requestHeaders.set('user-agent', 'New User Agent overriden by middleware!')

const response = NextResponse.next({
  request: {
    headers: requestHeaders,
  },
})

Request Headers in getServerSideProps:

x-hello-from-middleware1: hello

x-hello-from-middleware2: world!

user-agent: New User Agent overriden by middleware!