Search code examples
expresscookiessession-cookies

Why wouldn't express-session work when cookie is set to secure?


Why does this work:

router.use(session({
  name: process.env.SESSION_COOKIE,
  genid: () => uuidv4(),
  cookie: {
    httpOnly: true,
  },
  secret: process.env.SESSION_SECRET,
  store: new RedisStore({
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT,
    ttl: 1 * 24 * 60 * 60, // In seconds
  }),
  saveUninitialized: false,
  resave: false,
}));

But this doesn't?

router.use(session({
  name: process.env.SESSION_COOKIE,
  genid: () => uuidv4(),
  cookie: {
    httpOnly: true,
    secure: true,
  },
  secret: process.env.SESSION_SECRET,
  store: new RedisStore({
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT,
    ttl: 1 * 24 * 60 * 60, // In seconds
  }),
  saveUninitialized: false,
  resave: false,
}));

Setting secure to true results in the session cookie not being set at all. FWIW, I'm using PassportJS for authentication.

NOTE: This question might look similar to this one but the top-voted answer there doesn't quite address the issue. It says httpOnly is causing the problem but I don't understand why it would? The cookie isn't being set on the client, right?

The file in question is up at https://github.com/amitschandillia/proost/blob/master/web/routes/auth-routes.js.

NOTE 2: The server is SSL-enabled and the URL is https://www.schandillia.com.


Solution

  • The secure option for a cookie means that the cookie is ONLY sent by the browser over an https connection and, in some browsers, the cookie marked as "secure" won't even be saved by the browser for future requests if it arrives over an insecure connection.

    Your server appears to be an http server so the cookie will not be sent back to your server on subsequent requests making the cookie disappear.