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?
You don't need a node server running 24/7 for hosting your application. Also, if you don't use getServerSideProps, Next. js by default will pre-render your page, this page gets cached on a CDN. So yes you can make API calls to your PHP backend, without the need for a setting up a nodejs server yourself.
Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.
NextJS built in middleware API routes does not provide req. headers. Instead you need to pass cookies on your request.
Yes, you can. But, why would you want to? The HTTP protocol allows you to set your own custom headers. However, it would also mean that your server would need o understand your custom headers.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With