Today we are going to learn a small function to decode JWT tokens using React.
The first thing we will do is to install the necessary libraries:
npm i jsonwebtoken --save
npm install auth0-js --save
And the types if we are using TypeScript:
npm i --save-dev @types/auth0-js
Once installed, let’s create this function in a utils.tsx file:
export function decodeToken(token: string): any { // Import the `jsonwebtoken` library to decode the token const jwt = require("jsonwebtoken"); // Decode the token and get the user information const decodedToken = jwt.decode(token, { json: true }) as any; // Return the user information return decodedToken; }
It will decode the tokens passed as a parameter and return them in JSON format.