How to change cache-control header for all site's routes
Answered
Morelet’s Crocodile posted this in #help-forum
Morelet’s CrocodileOP
In my site, when someone calls
This prevents my CDN (sitting in front of the Next.js server) from caching that page
Is this the default Next behavior ?
Any way to change it ?
For static resources (js, css files) the cache control is fine
mysite.com/some-page the response for that page has the following cache-control header:private, no-cache, no-store, max-age=0, must-revalidateThis prevents my CDN (sitting in front of the Next.js server) from caching that page
Is this the default Next behavior ?
Any way to change it ?
For static resources (js, css files) the cache control is fine
Answered by Ray
maybe you can try this in next.config.js
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'Cache-Control',
value: 'max-age=300s',
},
],
},
{
source: '/hello',
headers: [
{
key: 'Cache-Control',
value: 's-maxage=300s',
},
],
},
]
},
}18 Replies
@Morelet’s Crocodile In my site, when someone calls `mysite.com/some-page` the response for that page has the following cache-control header:
private, no-cache, no-store, max-age=0, must-revalidate
This prevents my CDN (sitting in front of the Next.js server) from caching that page
Is this the default Next behavior ?
Any way to change it ?
For static resources (js, css files) the cache control is fine
maybe you can try this in next.config.js
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'Cache-Control',
value: 'max-age=300s',
},
],
},
{
source: '/hello',
headers: [
{
key: 'Cache-Control',
value: 's-maxage=300s',
},
],
},
]
},
}Answer
Morelet’s CrocodileOP
Cool, did you take it from any documentation you can point me to ?
Morelet’s CrocodileOP
Looks good thank you!
@Morelet’s Crocodile Looks good thank you!
cool, please mark solution if your issue has been solved
Morelet’s CrocodileOP
Looks like it won't work
https://nextjs.org/docs/app/api-reference/next-config-js/headers#cache-control
https://nextjs.org/docs/app/api-reference/next-config-js/headers#cache-control
it only work in production build
are you trying it with
next start?Morelet’s CrocodileOP
I need it to work in production, and from the docs, it says that overriding cache-control headers in the config will not work in production
well it works for me on dynamic page
the cache control header for static page will be
s-maxage=31536000, stale-while-revalidateif you get this header
which mean its a dynamic page
private, no-cache, no-store, max-age=0, must-revalidatewhich mean its a dynamic page
Morelet’s CrocodileOP
So what do they mean by
You cannot set Cache-Control headers in next.config.js for pages or assets, as these headers will be overwritten in production to ensure that responses and static assets are cached effectively.
Morelet’s CrocodileOP
Okay, thanks for your help, appreciate it