Artem
Artem

Reputation: 17

How to disable caching for some routes in the Express 4 applications?

i tried these examples: Removing all headers from express.js this Disable etag Header in Express Node.js and this https://github.com/expressjs/express/issues/2472 but unfortunately they did not solve my problem. In Firefox, Opera and Chrome my app works fine when the developer tools are open and caching is disabled or when I start my app for the first time after browser was launched. I understand that this has to do with caching. Tell me please, how to disable caching for some routes in the Express application. Is it possible? Is there a general way to do this?

P.S. I was very surprised, but my Express app works perfectly in Internet Explorer 11

Upvotes: 1

Views: 3505

Answers (1)

Lafif Astahdziq
Lafif Astahdziq

Reputation: 3986

I think you can set the headers to force revalidate by setting the res such as

res.setHeader('Surrogate-Control', 'no-store');
res.setHeader(
  'Cache-Control',
  'no-store, no-cache, must-revalidate, proxy-revalidate'
);
res.setHeader('Expires', '0');

or maybe a bit tidier with middleware

const dontCache = (req, res, next) => {
  res.setHeader('Surrogate-Control', 'no-store');
  res.setHeader(
    'Cache-Control',
    'no-store, no-cache, must-revalidate, proxy-revalidate'
  );
  res.setHeader('Expires', '0');
  next();
};

app.get('/some-route', dontCache, async(req, res) => {
  ...
})

Upvotes: 1

Related Questions