Cache Control for Dynamic Data Express.JS

The inelegant way is to simply add a call to res.set() prior to any JSON output. There, you can specify to set the cache control header and it will cache accordingly.

res.set('Cache-Control', 'public, max-age=31557600'); // one year

Another approach is to simply set a res property to your JSON response in a route then use fallback middleware (prior to the error handling) to render and send the JSON.

app.get('/something.json', function (req, res, next) {
  res.JSONResponse = { 'hello': 'world' };
  next(); // important! 
});

// ...

// Before your error handling middleware:

app.use(function (req, res, next) {
  if (! ('JSONResponse' in res) ) {
    return next();
  }

  res.set('Cache-Control', 'public, max-age=31557600');
  res.json(res.JSONResponse);
})

Edit: Changed from res.setHeader to res.set for Express v4

Leave a Comment