reactjsmongodbjwtreact-fullstack

JWT (JSON Web token) front end webpack error


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.


Solution

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