Reputation: 2987
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.
Upvotes: 13
Views: 13005
Reputation: 35
in my case only updating the following property worked!
req.session._expires
I'm still not entirely sure why ...
I'm using "express-session": "^1.17.3",
My code use:
req.session._expires = new Date(Date.now() + (process.env.MAX_SESSION_TIME >> 0))
Upvotes: 0
Reputation: 1181
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
})
}))
Upvotes: 28
Reputation: 76444
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)
Upvotes: 6