MindBrain
MindBrain

Reputation: 7768

How to invalidate browser cache after logout from the node js application

I have developed an application in node js and express. I wish to invalidate the browser cache after the user logs out of the application . The main reason being that the user should not be able to see the earlier loaded page when he clicks on the back button.

Upvotes: 2

Views: 2960

Answers (3)

Nilotal_35
Nilotal_35

Reputation: 1

Below code works fine in chrome but in Safari it won't work.

//import nocache module

const nocache = require("nocache");

//create a middleware incentral place like app.js or index.js to register for all routes. that's it.

app.use(nocache());

Upvotes: 0

Abdul Suhaib
Abdul Suhaib

Reputation: 1

Using

 app.use((req, res, next) => {      
    res.set('Cache-Control', 'no-store')
    next() 
 })

in my app.js worked for me.

Upvotes: 0

laggingreflex
laggingreflex

Reputation: 34627

You can conditionally set the headers to never cache your page based on whether user is logged in or not.

This express middleware will do just that:

app.use(function(req, res, next) {
    if (!req.user) {
        res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
        res.header('Expires', '-1');
        res.header('Pragma', 'no-cache');
    }
    next();
});

Upvotes: 5

Related Questions