How to setup Redis for sessions on an Expressjs application

Bahadir Balban

Buzz Founder

@saasboxengineering

(source: redis.io) Redis is a trademark of redis labs

Here is how you do it:

var redis_config = config.redis;
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require('redis');
var client = redis.createClient(redis_config.port, redis_config.host);
// These 3 has to be declared in this order or
// your sessions will fail and you won't know why! :)
app.use(session({
    store: new RedisStore({
      host: redis_config.host,
      port: redis_config.port,
      client: client,
      logErrors: true,
    }),
    secret: 'your-secret-goes-here',
    maxAge: Date.now() + (15 * 86400 * 1000),
    saveUninitialized: false,
    resave: false,
    secure: false,
}));

app.use(passport.initialize());
app.use(passport.session());

Note the order of app.use() statements for session and passportJS initialization.

As you may see, Redis usually only needs a hostname and port for establishing a connection.




Join The Discussion