Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Expected "payload" to be a plain object" when signing a jwt token

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading