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.
The private response directive indicates that the response can be stored only in a private cache (e.g. local caches in browsers). You should add the private directive for user-personalized content, especially for responses received after login and for sessions managed via cookies.
It is unmaintained Express has not been updated for years, and its next version has been in alpha for 6 years. People may think it is not updated because the API is stable and does not need change. The reality is: Express does not know how to handle async/await .
I found how to do caching on static files but can't find how to make it on dynamic data. Show activity on this post. 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.
Setting cache control middleware in Express The simplest middleware to set cache-controlwould be to set the cache header for the entire application as follows: app.use(function(req, res, next) { res.set('Cache-control', 'public, max-age=300') })
Cache headers in Express js app Effective implementation of caching strategy can significantly improve resilience of your Express app and save cost. When you implement the right caching strategies combined with a content delivery network (CDN) your website can serve massive spikes in traffic without significant increase in the server load.
Cache headers intro The http header Cache-controlallows to define how your proxy server (e.g. Nginx), your CDN and client browsers will cache content and serve it instead of forwarding requests to the app. You can find the full specification of Cache-controlat MDN.
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
You can do it like this, for example :
res.set('Cache-Control', 'public, max-age=31557600, s-maxage=31557600'); // 1 year
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With