How to access Cookie set with Passport.js How to access Cookie set with Passport.js node.js node.js

How to access Cookie set with Passport.js


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


Add to signin path

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

Add to signout path

res.clearCookie('userid');


The answer by user1071182 is correct, but doesn't make clear where to place the cookie-setting code.

Here is a fuller example:

app.get("/auth/google/callback",    passport.authenticate("google"),    setUserIDResponseCookie,    (req, res, next)=>{        // if success        if (req.user) {            res.redirect("http://localhost:3000");        } else {            res.redirect("http://localhost:3000/login-failed");        }        next();    });function setUserIDResponseCookie(req, res, next) {    // if user-id cookie is out of date, update it    if (req.user?.id != req.cookies["myapp-userid"]) {        // if user successfully signed in, store user-id in cookie        if (req.user) {            res.cookie("myapp-userid", req.user.id, {                // expire in year 9999 (from: https://stackoverflow.com/a/28289961)                expires: new Date(253402300000000),                httpOnly: false, // allows JS code to access it            });        } else {            res.clearCookie("myapp-userid");        }    }    next();}

Note: Make sure to:

  1. Add the shown handler to the authXXX/callback route, not the authXXX route.
  2. Call passport.authenticate "plainly", ie. without the redirect options. If you set the redirect options there, the cookies will not be set properly (from what I remember). Instead, add custom redirect code after the cookies have been set. (as shown above)
  3. If you have a "sign out" route, add the handler above to that route as well.