I have an API that can be called either using a browser where requests are transactional and have a session OR directly, eg. using curl, where requests are atomic. Browser reque
An alternative approach to reducing the amount of sessions stored in your session storage is to set a default maxAge to something low. Then, when you actually need sessions stored longer, like after a user logins, you can set req.session.cookie.expires = null;
. Also don't forget to set the session expiration to something low when the user logs out.
Here's an example:
// set default to something low
app.use(session({
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 5 * 60 * 1000 // 5 minutes
},
secret: secrets.sessionSecret,
store: new MongoStore({
url: yourUrl,
auto_reconnect: true
})
}));
// on successful login,
// set expiration to null or something longer than default
var time = 14 * 24 * 3600000; //2 weeks
req.session.cookie.maxAge = time;
req.session.cookie.expires = new Date(Date.now() + time);
req.session.touch();
// on logout, reset expiration to something low
var time = 5 * 60 * 1000; // 5 minutes
req.session.cookie.maxAge = time; //2 weeks
req.session.cookie.expires = new Date(Date.now() + time);
req.session.touch();
This is particularly useful when remote monitoring your app because if the monitoring is frequent enough, the sessions will fill up fast.