I am trying to set a cookie to store session using express-session. I am sending requests over HTTPS.
app.use(session({
secret: env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: true, // Ensure secure is set to true for HTTPS
sameSite: 'none', // Required for cross-origin cookies
httpOnly: true,
maxAge: 60 * 60 * 1000 // 1 hour
},
rolling: true,
store: MongoStore.create({
mongoUrl: env.MONGODB_CONNECTION_STRING
})
}));
If I only put:
cookie: {
httpOnly: true,
maxAge: 60 * 60 * 1000 // 1 hour
},
Then the cookie is received at the browser but it is not working because it is coming from https and cross origin. If I put:
cookie: {
secure: true, // Ensure secure is set to true for HTTPS
sameSite: 'none', // Required for cross-origin cookies
httpOnly: true,
maxAge: 60 * 60 * 1000 // 1 hour
},
Then the cookie is not received at the front end at all. I have deployed frontend and backend both at Vercel.
I tried to put secure: true, sameSite: 'none', in the cookie but then the cookie is not received at the frontend at all.
The issue has been resolved by setting proxy trusted.
app.set('trust proxy', 1) // trust first proxy
Mohit Sharma has confirmed the same in his comments.
Citation: