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

19.6k views Asked by At

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();
})
}

5

There are 5 answers

0
Atif Hossain On

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);
0
Dilkash Shaikh Shahagir Mahaja On

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
0
Mahmoud Mohamed Ouf On

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

0
Pieter Burger On

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.

0
amadich On

for me i tryed remove useState() and change with veriable exemple :

// const [user , setUser] = useState({}); # Remove This <
let user; // Use This 


// cooking-login jwt
    const jwtlogin = (mytoken) => {
        // Decode JWT token
        const decoded = jwtDecode(mytoken)

        // set emails State
        user = decoded;
        // set cookie
        cookies.set("jwt_auth",mytoken, {
            expires: new Date(decoded.exp * 1000),
        })
    }

Just This and Thanks