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

Issue

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.

Solution

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();
});

Answered By – laggingreflex

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published