Search code examples
node.jsexpresscookiesuser-managementsession-management

Why the browser caching my webpages eventhogh I used nocache middleware and handled sessions


I am a beginner working on a small user management project using NodeJS express. I did session handling and used nocache middleware on app level. When a user logs in, a session is created and when the user logs out the session is being destroyed, but still when I press the browser's previous page button after the user logs out, it goes back to the previous page of which the session was destroyed. Why is this happening and How do I solve this?

I tried nocache middleware on app level to prevent caching. When a user logs in I created a new session (like req.session.user = userData), and destroyed it when the user logs out.

req.session.destroy(function(err) {
        if(err) {
            console.log(err);
            res.send(err);
        }
        else {
            res.redirect("/login?logout=Logout Successfully...");
        }
    });

Solution

  • Going back to a previously visited page with the browser's "Back" button fetches the page from the back/forward cache. This is best compared to switching back to a previously viewed browser tab after doing something else on a different tab. In both cases, the browser makes no request to the server, that's why the absence of a session it not noticed.

    In earlier times, giving a page Cache-Control: no-store prevented it from entering the back/forward cache, but Google Chrome has recently changed this behavior.

    You can force a navigated-to page to show data only with an active session if you use the pageshow event as explained here. If you also want to cover the case of a tab switch, use the visibilitychange event as well.