'jsonwebtoken doesn't working when page reloads

I am trying to implement jsonwebroken, but after implementing it when I login it's workig, but when I reload the page It's getting blank, it's can't get the email from useAuthstate

these errors are given. enter image description here

 const handleSingIn = async (event) => {
    event.preventDefault();
    await signInWithEmailAndPassword(email, password);
    

    const url = `http://localhost:5000/login`
    fetch(url, {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify({email})
    })
    .then(res => res.json())
    .then(data => {
        console.log(data);
        localStorage.setItem('accessToken', data?.accessToken); 
    })
}

Getting the accessToken from the server.

 // auth
    app.post('/login', async (req, res) => {
        const user = req.body;
        console.log(user);
        const accessToken = jwt.sign(user, process.env.JWT_ALGO_SECRET, {
            expiresIn: '1d'
        })
        res.send({ accessToken })
    })



This is the page where I am getting error.



const MyInventories = () => {
const [myBooks, setMyBooks] = useState([]);
console.log(myBooks);
const [user] = useAuthState(auth);
const email = user?.email;
console.log(user);
const url = `http://localhost:5000/books?email=${email}`;
console.log(url);

useEffect(() => {
    fetch(url, {
        headers: {
            authorization: `bearer ${localStorage.getItem('accessToken')}`
        }
    })
        .then(res => res.json())
        .then(data => setMyBooks(data))
}, [user])

API for getting the users if email and webtoken is verified

 //load single users items.
    app.get('/books', verifyToken, async (req, res) => {
        
        const decodedEmail = req.decoded.email;
        const email = req.query.email;
        if (email === decodedEmail) {
            const query = { email: email };
            console.log(query);
            const cursor = bookCollections.find(query);
            const result = await cursor.toArray();
            res.send(result);
        }
        else{
            res.status(403).send({message: "Forbidden access"});
        }
    })

verification

function verifyToken(req, res, next) {
const header = req.headers.authorization;
console.log('inseide token', header);
if (!header) {
    return res.status(401).send({ message: 'unauthorized access' });
}
const token = header.split(' ')[1];
console.log(token);
jwt.verify(token, process.env.JWT_ALGO_SECRET, (err, decoded) => {
    if (err) {
        return res.status(403).send({ message: 'Forbidden' });
    }
    console.log(decoded)
    req.decoded = decoded;
})
next()

}



Sources

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

Source: Stack Overflow

Solution Source