Sayat Satybald
Sayat Satybald

Reputation: 6580

Cache Control for Dynamic Data Express.JS

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.

Upvotes: 51

Views: 75636

Answers (3)

JMag
JMag

Reputation: 120

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

Upvotes: 0

Bằng Nguyễn Hữu
Bằng Nguyễn Hữu

Reputation: 99

You can do it like this, for example :

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

Upvotes: 8

Jason
Jason

Reputation: 965

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

Upvotes: 81

Related Questions