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?

Add to signin path

res.cookie('userid', user.id, { maxAge: 2592000000 });  // Expires in one month

Add to signout path

res.clearCookie('userid');

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/guide/configuration.html

If you're using the angular-fullstackgenerator, this is how I modified setUserCookie to get the _id in the user cookie (which I later can retrieve in AngularJS).

setUserCookie: function(req, res, next) {
    if (req.user) {
        req.user.userInfo['_id'] = req.user._id;
        console.log('Cookie', req.user.userInfo);
        // Splice in _id in cookie
        var userObjWithID = {
            "provider": req.user.userInfo.provider,
            "role": req.user.userInfo.role,
            "name": req.user.userInfo.name,
            "_id": req.user._id
        };
        res.cookie('user', JSON.stringify(userObjWithID));
    }
    next();
}