Encountering a login issue with the jsonwebtoken code, specifically getting the error message "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')."

I encountered an error in my console saying, "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')." I am seeking assistance in resolving this issue.

Below is the code snippet:

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

I made a POST request with an authorization token using Postman to localhost:3000/api/login. Metadata and didToken were successfully logged in the console, suggesting that the issue lies within the jwt line.

The console also displayed the message: "at login (webpack-internal:///(api)/./pages/api/login.js:22:74)" despite there not being a 74th character in line 22.

Answer №1

Avoid using curly brackets in this instance:

import { jwt } from "jsonwebtoken";

Consider changing it to:

import  jwt  from "jsonwebtoken";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with React Redux: Passing down a component's method to its children results in an undefined error

Currently, I am working on creating a todo list using React and Redux. In my code snippet provided below, there is a component that includes a function called onDeleteItem. The issue I am facing is the inability to pass the onDeleteItem function to the s ...

What is causing an empty box to appear due to padding? Is there a way to conceal it

There seems to be an issue with adding padding to the results id div box. The padding is causing a blank yellow box to appear at the bottom before any results are submitted. I've tried to hide this box without success by adding a displayResult() funct ...

Alternative method for displaying text in Discord

At the moment, my discord bot is set up to read from a file and post the new data in that file to a specific channel. I am interested in modifying the output so that any characters enclosed in ~~ are displayed as strikethrough text. const Bot = require( ...

Conceal or reveal radio buttons according to information in a table

How can I dynamically add and remove values from a table based on radio button selections? My goal is to add the selected value to the table and hide it from the radio button list, and if the value is deleted from the table, I want to show it back in the r ...

ajax is unable to decode a JSON string from a GET request

Currently, I am leveraging angularjs to retrieve userId, userTitle, and userComment from a form. These values are then sent to a PHP page from the controller for communication with a server. Everything works well when sending integers, but I face an issue ...

ReactJS encountered an error of type ERR_INVALID_ARG_TYPE

Hello there! I recently purchased a template from ThemeForest and everything was working perfectly with the previous version. However, upon updating to the new version, I encountered an error that looks like this: > TypeError [ERR_INVALID_ARG_TYPE]: Th ...

initiate scanning for HTTP GET calls

My current project involves using electron to create an application that serves multiple image files through a webserver using express. Another app built for Android is responsible for retrieving and posting files to this server. While I have successfully ...

Retrieve the Latest Information from the Asp.Table

My table setup is as follows: <asp:Table ID="model" runat='server'> <asp:TableRow> <asp:TableHeaderCell class="col-xs-2"> Name </asp:TableHeaderCell> <asp:TableHeaderCell class="col- ...

Novice in AngularJS routing

Having trouble with my first AngularJS routing code. The error console isn't much help. Here is my HTML page: <body ng-app="myApp"> <div ng-controller="AppController"> <div class="nav"> <ul> <li> ...

The outer DIV will envelop and grow taller in conjunction with the inner DIV

Could use a little help here. Thank you :) I'm having trouble figuring out how to get the outer div to wrap around the inner div and expand upwards with the content inside the inner editable div. The inner div should expand from bottom to top, and t ...

Identify client-side navigation using next/navigation in Next.js version 13 and above

Can you help me with a simple issue? I am trying to detect when users navigate within the app. Route changes are happening using the <Link> attribute from react/link. I have a context that needs to track all navigations so it can add a parameter to ...

Ways to center align text in a div vertically

I'm working with 2 divs that are floating side by side. The left div contains a part number, which is only one line. The right div holds the product description, which can span multiple lines. I am looking for a way to vertically align the text in t ...

Unusual occurrences when making several ajax requests to a single URL

I've encountered a peculiar scenario while working on a CherryPy server, and I'm seeking assistance in understanding the intricacies behind it. Here's the content of server.py: import cherrypy import os import threading class Root(object): ...

jQuery - harnessing the power of JavaScript events such as "dragover"

I have a JavaScript function that includes an event listener for 'dragover'. Here is the code snippet: document.getElementById("someID").addEventListener("dragover", function(){ //Add your logic here }, fa ...

Require assistance with try-catch statements

I am troubleshooting an issue with a try-catch block in my Protractor test. Take a look at the code snippet below: try { element(by.id('usernameas')).sendKeys(data); } catch(err) { console.log('error occurred'); } To test the ...

Is it possible to efficiently utilize Map/Set in TypeScript/JavaScript when working with objects?

I'm currently transitioning from Java to TypeScript and I've encountered an issue with working with objects in hashmaps and hashsets. In Java, I would simply override the hashCode method to easily manipulate these data structures. Is there a simi ...

Angular's Reactive forms: The power of bidirectional binding

Struggling with Reactive forms? I've encountered an issue where updating the model class when a User changes the input is easy, but what about programmatically changing the model and reflecting those changes in the HTML form? In simplified terms: th ...

Having trouble loading environment variables in NextJS on Heroku?

I am currently utilizing NextJS and deploying my application on Heroku. When the page initially loads, I am able to retrieve data through getInitialProps without any issues. However, when trying to access this data in a regular function, I encounter an er ...

What is the best way to retrieve the value of a nested function in JavaScript?

I am currently working on a project that involves a function. function findParentID(parentName) { Category.findOne({ categoryName: parentName }, function (err, foundParent) { var parentID = foundParent.categoryID;    return parentID;<br> } ...

Collecting numerous user-input data from dynamically generated fields

I am working on a simple form in Laravel where users can add multiple forms dynamically using AJAX. Here is the link to my code on jsfiddle: dynamic adding field by user Below is the HTML structure: <form id="paramsForms"> {{csrf_f ...