Having difficulty authenticating a JWT token in my Nextjs application

Help required with verifying a JWT token in Nextjs as I'm encountering the following error:

TypeError: Right-hand side of 'instanceof' is not an object

See below for the code I am currently using:

useEffect(() => {
    let token = localStorage.getItem("jqToken") || "";
    let result: any = "";
    try {
      result = jwt.verify(token, "SECRETEKEY");
    } catch (error) {
      console.log(error, "ERR");
    }
    console.log("first", result);
  }, []);

If anyone has solutions to this issue, please share your thoughts!

Answer №1

To resolve the issue, I tackled it by putting together a file directly in the root directory named "verifyToken.ts". Afterward, I proceeded to write the following code:

import jwt, { JwtPayload, Secret } from 'jsonwebtoken';

export const verifyToken = (token: string, secret: Secret): JwtPayload | null => {
    try {

        // Validate the token using the specified secret key
        const decoded = jwt.verify(token, secret) as JwtPayload;
        console.log(decoded)
        return decoded;
    } catch (error) {
        console.log(error)

        return null;
    }
};

Upon implementing the above steps, the problem was successfully resolved.

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

Angular 2 is throwing an error stating that the argument 'ElementRef' cannot be assigned to the parameter 'ViewContainerRef'

I'm developing an Angular 2 application with angular-cli, but when I include the following constructor, I encounter the following error: Error Argument of type 'ElementRef' is not assignable to parameter of type 'ViewContainerRef&apos ...

Enhancing Readability of Public Static Member Variables in Typescript

In my node application, I am utilizing typescript and winston for logging purposes. One key element of my setup is the "Logger" class which consists of a "logger" member and an "init()" function. By exporting this class, I understand that the "logger" memb ...

I am getting a 403 error on my unique Vercel domain

Just starting out with Vercel and it seems like I've hit a unique snag. I successfully imported my GitHub repository and set up a project in Vercel. Even added a custom domain that was approved by Vercel (following the provided instructions and updat ...

Advancement of server-side actions in NextJs 13 or 14 can now be tracked in

Is there a method to notify the client of status updates during server actions in NextJs 13 or 14? For example, if you have a server action that involves processing 1000 database records, how can you display the progress of this activity to the client? ...

What steps can I take to stop a browser from triggering a ContextMenu event when a user performs a prolonged touch

While touch events are supported by browsers and may trigger mouse events, in certain industrial settings, it is preferred to handle all touch events as click events. Is there a way to globally disable context menu events generated by the browser? Alternat ...

Exceed the capacity of a React component

Imagine having a React component that can render either a <button>, an <a>, or a React Router <Link> based on different props passed to it. Is it possible to overload this component in order to accept the correct props for each scenario? ...

How can we ensure file uploads are validated when using class-validator?

Recently, I've been utilizing the wonderful class-validator package to validate data. One specific validation task I'm working on is validating a file upload, ensuring that the file is not empty and ideally confirming that it is an image file. H ...

Renew expired JWT tokens using Angular 11 interceptor in conjunction with a Spring Boot backend

I have been working on a project using spring boot and angular, where users log in from the Angular frontend to the authentication API on Spring Boot to receive a JWT token. To ensure that all requests include this token, I have implemented an interceptor ...

Can you guide me on incorporating a date input with ngModel?

I have a date input field set up as follows: <input [(ngModel)]="value" type="text" class="form-control"> Can someone explain how I can display and submit the value correctly? The user's input should be formatted as dd/MM/yyyy, while t ...

Rendering a page in Next.js for React based on user authentication status

I am currently experimenting with setting up a nextjs index.tsx page that will display a specific component if the user is authenticated, and another one if they are not. While I have successfully rendered the component for non-authenticated users, I am f ...

The object might be undefined; TypeScript; Object

Why is it that the object may be undefined, even though it is hard-coded in my file as a constant that never changes? I've tried using ts-ignore without success. const expressConfig = { app: { PORT: 3000, standardResponse: `Server ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

What are the steps to create custom Typescript RecursiveOmit and RecursivePick declarations for efficient cloning routines?

For some time now, I have been attempting to create a declaration for RecursiveOmit and RecursivePick in cloning methods such as JSON.parse(JSON.stringify(obj, ['myProperty'])) type RecursiveKey<T> = T extends object ? keyof T | RecursiveKe ...

Combine Two Values within Model for Dropdown Menu

I am currently facing a situation where I have a select box that displays a list of users fetched from the backend. The select box is currently linked to the name property of my ng model. However, each user object in the list also contains an email proper ...

What is the best way to dynamically implement text ellipsis using CSS in conjunction with Angular 7?

i need to display a list of cards in a component, each card has a description coming from the server. In my component.html, I am using a ngFor like this: <div [style.background-image]="'url('+row.companyId?.coverUrl+')'" class="img- ...

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

Require assistance in accurately assigning a date to a Date[] in Typescript Array without altering current elements

In my current code, I have a loop that verifies if a date is a holiday and then adds it to an array. The issue I'm facing is that whenever I assign a new element to the array, all previous data in the list gets updated to the latest element. Here&apos ...

The error message "TypeScript is showing 'yield not assignable' error when using Apollo GraphQL with node-fetch

Currently, I am in the process of implementing schema stitching within a NodeJS/Apollo/GraphQL project that I am actively developing. The implementation is done using TypeScript. The code snippet is as follows: import { makeRemoteExecutableSchema, ...

Finding the Node.js log location during deployment in Heroku

My Node app on Heroku is giving me trouble. It deploys without any errors, but it crashes right at the start. The log provided below doesn't point to the issue clearly. When I try to access the suggested log at .npm/_logs/2021-04-22T19_59_52_474Z-debu ...