skip to Main Content

I don’t know how to extract only a specific value from my JWT token, I use react-jwt as my React library to decode my token, when I console.log I get this:

Object { userId: "850dff98-54fb-4059-9e95-e44f5c30be0f", iat: 1698866016 }

And I’d like to extract only the value of userId to put it in a localstorage like this: localStorage.setItem("userId", "the value")

import {useJwt} from "react-jwt"

export async function JWTDecode() {
    const token = localStorage.getItem("token")

    const { decodedToken } = useJwt(token!);
    console.log(decodedToken)
}

2

Answers


  1. You have to parse the string with JSON.parse first, then you can access the members.

    const token = localStorage.getItem("token");
    const tokenObj = JSON.parse(token);
    const userId = tokenObj.userId;
    

    You should probably also add some error handling and validation in there to make sure the token object is valid.

    Login or Signup to reply.
  2. Also, you could type it as they suggested in the Github Issue

    interface TokenPayload {
      userId: string;
      iat: number;
    }
    
    const { decodedToken, isExpired } = useJwt<TokenPayload>(token);
    

    Had to reference the attributes using ? but that should be fine,
    Sandbox here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search