Issue
So I have this API where if you want to get any data from it, you have to add headers 'Authorization':'access token'
to be able to access the API. And to get that 'access token'
is first you must do a POST request to the API with provided credentials and it'll return the token.
But the thing is that token will expire after exactly 12 hours. Since I'm using react-query
, this is how I access the API :
useQuery(['data'], () =>
axios
.get('/endpoint', { headers: {
Authorization:`${token}`,
},
})
.then((res) => res.data.data)
);
Where ${token}
is a variable that I manually put the token I got from Postman API (yes I manually added it. I do a post request in there and copy pasted it)
But since it'll expire after 12 hours. I simply have no idea how to automate to refresh the token.
The API have an endpoint where you can refresh token with the 'old token' as headers and it'll return a new token.
Do I need to use state management to manage the token once it gets expire?
What would be the best approach to refresh the token once it expires?
Solution
Do I need to use state management to manage the token once it gets expire?
Sure, you could. You are already going to be storing the token somewhere, so presumably you can also store expiry info alongside it.
There are a hundred different ways you could choose to manage this, although it depends on the details that you haven't shared.
One way would be to create an Axios interceptor to check this before requesting, and refresh it if it's getting close to expired.
Here's an example.
const axios = Axios.create()
const tokenKey = 'auth-token'
const getToken = () => {
return localStorage.getItem(tokenKey)
}
const setToken = (token) => {
localStorage.setItem(tokenKey, token)
}
const isTokenExpired = () => {
const decoded = jwt_decode(getToken)
return decoded.iat > Date.now()
}
const getRefreshedToken = () => {
return axios.post('/refresh_endpoint')
}
const refreshToken = async () => {
const newToken = await getRefreshedToken()
setToken(newToken)
}
axios.interceptors.request.use(async (req) => {
if(isTokenExpired()){
await refreshToken()
}
})
Answered By - defraggled Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.