Node.js passport-jwt how to send token in a cookie?

you should follow code:

user.comparePassword(req.body.password, function (err, isMatch) {
  if (isMatch && !err) {
    // Create token if the password matched and no error was thrown
    var claims = {
      sub: user._id,
      email:user.email,
      iss: 'https://NodeLogin.com',
      permissions: user.role
    };

    var token = jwt.sign(claims, config.secret, {
      expiresIn: 60 // in seconds
    });

    res.cookie('jwt',token); // add cookie here
    res.json({ success: true, token: 'JWT ' + token });
  } else {
    res.send({ success: false, message: 'Authentication failed. Passwords did not match.' });
  }
});

and passport config:

var cookieExtractor = function(req) {
  var token = null;
  if (req && req.cookies) token = req.cookies['jwt'];
  return token;
};
module.exports = function(passport) {  
  var opts = {};
  opts.jwtFromRequest = cookieExtractor; // check token in cookie
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.id}, function(err, user) {
      if (err) {
        return done(err, false);
      }
      if (user) {
        done(null, user);
      } else {
        done(null, false);
      }
    });
  }));
};

it's working for me :)


For httpOnly, signed, secure Cookies you might need to use signedCookies

const cookieExtractor = function (req) {
    let token = null;
    if (req && req.signedCookies && req.signedCookies.jwt) {
        token = req.signedCookies['jwt']['token'];
    }
    return token;
};