I am currently learning the MERN stack and working on a small project that requires me to have some session data that can persist between routes.
It works as intended, but whenever I go to an incorrect route or go back to the landing page and log the session id console.log(req.session.id)
It is different every time.
So I did some digging, and from some previous stackoverflow posts, session not persisting when using secure cookie in NodeJS with express-session, Setting the cookie: { secure: false }
while testing on http seems to solve my problem. The session id and by extension the session data persists.
I want to know why setting cookie: { secure: false }
in the express session options allows the session id and data to persist, and not having it does not.
Here is my session options
server.use(session({
secret: 'sxexsxsxixoxn',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}))
CodePudding user response:
If you set cookie: {secure: true}
, the cookie will only be set over an https connection, and not over an http connection. See also here.
So if you only have an http server, you must set cookie: {secure: false}
, otherwise no cookies will be set and session handling will not work.