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
});

I had this problem as well, with a returned user from mongoose, just add toJSON() or toObject() will fix the issue, but what happens if your user is not always coming from mongoose?

You will get a

user.toJson/user.ToObject is not a function

if you try to do this on a plain object.

If your user is coming from different sources and you don't know if it will be a plain object or not, you can solve it like this:

JSON.parse(JSON.stringify(user));