Lukas Olsen Lukas Olsen -3 years ago 149
Node.js Question

How to access Cookie set with Passport.js

I'm using Passport.js to achieve login to my Node-App. But in my app i need to get access to the user's ID and currently i don't have an idea how to achieve this thing!

How can i access the user-id or should i send it in a cookie myself?

Answer Source

You should introduce the following code in your app, next to the configuration of the strategies:

passport.serializeUser(function(user, done) {
   done(null, user.id);
});

passport.deserializeUser(function(obj, done) {
   done(null, obj);
});

In this way, when you invoke the done function with the authenticated user, passport takes care of storing the userId in a cookie. Whenever you want to access the userId you can find it in the request body. (in express req["user"]).

You can also develop the serializeUser function if you want to store other data in the session. I do it this way:

passport.serializeUser(function(user, done) {
   done(null, {
      id: user["id"],
      userName: user["userName"],
      email: user["email"]
   });
});

You can find more here: http://passportjs.org/docs/configure

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download