Setting up sessions on express app on multiple dynos heroku app

I have implemented some user authentication on a single Heroku dyno using express (node.js)+ mongodb and everything is working fine. However, when I increase the number of dynos (more than 1), I cannot login, I keep being redirected on my login page, meaning my session hasn't been set. Here is my code:

checkCookies = function(req, res, next) {

  if(req.session.user){
   res.locals.user = req.session.user;
   next();
  }
  else{
    res.redirect('/login');
  }
};
app.use(express.cookieParser());
  app.use(express.session({ secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK',
  cookie: {httpOnly: true, maxAge:14*24*60*60*1000}
  }));

What is the best solution to handle shared session on express/node.js using mongodb?

Use connect-mongo module with express.

var http    = require('http'),
    express = require('express'),
    session = require('connect-mongo')(express)

And then in your workers setup session to store externally. Code below will use session from mongo, cookies and extra headers in order to allow cross-domain and jsonp.

app.configure(function() {
  app.use(express.cookieParser());
  app.use(express.session({
    store: new session({
      db: 'sessions'
    }),
    secret: 'yoursecret',
    cookie: {
      path: '/',
      maxAge: 1000 * 60 * 60 * 24 // 1 day
    }
  }));
  app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
  });
  app.set('jsonp callback', true);
});

connect-mongo should meet your needs: https://github.com/kcbanner/connect-mongo

The above answers are misleading in that they imply you can't share cookie based sessions across multiple dynos on Heroku.

I'm able to to use cookie based sessions across multiple dynos if I use cookie-session as opposed to express-session. What's missing from the first post in this thread is the secret value is NOT passed to the cookie parser. This means that node will assign a random hash to the parser each time the process restarts or when a new dyno spins up.

Doing the following works for me:

app.use(express.cookieParser('0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK'));
  app.use(express.session({ secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK',
  cookie: {httpOnly: true, maxAge:14*24*60*60*1000}
  }));