Reputation: 3
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.
Upvotes: 0
Views: 140
Reputation: 5
For Development:
cookie: {
httpOnly: true
}
For Production:
cookie:{
http:false,
secure: true
}
If a cookie is set with the secure
flag, it will only be sent to the server by the browser over https
, and not plain http
. This should for production environments.
However, when developing an app, you will use plain http
. If you set your session cookie as secure in this case (using plain http), the server will never receive it, and you will experience a new empty session on each request.
So in short, you should only set the cookie as secure if you are using https and httpOnly if you are using http.
Upvotes: 0
Reputation: 1954
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:
Upvotes: 0