Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node+Passport.js + Sessions + multiple servers

Passport is great. I now discovered that I have some problem with how it handles sessions. I must be using it wrong.

All works well for me with login + sessions + user data I store in my database. However I find that when I move to production environment (cloud on EC2 with multiple servers), I lose the login session each time. This is now clear to me - probably happens since the session is unique to each server.

So my question is - how do I get around this.. I guess I will need to store my own cookie on the user's browser?

Does this mean that I cannot use express.session at all?

Thanks, Ilan

like image 642
Ilan lewin Avatar asked Jan 10 '23 17:01

Ilan lewin


1 Answers

OK, So basically what I was looking for (not sure it would be the same answer for everyone else) was a way to store session data between loadbalanced instances without making a DB call for every page view, which seems excessive to me, since I just need to keep the user signed in to Google/FB.

It seems that the answer I was looking for was the cookie-session middleware https://github.com/expressjs/cookie-session

This needs to replace the default express.session mechanism which uses MemoryStore. BTW MemoryStore itself gives you a warning when run that it will not scale past a single process, and also that it may cause a memory leak.

Which if I understand correctly is serializing the session data itself into the session cookie (encrypted) instead of just using a session ID in the session cookie. This seems perfect to me. Obviously I don't expect it to work if you have a lot of session data, since a cookie is limited in size. In my case, I just needed the name, ID and avatar url, so I think this will suffice. Thanks for everyone who helped.

like image 52
Ilan lewin Avatar answered Jan 22 '23 06:01

Ilan lewin