Sails.js + Passport.js : req.user undefined

Sails.js is a popular express based MVC framework that has been gaining popularity these past few years. Passport.js is used for user authentication purposes.

Recently, i was working on one of my projects that involved these two and i came upon a very weird issue which took me a few hours to figure out and was worthy of a blog post.

So, i was using Passport with LocalStrategy for basic Mongo-store based authentication. The api was working fine and sessions were being stored in the database just fine.

But when i connected the api to my Angular frontend, the session data seemed to be inconsistent and the logged in user wouldn’t show up on frontend. So went through all my sails config files and made sure everything was setup properly.

My first thought was that maybe the CORS settings were causing problems and sure enough, i had to setup the sails server to allow origins and headers in the sails.config.cors:

Bear in mind though that the CORS setting for origin should not be this open-ended on a live server, so you might wanna change that.

After restarting the server i realized that the calls were going through but the req.user still shows up as undefined. After doing some digging i saw that the session data was being stored in Mongo and the cookie data was being returned on get calls as well. But the cookie data was not being sent to the server which was forcing it to create a new session on every call.

So you can see that in the CORS settings, the API accepts credentials but my frontend was not sending any,  which was the root cause. Then I updated my GET and POST HTTP call code to send credentials as well:

And that is how the req.user popped back up on my console screen and i was more than relieved 🙂 I hope this helped someone else out there.



Application developer, movie buff, occasional reader and a huge Manchester United fan.