'Invalid Token Error: Invalid token specified: Cannot read property 'replace' of undefined?

I was trying to decode token created through jwt, so that I can access values in my react page and and use it.But for some reason it shows "InvalidTokenError: Invalid token specified: Cannot read property 'replace' of undefined" this error, I really need help on this, thankyou very much in advance to whoever answers this.

Front-End in react.js,decoding the token

 useEffect(()=>{
const token=localStorage.usertoken

const decoded = jwt_decode(token);

setinfo({
   id:decoded._id,
   email:decoded.email,
   username:decoded.username,
   
})


 },[])

Back-end node.js

router.get("/info",authenticateToken,(req,res)=>{

    UserProfile.findOne({_id: req.user._id})
            .then(user=>{
                console.log(user);
                if(user){
                    res.json(user)
                } else {
                    res.send("User does not exist")
                }
                
                
            })
            .catch(err=>{
                res.send("error:"+err);
            })
        
})

function authenticateToken(req,res,next){

const authHeader= req.headers['authorization']
const token = authHeader && authHeader.split(' ')

if(token == null) return res.sendStatus(401)

jwt.verify(token,secretkey,(err,user)=>{

    if(err) return res.sendStatus(403)
    req.user = user
    next();
})
}


Solution 1:[1]

I think the way you are accessing the token from localStorage is wrong. Instead of

localStorage.usertoken

use

localStorage.getItem("userToken")

considering you have set user token by

localStorage.setItem("userToken", token_received_from_backend);

Solution 2:[2]

I also got the same error. In my case, I have got one mistake. In Localstorage please remove the token variable and refresh the page

  • In My case, the local-storage variable name is myToken is undefined, so I deleted the variable and refresh the page

Solution 3:[3]

When you call the cloud function, Try to add the full function url in the post request instead of "/login".

Solution 4:[4]

I found this article that worked for me:

https://www.onooks.com/invalid-token-specified-cannot-read-property-replace-of-undefined/

In summery it suggest that you clear your browser’s local storage cache using the developer tools "F12" and go to Storage\Local Storage, right click and clear.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Atif Hossain
Solution 2 Dilkash Shaikh Shahagir Mahaja
Solution 3 Mahmoud Mohamed Ouf
Solution 4 Pieter Burger