JWT (JSON Web token) front end webpack error

Viewed 1608
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.

3 Answers

Install jwt-decode

npm i jwt-decode

import jwtDecode from 'jwt-decode'

Then

const decoded = jwtDecode(token)
console.log(decoded)

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.

Related