Renewing/Refreshing Express Session

gcc picture gcc · Aug 9, 2015 · Viewed 13.1k times · Source

In my app I restrict some access to some actions and pages if a user is not logged in. I have:

var restrict = function(req, res, next) {
    if (!req.user) {
      console.log("USER isn't logged in.")
      return res.status(403).send('Access or action denied, please log in'); 
    }
    next();
}


app.get('/stocks', restrict, MainHandler.findAllStocksFromUser);
app.get('/stocks/:id', MainHandler.findStockByIdAndDates);
app.put('/stocks/:id/stockActions', restrict, MainHandler.handleStockAction);

I'm essentially trying to refresh a session everytime the client makes a request to the server so that the server doesn't logout the user/destroy the session when it shouldn't. For testing, I want the session to expire/the user to be logged out if 20 seconds go by without the user making an requests to the server. I have:

    app.use(session({secret: 'secret', saveUninitialized: true, resave: true, expires: new Date(Date.now() + (20000))}));

Then I try to use middleware to refresh the expiration date every time the use makes a request:

// Session-persisted message middleware
app.use(function(req, res, next){
  req.session.cookie.expires = new Date(Date.now() + 20000);
  next();
});

But if I log in from the client, and click around, causing requests to the server, I still get the log-in error on the client after 20 seconds, despite trying to "refresh" the session in the middleware. I have also tried using maxAge using the same strategy with the middleware. Any ideas? Thanks!

Answer

TheLovelySausage picture TheLovelySausage · May 12, 2017

You can try define your session as follows

app.use (
   session ({
      secret: "secret",
      saveUninitialized: true,
      resave: true,
      cookie: {
         expires: 20 * 1000
      }
   })
);

and then refresh the session using

req.session.touch()

or you could define your session as

app.use (
   session ({
      secret: "secret",
      saveUninitialized: false,
      resave: true,
      rolling: true,
      cookie: {
         expires: 20 * 1000
      }
   })
);

and it will renew the session automatically and it will only expire when it has been idle for the value in the expires variable