Next.js Discord

Discord Forum

Unable to set request headers in middleware

Answered
Chinese Alligator posted this in #help-forum
Open in Discord
Chinese AlligatorOP
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers)

  requestHeaders.set("X-Request-Header", "test")
 
  const response = NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  })
 
  return response
}

Inspecting the devtools network tab I do not see the X-Request-Header in my Request Header section for any of the network requests.
I am however able to add a response header:
response.headers.set(
  'X-Response-Header', "But i need a Request Header"
)
Answered by joulev
You don’t see it in the network tab because the network tab only displays the raw request object that you sent to the server. Here in middleware it is done entirely in the server, your browser doesn’t know.

If you use headers() in a server component to read the header, you should still be able to get the header value correctly.
View full answer

1 Reply