'Deal with refresh token in React
I need to use refresh-token to get new access-token and it expires. In frontend, when searching around I come across with 2 approaches:
Use axios interceptors to check if access-token is still valid or not => If it is not valid access-token (not expires), then use refresh-token to get a new access-token => If get new token success => perform the request.
Perform the request => server check access-token => if invalid then send error code to client => client then perform request to get new access-token => if get new token success => retry the request
I dont know which way is better. It seems to me that approach 1 is easier but it is may not the responsibility of client to check if access-token is valid or not. The second way seems good to me but how I retry the request after receiving new access-token
Solution 1:[1]
I use other variant with assumption that each request to the backend is reseting the token expiriation datetime. In this case I have flow:
- login request => response with token and information how long
tokenis valid (in seconds, for example keyexpire_in_seconds) - on frontend side start counting down from
expire_in_secondsto 0 - each authorized request to backend => reset on frontend side expiration time to
expire_in_seconds(and on backend side too of course) - when user is doing nothing for a while and counter is decreasing you can show message for user 'Your session will expire after {counter} seconds. Keep the session'
- if user will click button (Keep the session) - reset counter on both sides (backend and frontend)
- if user will not click the button - logout him
Solution 2:[2]
You can use something like this: Axios has error.config, this is last request, which catched with error.
api.interceptors.response.use(
response => {
...
},
error => {
if (error.response.status === 401) {
refreshToken(YOUR_DATA) // your method to refresh Token
axios.request(error.config).then(response => { // makes the last request that passed with an error
...
})
.catch(error => console.log(error)
}
...
}
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Hardy1207 |
