Search code examples
javascriptnext.jsjwthasura

Getting the error "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')" in jsonwebtoken code


I am getting the error "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')" in my console and i need help to solve it.

Here is my code

import { mAdmin } from "../../library/magic-server";
import { jwt } from "jsonwebtoken";

export default async function login(req, res) {
    
  if (req.method === "POST") {
    try {
      const auth = req.headers.authorization;
      const didToken = auth ? auth.substr(7) : "";
      console.log({ didToken });

      const metadata = await mAdmin.users.getMetadataByToken(didToken);
      console.log({ metadata });

      const token = jwt.sign(
        {
          ...metadata,
          iat: Math.floor(Date.now() / 1000),
          exp: Math.floor(Date.now() / 1000 + 7 * 24 * 60 * 60),
          "https://hasura.io/jwt/claims": {
            "x-hasura-allowed-roles": ["user", "admin"],
            "x-hasura-default-role": "user",
             "x-hasura-user-id": `${metadata.issuer}`,
          },
        },
        '<my secret key>',
        { algorithm: 'HS256' },
        function(err, token){
            console.log(token);
            console.error(err);
        }
      );

      console.log({ token });

      res.send({ done: true });
    } catch (error) {
      console.error("something went wrong logging in", error);
      res.status(500).send({ done: false });
    }
  } else {
    res.send({ done: false });
  }
}

Using postman, i posted an authorization with token to localhost:3000/api/login. In the console, I am able to log metadata and didToken so it seems the problem is in the jwt line.

Also the console said "at login (webpack-internal:///(api)/./pages/api/login.js:22:74)" below the error but there isn't a 74th letter in line 22nd.


Solution

  • you dont need curly braces here:

    import { jwt } from "jsonwebtoken";
    

    Try making it:

    import  jwt  from "jsonwebtoken";