Express-Session not working on production when on Incognito Mode

Viewed 47

I am using express-session to handle user sessions. The problem is when I'm on incognito mode in production it doesn't work. I use heroku to deploy my node js application.

On localhost I use this and it works on both normal and incognito mode.

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    store: store,
    cookie: {
      maxAge: 1000 * 60 * 60 * 100,
    },
  })
);

But once deployed, I use the code below since the top doesn't work on production and doesn't set the cookie. Now this works and sets the cookie but not on incognito mode.

app.use(   session({
    store: store,
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    proxy: true, 
    cookie: {
      secure: true,
      maxAge: 1000 * 60 * 60 * 48,
      sameSite: "none",
    },   }) );

I found a similar problem but has no answers: Express Session is not working in production on incognito mode but everything working fine locally

EDIT

After hours of searching. I think this problem has something to do with how heroku handles cookies if sent from a different from a different domain eg: www.my-front-end.netlify.app requests api from www.my-heroku-backend.app If someone on incognito allows third party cookies, then the problem will be solved. I may be wrong please feel free to correct me. Thanks everyone. For more info check: https://devcenter.heroku.com/articles/cookies-and-herokuapp-com

TLDR: Heroku sends third party cookies. Incognito blocks third party cookies thus the error is created.

1 Answers

In my understanding, express session will be like a map stored inside the express instance running context.. Every request will be validated against the existence of an entry in that map.. In local you are running a single instance of express server...

That may not be the case in heroku instance.. there should be multiple instances of your express server running behind the proxy.

So.. your session creation request posted to instance_1 and it responded back with a cookie to refer an entry it's internal session map..

And further request got forwarded by the proxy to a different express instance say instance_2 which doesn't know anything about the session created inside instance_1.

So it returns 401 and makes your session inconsistent.

There are ways to store db in a common DBs.like an external mongo.

Please google and Try that..

Related