How to disable webpage caching in ExpressJS + NodeJS?
nocache
Don't waste your time reinventing the wheel, use the nocache middleware.
Install it:
npm install --save nocache
Then add it to you app:
const nocache = require('nocache');app.use(nocache());
It works in an easy way (from the doc):
This sets four headers, disabling a lot of browser caching:
- Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
- Pragma: no-cache
- Expires: 0
- Surrogate-Control: no-store
Etag
Beware of ETags: this header isn't removed using the middleware above, because it works in a different way. It's generated at the end of the request, so you have two choices.
app.set
Disabling it using express builtin app.set('etag', false);
method
on-headers
Removing the header just before it is sent to the client using the on-headers module:
const onHeaders = require('on-headers');// install it as a middlewareapp.use((req, res, next) => { // listen for the headers event onHeaders(res, () => { this.removeHeader('ETag'); });});
There are two things to consider when dealing with cache in Express.js - ETag
and Cache-Control
headers.
ETag (MDN reference)
If you have dynamic content which does not benefit from ETags, it's best to disable it because it incurs small overhead with each request.
app.set('etag', false)
Cache-Control (MDN reference)
To completely disable cache, use the following header:
app.use((req, res, next) => { res.set('Cache-Control', 'no-store') next()})
This header does not affect express.static()
middleware. It handles cache in its own way.