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.
Try something like: app. use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) );
saveUninitialized : When an empty session object is created and no properties are set, it is the uninitialized state. So, setting saveUninitialized to false will not save the session if it is not modified. The default value of both resave and saveUninitialized is true, but using the default is deprecated.
var cookieSession = require('cookie-session') var express = require('express') var app = express() app. use(cookieSession({ name: 'session', keys: ['key1', 'key2'] })) // Update a value in the cookie so that the set-cookie will be sent. // Only changes every minute so that it's not sent with every request. app.
Here, since sess is global, the session won't work for multiple users as the server will create the same session for all the users. This can be solved by using what is called a session store. We have to store every session in the store so that each one will belong to only a single user.
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
})
}))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With