Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 775
Cyril Gaillard Avatar asked Dec 05 '22 10:12

Cyril Gaillard


2 Answers

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 },
}))
like image 179
Robert Moskal Avatar answered Mar 02 '23 01:03

Robert Moskal


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

like image 38
Dan Kohn Avatar answered Mar 01 '23 23:03

Dan Kohn