How to set custom HTTP response headers in Next.js without using a custom server?

Viewed 17515

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?

2 Answers

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

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.

Related