Renewing/Refreshing Express Session
Asked Answered
G

2

10

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!

Gradatim answered 9/8, 2015 at 20:4 Comment(1)
You could try to use github.com/expressjs/session#sessionregenerateNucleus
P
12

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

Picco answered 12/5, 2017 at 10:48 Comment(0)
S
6

express-session supports a duration-based maxAge setting, which will work better than setting a fixed date for all sessions. So your middleware usage should instead look like:

app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true,
  maxAge: 20000
}));

Next, to update the expiration of the session, you can just call req.session.touch(); if that is all you're doing to the session and its contents.

The documentation has a lot of other good information on controlling session expiration and related topics.

Savage answered 9/8, 2015 at 21:3 Comment(3)
This isn't working for me. If i print req.session.maxAge to the console on each request I get 'undefined'. So I tried doing app.use(session({secret: 'secret', saveUninitialized: true, resave: true, cookie: {maxAge: 20000}})); instead and req.session.touch() isn't seeming to work because the session still stops after 20 seconds regardless of how many requests I makeGradatim
@Gradatim Did you get any solutions to this??Petticoat
I think you have to use req.session.cookie.maxAgeBandoleer

© 2022 - 2024 — McMap. All rights reserved.