51

How it is possible to set up a cache-control policy in express.js on JSON response?

My JSON response doesn't change at all, so I want to cache it aggressively.

I found how to do caching on static files but can't find how to make it on dynamic data.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
Sayat Satybald
  • 6,300
  • 5
  • 35
  • 52

3 Answers3

80

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

Jason
  • 955
  • 9
  • 9
7

You can do it like this, for example :

res.set('Cache-Control', 'public, max-age=31557600, s-maxage=31557600'); // 1 year
akmozo
  • 9,829
  • 3
  • 28
  • 44
  • 16
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Clijsters Mar 09 '18 at 13:02
0

I had the same question recently, what worked for me was to do the following:

const express = require('express');
const app = express();
const port = 3000;
let options = {
  maxAge: '2y',
  etag: false
}

app.use(express.static('public', options));

Basically with maxAge you set your cache time. Documentation: https://expressjs.com/en/starter/static-files.html

JMag
  • 110
  • 2
  • 9