Headers
Headers allow you to set custom HTTP headers for an incoming request path.
To set custom HTTP headers you can use the key in next.config.js
:
source
is the incoming request path pattern.headers
is an array of header objects with thekey
andvalue
properties.
If two headers match the same path and set the same header key, the last header key will override the first. Using the below headers, the path /hello
will result in the header x-hello
being world
due to the last header value set being world
.
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'x-hello',
value: 'there',
},
],
},
{
source: '/hello',
headers: [
{
key: 'x-hello',
value: 'world',
],
},
],
},
}
Path matches are allowed, for example /blog/:slug
will match /blog/hello-world
(no nested paths):
module.exports = {
async headers() {
return [
{
source: '/blog/:slug*',
headers: [
{
key: 'x-slug',
value: ':slug*', // Matched parameters can be used in the value
},
{
key: 'x-slug-:slug*', // Matched parameters can be used in the key
value: 'my other custom header value',
},
],
},
],
},
}
To match a regex path you can wrap the regex in parenthesis after a parameter, for example /blog/:slug(\\d{1,})
will match but not /blog/abc
:
When leveraging basePath
support with headers each source
is automatically prefixed with the basePath
unless you add basePath: false
to the header:
module.exports = {
async headers() {
return [
{
source: '/with-basePath', // becomes /docs/with-basePath
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
source: '/without-basePath', // is not modified since basePath: false is set
headers: [
{
key: 'x-hello',
value: 'world',
},
],
basePath: false,
},
]
}