Home > Back-end >  "Expected "payload" to be a plain object" when signing a jwt token
"Expected "payload" to be a plain object" when signing a jwt token

Time:07-22

This is the error

apis_1      | Error: Expected "payload" to be a plain object.
apis_1      |     at validate (/lens-apis/node_modules/jsonwebtoken/sign.js:40:11)
apis_1      |     at validatePayload (/lens-apis/node_modules/jsonwebtoken/sign.js:62:10)
apis_1      |     at Object.module.exports [as sign] (/lens-apis/node_modules/jsonwebtoken/sign.js:114:7)
apis_1      |     at /lens-apis/dist/org/signup/signup.route.js:115:37
apis_1      |     at Generator.next (<anonymous>)
apis_1      |     at fulfilled (/lens-apis/dist/org/signup/signup.route.js:5:58)
apis_1      |     at processTicksAndRejections (internal/process/task_queues.js:95:5)

this is the code

        if (!user) {
          return h.response({
            message: "User does not exist",
          });
        } else if (!upassword) {
          return h.response({
            message: "Your Password is incorrect",
          });
        } else {
          let token = jwt.sign(user, process.env.JWT_SECRET, {
            expiresIn: "1h",
          });
          if (!token) {
            console.log("token not found");
          }
          return h.response({
            message: "you have successfully logged in",
            token: `${token}`,
          });
        }

I am trying to get jwt token to access other routes, I am working in node typescript Hapi and docker

Answer to Phil's Question, User is schema or model for sql database and findOne I am not sure as well because this code was already built and the framework i am using is Hapi.js

 import { ServerRoute } from "@hapi/hapi";
import Joi, { options } from "joi";
import { ISignup, IsLogin } from "./signup.types";
import firebase from "firebase-admin";
import { User } from "../../user/user.model";
import { Org } from "../org.model";

CodePudding user response:

jsonwebtoken expects the first argument to be a plain object.

If it is a database document, deconstruct the required data into a plain object.

let token = jwt.sign({ name: user.name }, process.env.JWT_SECRET, {
   expiresIn: "1h",
});

JSON.parse(JSON.stringify(user)) might also work to convert the whole object.

  • Related