How it is possible to setup a cach-controll policy in express.js on json response? My json response does'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.
The inelegant way is to simply add a call to res.setHeader()
prior to any JSON output. There, you can specify to set the cache control header and it will cache accordingly.
res.setHeader('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.JSONResponce= { 'hello': 'world' };
next(); // important!
});
// ...
// Before your error handling middleware:
app.use(function (req, res, next) {
if (! ('JSONResponce' in res) ) {
return next();
}
res.setHeader('Cache-Control', 'public, max-age=31557600');
res.json(res.JSONResponce);
})