Storing data in the session state is a little bit naughty as HTTP should remain stateless but there is a trade-off. In this case I wanted to test an assumption around a potential feature for Mayday. I felt it was more important to release than over architecture the entire solution with the possibility of dropping the feature the next day.
When it comes to Node.js, session state is stored in-memory meaning any restarts or new deployments will delete the data.
Enter Redis
Redis is an ultra-fast, open source, advanced key-value store. To make it even easier, RedisToGo offer a hosted version with a Heroku plugin. After adding the plugin, an account will be created with a database URL provided as a configuration variable.
$ heroku config
REDISTOGO_URL => redis://redistogo:[email protected]:9712/
NODE_ENV => production
To use this as your session store you will need to configure the middleware by defining a RedisStore from the connect-redis npm.
The require statements should look like this:
var express = require(‘express’);
var RedisStore = require(‘connect-redis’)(express);
var url = require(‘url’)
For development you will want to use your local server.
app.configure(‘development’, function(){
app.use(express.session({ secret: “password”,
store: new RedisStore({
host: “127.0.0.1”,
port: “6379”,
db: “name_of_my_local_db”
})
}));
});
For production you should use the RedisToGo URL provided.
app.configure(‘production’, function(){
var redisUrl = url.parse(process.env.REDISTOGO_URL);
var redisAuth = redisUrl.auth.split(‘:’);
app.use(express.session({ secret: “password”,
store: new RedisStore({
host: redisUrl.hostname,
port: redisUrl.port,
db: redisAuth[0],
pass: redisAuth[1]
})
}));
});
Node.js and Connect-Redis will do the rest for you.
The key will be the session id for the user with the value being a JSON serialised object of req.session.
Hello, now you can use https://github.com/cmanzana/heroku-redis-client too :).