Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting cache-control header for static file serving on nextjs default server

Tags:

next.js

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?

like image 923
Ken Yip Avatar asked May 29 '20 02:05

Ken Yip


People also ask

How do I serve a static file in Nextjs?

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 ( / ).

How do I set up cache control headers?

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

Is Nextjs good for static?

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.


2 Answers

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',
          }
        ],
      },
    ]
  },
like image 67
FDisk Avatar answered Oct 09 '22 13:10

FDisk


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);
  });
like image 33
hallvors Avatar answered Oct 09 '22 13:10

hallvors