How to disable webpage caching in ExpressJS + NodeJS?

前端 未结 3 1710
心在旅途
心在旅途 2020-12-10 12:35

By default, my browser caches webpages of my ExpressJS app.

This is causing a problem to my login system (users not logged in can open old cached pages of logged in

相关标签:
3条回答
  • 2020-12-10 13:27

    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.

    0 讨论(0)
  • 2020-12-10 13:30
    app.disable('view cache');
    

    ^^ Code for ExpressJS

    0 讨论(0)
  • 2020-12-10 13:36

    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 middleware
    app.use((req, res, next) => {
        // listen for the headers event
        onHeaders(res, () => {
            this.removeHeader('ETag');
        });
    });
    
    0 讨论(0)
提交回复
热议问题