How to check validity of JWT to set refreshToken

I’m using React and JWT + refresh token. When my user log in, I set in localStorage the token and refresh_token.

Now, I set up my token to 5s validity to make my logic for refresh token.

My question is, once my user is logged in, and the token and refresh token are stored in Local Storage, how can I check the validity on each reload or re-render of react ?

Am i supposed to make an API call on every page ?

Here is my loggin function :

// Login user
const login = async (userData) => {
    let datas;
    await axios.post('/authentication_token', userData)
        .then((response) => {
            localStorage.setItem('user', JSON.stringify(response.data))
            axios.defaults.headers.common['Autorization'] = `Bearer ${response.data.token}`
            datas = response.data
        })
    return datas
}

>Solution :

You need to refresh API call in App.js and use setInterval() every 5 seconds to call your refresh token API, and your refresh token will be updated. Instead you should check the accuracy of the token, maybe if your token expires your API throw you 401 status code and you will be logged out.

Leave a Reply