how can i get the user_id from jwt in the localstorage and use it in react?

I am writing a logic to create a post and i want to add the logged in user as the user making the post, i have saved the refresh token in my browser localstorage, when i copy the refresh token and paste in jwt.io, i get this response

{
  "token_type": "refresh",
  "exp": 1679234275085,
  "iat": 1674953425085,
  "jti": "d723e65f9bdctret41399e5d09278ef1fcbc",
  "user_id": 1,
  "username": "destiny",
  "email": "desphixs111@mailnator.123"
}

now how do i grab the user_id and use it in react, this is where i want to use it

const formData = new FormData()

formData.append("user", 1)

Instead of hardcoding the user_id as 1 or 2, i want to pass it in dynamically, how can i do this?

>Solution :

You can use jwt-decode library.

  1. Install the jwt-decode library by running npm install jwt-decode in your project’s root directory.

  2. Import the library in your component or file where you want to use it:

    import jwtDecode from 'jwt-decode';
    
  3. Retrieve the JWT token from local storage:

    const token = localStorage.getItem('refresh_token');
    
  4. Decode the token and extract the user_id:

    const decoded = jwtDecode(token);
    const user_id = decoded.user_id;
    
  5. Append the user_id to the form data:

    formData.append("user", user_id)
    
  6. Send the form data to your server to create the post.

Note:

  • You should always validate the token and check the expiration date before using it.
  • It’s also important to check that the token exists in the local storage before using it, and handle the case where the token is not found.

Leave a Reply