Cookie not saving on client device when using secure: true

26 Views Asked by At

I am using express-session middleware to maintain session but on using secure: true cookie does not create on client device while it does on server side. The protocol is https. So I believe the cookie should be created.

app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({
      mongoUrl: process.env.DATABASE_URL,
      dbName: 'siteData',
      touchAfter: 24 * 3600, // time period in seconds
      autoRemove: "interval",
      autoRemoveInterval: 10,
    }),
    cookie: {
      name: 'Session',
      maxAge: 2 * 24 * 60 * 60 * 1000,
      secure: !(process.env.NODE_ENV !== 'production'),
      path: '/'
    },
  })
);

Any solutions are welcome. I don't want the client credentials to breached at any cost

1

There are 1 best solutions below

0
Shivansh Kothari On BEST ANSWER

Just found the answer through this thread. Brilliant answer by @dgreisen. The problem was solved by adding proxy: true to the code.

    app.use(
      session({
        secret: process.env.SESSION_SECRET,
        proxy: true,
        resave: false,
        saveUninitialized: false,
        store: MongoStore.create({
          mongoUrl: process.env.DATABASE_URL,
          dbName: 'siteData',
          touchAfter: 24 * 3600, // time period in seconds
          autoRemove: "interval",
          autoRemoveInterval: 10,
        }),
        cookie: {
          name: 'Session',
          maxAge: 2 * 24 * 60 * 60 * 1000,
          secure: true,
          path: '/'
        },
      })
    );

P.S. app.set('trust-proxy', 1); did not work for whatever reason