node express session connect.sid cookie is ignored if inmemory store is used

kiran
2 min readApr 4, 2021

node session library gotchas and cross origin requests

Photo by Mae Mu on Unsplash

In one of my personal projects, I wanted to use a session library with very basic functionality.

It has to handle the cookie header setting and parsing part and provide a session id.No session store was needed as is.

express-session

I tested express-session, but it needed a session store(not the default inmemory store) for it maintain a users session properly across server restarts.Even if the request header has a session cookie, after a server restart express session would ignore the cookie and create a new session id for that request if inmemory store was used.

Also in my local setup, the web and the api were running on different ports i.e vue app and node api.So when the api sends the cookie header, the browser would only save the cookies when origin and credentials were set true in cors express middleware.Check this and this.

XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.

cookie-session

This was fine for my use case, just set a unique id for every user without a session cookie and get the same id if the request header already has the cookie.This is all done by the cookie-session module.Any properties added to the req.session are serialized and sent as a cookie and decoded from the request header for every request.

In cookie-session, you have to atleast add something to req.session to trigger set-cookie header.This is also true for express-session.

--

--

kiran

I am a software engineer by profession. I write so as to remind my selves when I forget :-)