5
import React, { useEffect, useState } from 'react'

import jwt from 'jsonwebtoken'

import { useNavigate } from 'react-router-dom'
import Navbar from './Shared/navbar'



export default function Home() {

const navigate = useNavigate();
const [user, setUser ] = useState('')

async function populateUser() {

     const req = await fetch('http://localhost:5000/users', {
        headers: {
            'x-access-token': localStorage.getItem('token'),
        },
    })

    const data = await req.json()
    if (data.status === 'ok') {
        console.log(data)
    } else {
        alert(data.error)
    }
}


useEffect(() => {

    const token = localStorage.getItem('token')
    if (token) {
        const user = jwt.decode(token)
        if (!user) {
            localStorage.removeItem('token')
            navigate('/login')
        }
    } else {
        populateUser()
    }
}, [])
return (
    <>
    <Navbar/>
    </>
)}

I am trying to get user data in the front end by using jwt to decode the jwt token, however this breaks my app and I get this error enter image description here

I read online that this is a recent webpack issue (v5) is there a way to fix this? I am also not sure what the error message is asking me to do. To clarify without the jwt method I do get the token back and the login is successful.

andrew kim
  • 137
  • 1
  • 6

4 Answers4

7

I solved it by using different package named jwt-decode. Here is the docs - https://www.npmjs.com/package/jwt-decode. It works!

huxnet
  • 86
  • 2
5

Install jwt-decode

npm i jwt-decode

import jwtDecode from 'jwt-decode'

Then

const decoded = jwtDecode(token)
console.log(decoded)
Mrunal Tupe
  • 140
  • 4
  • 6
1

To avoid this issue, use any other jwt packages instead of jsonwebtoken. Or else use jwt-decode for particular decoding operations. Because React is a frontend library which doesn't have node compartments to comprehend jwt. So that install jwt-decode in your frontend

npm i jwt-decode

after that import that to your particular page/component

import jwt from 'jwt-decode'

then decode the token as you did before.

const user = jwt.decode(token)

Dont destructure with different components. It is dedicated to work within your imported page/component.

Abishethvarman V
  • 129
  • 1
  • 1
  • 9
0

you can import just the decode from jsonwebtoken like this, I think this will help,

import { decode } from "jsonwebtoken";

const secret = decode(params.userName);
Elias Salom
  • 99
  • 1
  • 13