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

Viewed 12876

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?

3 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',
          }
        ],
      },
    ]
  },

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);
  });

I'm using Express as a custom server for Next.js, and this is how I set "Cache-Control" header for static files:

const express = require("express");
const server = express();
...
server.use(express.static(__dirname + "/public", { maxAge: "365d" }));
server.use(function (req, res, next) {
  if (req.url.match(".js|.css|.woff|.jpg|.png|.gif|.ttf")) {
    res.setHeader("Cache-Control", "public,max-age=31536000"); // 365 days
  }
  next();
});
Related