Express-session Secure Cookies not working

Justin Lok picture Justin Lok · May 18, 2017 · Viewed 8.6k times · Source

When not using secure cookie true setting, my app user login works fine. When I enable secure cookies, the login appears to go through fine, but it seems the cookie is not saved and the user is not logged in.

In other words, this works:

app = express();
app.use(session({
    secret: 'secret code',
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: false,
        maxAge: 5184000000 // 60 days
        }
}));

This does not work (user isn't able to log in):

app = express();
app.set('trust proxy');
app.use(session({
    secret: config.cookieSecret,
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    proxy: true,
    secureProxy: true,
    cookie: {
        secure: true,
        httpOnly: true,
        maxAge: 5184000000 // 60 days
        }
}));

Behind cloudflare and nginx. This is in my nginx config:

location ~ / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://localhost:3000;
}

From what I read, I think it should work. What am I missing?

EDIT: I am running https with a valid ssl cert.

Answer

Stoyan Berov picture Stoyan Berov · Feb 6, 2020

The combination of settings that worked for me:

  • Inside the nginx server configuration, add proxy_set_header X-Forwarded-Proto $scheme;
  • Inside the express-session configuration:

    server.use(
      session({
        proxy: true, // NODE_ENV === 'production'
        cookie: {
          secure: true, // NODE_ENV === 'production'
        },
        // everything else
      })
    );