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?
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.