With the backend node.js, I have created a JWT token with a expire time:
signToken = (user) => {
return jwt.sign({ id: user.userId }, process.env.JWT_SECRET, { expiresIn: 60 * 60 * 24 * 10 }) // 1h = 60 * 60
}
With the fronend React app, when the user login, I will pass this JWT token with the return data and save it to localstorage(I'm using Redux):
const result = await userLogin({ username, password })
dispatch({ type: USER_LOGIN_SUCCESS, payload: result.data.data })
const { userReducer } = getState()
window.localStorage.setItem("accessToken", JSON.stringify(userReducer.token))
Each api required this token for authorization, I will pass this in the header. I set it in the axios request interceptors:
instance.interceptors.request.use(
(config) => {
const accessToken = localStorage.getItem("accessToken")
config.headers.Authorization = accessToken ? `Bearer ${accessToken}` : ""
if (config.url.includes("/files/")) {
config.headers["Content-Type"] = "multipart/form-data"
}
return config
},
(error) => {
return Promise.reject(error.response)
}
)
My question is how can I detect if the token is expire or not on React. With this React app, I'm using axios, redux, react-redux and react router.
localStorage
along with the token. And when the token is near to expire you can perform necessary operations such as token regeneration, validation etc