Node Cache-Control - unable to set headers in client/build

Viewed 181

I'm using create react app with node/express. I am attempting to resolve a performance issue reported by Lighthouse "Serve static assets with an efficient cache policy".

I have attempted to set Cache-Control in a variety of ways. Below is the current config and it's not working.

let options = {
      etag: true,
      maxAge: 31536000,
      redirect: true,
      setHeaders: function (res, path, stat) {
        res.set(
          {
          'x-timestamp': Date.now(),
          'robert': 'hi'
          }
        )
      }
    };

let indexOptions = {
  'Cache-Control': 'no-cache'
};

if (process.env.NODE_ENV === 'production') {
  // Serve any static files
  // app.use(express.static(path.join(__dirname, 'client/build')));
  // ADDED OPTIONS WITH CACHE EXPIRY
  app.use(express.static(path.join(__dirname, 'client/build'), options));
  // app.use(express.static(path.join(__dirname, 'client/build'), {'Cache-Control': 'client/build, max-age=31536000'}));
  // Handle React routing, return all requests to React app
  app.get('*', function (req, res) {
    // res.sendFile(path.join(__dirname, 'client/build', 'index.html'), {'Cache-Control': 'no-cache'});
    // res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
    res.sendFile(path.join(__dirname, 'client/build', 'index.html'), indexOptions);
  });
}

I am not getting any errors, it's just not setting any of them on either index or other files.

1 Answers

I would check whether you have NODE_ENV set to production in your deployment, either by disabling the env check or console logging your env vars when the code is deployed. For what it's worth, I usually check for NODE_ENV !== 'development' as opposed to checking for production for a few reasons. Many build pipelines, like create-react-app, will strip the dev only code when building your code. Additionally, NODE_ENV = 'production' isn't necessarily set in production so you have to make sure whatever you're deploying to sets it.

Related