Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify request headers in Next.js

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?

like image 423
aiw Avatar asked Jan 26 '26 16:01

aiw


2 Answers

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
}
like image 166
makeiteasy Avatar answered Jan 29 '26 06:01

makeiteasy


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: {}
    }
  }
});
like image 24
EricLKH Avatar answered Jan 29 '26 04:01

EricLKH