17

I am working on a Next.js application, and I would like to add a custom HTTP response header to all pages (I don't need it to be configurable per page).

Now I was wondering how to do that, without having to set up a custom server. Is this even possible? If so, how?

Golo Roden
  • 140,679
  • 96
  • 298
  • 425

2 Answers2

17

It's probably not possible without tradeoffs. Next.js has Automatic Static Optimization, so pages that can be statically exported will be exported to plain .html files. And .html files require no code execution on a server so there is no place to add a custom HTTP header.

Alternatively, you could add custom HTTP headers on every response with getServerSideProps in _app.js:

export async function getServerSideProps(context) {

  // set HTTP header
  context.res.setHeader('Content-Type', 'application/json')

  return {
    props: {}, // will be passed to the page component as props
  }
}

But having getServerSideProps would disable static optimization as all pages will be only server-side rendered.

Server-side Rendering

Nikolai Kiselev
  • 6,201
  • 2
  • 27
  • 37
  • This is the way, if you are deploying to Vercel – Jakov Gl. Jun 20 '21 at 21:03
  • `context.res.setHeader('toast', 'some message')` hasn't been working for me. Even calling `console.log('headers', context.res.getHeaders());` in the next line doesn't show my new header. Can you please look at https://stackoverflow.com/questions/72190692/how-can-i-show-a-toast-notification-when-redirecting-due-to-lack-of-session-usin?noredirect=1#comment127573841_72201657 Thank you so much for your help. – Ryan May 11 '22 at 18:29
13

For Next.js versions 9.5 and after you can define custom headers in your next.config.js file.

The following config would apply a custom header to all static and server-rendered pages.

module.exports = {
  async headers() {
    return [
      { 
        source: '/:path*{/}?',
        headers: [
          {
            key: 'x-custom-header',
            value: 'my custom header value for all pages',
          },
        ],
      },
    ]
  },
}

See next.config.js Headers

Currently matching all pages is a little unintuitive. As seen in the example above it requires the syntax '/:path*{/}?'. This is currently tracked in GitHub Issue #14930.

jamsinclair
  • 1,257
  • 1
  • 12
  • 16
  • This won't work on Vercel because it will overwrite Cache-Control headers set in next.config.js in production to ensure that static assets can be cache effectively – Jakov Gl. Jun 20 '21 at 21:02