Payload error in jsonwebtoken

It fails at the line

const token = jwt.sign(user, config.secret, {

With error “Expected “payload” to be a plain object”

Your user object is initialized here:

User.getUserByUsername(username, (err, user)

Which I assume is mongoosejs object, which contains many methods and is not “serializable”. You could handle this by passing a plain object, by either using .lean() from mongoose or plain toJSON method:

const token = jwt.sign(user.toJSON(), config.secret, {
  expiresIn: 604800 // 1 week
});

Leave a Comment