Pono Pono - 1 year ago 170
Node.js Question

Node.js and Express session handling - Back button problem

I have a restricted area '/dashboard' in my Express application. I use a very small function to limit the access:

app.get('/dashboard', loadUser, function(req, res){
res.render('dashboard', {
username: req.session.username

function loadUser(req, res, next){
if (req.session.auth) {
} else {

The problem is that when I logout a user by calling...

app.get('/logout', function(req, res){
if (req.session) {
req.session.auth = null;
req.session.destroy(function() {});

... the session is killed but when I hit Back Button in my browser I got the restricted page from browser's cache. This means no GET on '/dashboard' and no user login validation.

I tried using no-cache in meta (Jade Template) but it still doesn't work.

meta(http-equiv='Cache-Control', content='no-store, no-cache, must-revalidate')
meta(http-equiv='Pragma', content='no-cache')
meta(http-equiv='Expires', content='-1')


Answer Source

Josh's answer sadly didn't work for me. But after some searching I found this question: What's the best way to deal with cache and the browser back button?

and adopted the answer there to this node.js/express problem. You just have to change the following line

res.header('Cache-Control', 'no-cache');


res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');

Now, everytime I use the browser back button, the page is reloaded and not cached.

* update for express v4.x *

// caching disabled for every route
server.use(function(req, res, next) {
  res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');

// otherwise put the res.set() call into the route-handler you want
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download