I have read a few assorted comments on how installing a persistant storage solution for sessions ( for a Node/Express setup) seems like a bit of overkill for small scale websites, (redis, mongo, ect.).
Besides persistance, I could only find garbage collection of old sessions to be a reason not to use Memory Store in a production website... (ie. I close my browser, but the session is still stored in Memory Store on the server)
I threw in something like this simple garbage collector to address the issue:
var sessionGarbageCollector = function(req, res, next) {
// Set a session lifetime (Renewed each time this is called)
var now = new Date();
var expirydate = now.getime();
expirydate += 60000; // Some Session lifespan
req.session.LifeTime = expirydate;
req.session.sessionID = req.sessionID; // Make session ID accessible inside session
// Loop through all sessions and check for expired sessions
for ( var x in req.sessionStore.sessions ) {
req.sessionStore.get(x, function(err,sessionObj) {
if ( sessionObj.LifeTime ) {
if ( now.getTime() > sessionObj.LifeTime ) {
console.log("Removing Expired Sesson: " + sessionObj.sessionID);
req.sessionStore.destroy(sessionObj.sessionID, function(err,data) { } );
}
}
});
}
next();
}
I then included the following, to run it on every request- so each time somebody requests a page, the garbage collector checks to see if any sessions should be removed:
app.use(sessionGarbageCollector);
Now probably, I don't want to call this every time, but only on requests after maybe 10 minutes goes by, or some interval... but this is close enough to what I'm going for. ( For 'keep me logged in' sessions, I overwrite the session key cookie's 'session only' status on the client, and set a specific expiry date- with a matching expiry in the session with req.session.LifeTime, so you get the preserved session... well, if no one reboots the server that is ... )
I would like to know what other problems there are with this approach that I'm not seeing? (ie. besides garbage collection, what other limitations are there with Memory Store)
What have been other people's experience with it? Maybe somebody else has tried this sort of thing?
I don't see how using an external memory store is overkill. They are a perfect fit for handling sessions. For example, Redis is a key/value store where values have a Time To Live so that you don't have to worry about memory management and the likes. TJ Holowaychuk made a neat memory store that uses Redis as backend: connect-redis
So you need to: 1) Install Redis (takes 5 minutes tops and the default config is fine if your server's firewall is up which should be the case) 2) Install connect-redis and use it as session store with Connect's or Express' session middleware 3) Profit. And an added benefit is that Redis can also be used as message provider between your Express app and the other components of your system. Pretty handy.