I am using the default nextjs server to run my nextjs program by this command next start
.
However, I am not able to change the cache-control header for the files under the public folder.
Is there any method to set the cache-control header without setting the Custom Server?
Next. js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL ( / ).
To use Cache-Control headers, choose Content Management | Cache Control Directives in the administration server. Then, using the Resource Picker, choose the directory where you want to set the headers. After setting the headers, click 'OK'.
Next. js also became one of the most popular Static Site Generators. In other words, it's one of the best frameworks now for building superfast and SEO-friendly Jamstack websites.
There is undocumented feature or bug, but it works. More info can be found here https://nextjs.org/docs/api-reference/next.config.js/headers
Add config to you next.config.js
file for example:
async headers() {
return [
{
source: '/:all*(svg|jpg|png)',
locale: false,
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=9999999999, must-revalidate',
}
],
},
]
},
Per this bug report and discussion the Next devs believe static file serving should only be used as a developer convenience, not in production, and hence they don't consider it a priority to add such features.
However, in the issue comments somebody has suggested a workaround using Express to detect requests that will end up serving static files. For example, if the Next.js route handler is the handler()
method you can do this to set a one-year cache policy for *.woff font files:
// this is a hack to make the cache headers friendlier..
server.get('*.woff2?', (req, res) => {
res.setHeader('Cache-Control', 'public,max-age=31536000');
return handler(req, res);
});
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