5

I'm using express js 4 together with express-session and set maxAge to one hour. However if user continues accessing the website, the timeout should be extended otherwise the user will be logged out even he/she is still using it.

app.use(session({
  secret: 'xxx',
  name: 'sessionId',
  resave: true,
  saveUninitialized: true,
  cookie: {
    httpOnly: true,
    maxAge: 1*60*60*1000
  })
}))

It seems to be a common task but I can't find it anywhere. Thanks in advance.

Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148
Anurat Chapanond
  • 2,297
  • 1
  • 13
  • 21

2 Answers2

15

express-session has a rolling property that you can set. By default it's set to false. If you set the rolling property to true, it will reset expiration to maxAge.

I got the information from the documentation here

app.use(session({
  secret: 'xxx',
  name: 'sessionId',
  resave: true,
  saveUninitialized: true,
  rolling: true, // <-- Set `rolling` to `true`
  cookie: {
    httpOnly: true,
    maxAge: 1*60*60*1000
  })
}))
d_coder
  • 673
  • 7
  • 14
4

I think you could solve your problem by increasing maxAge each time the user sends a request. When the user sends a request, calculate the time remaining before the session times out, subtract this amount of time from one hour and add the result to maxAge. Alternatively you can use the expires property along with a very large maxAge:

var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = 100 * hour

and whenever a request is sent, calculate expires again:

var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)
Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148