React-Axios
I was developing a web application using react. And I used axios for asynchronous communication, and used axios.create to create axios instance by classifying it into two functions: one that requires user authentication and one that does not.
axios instance used when authentication is not required
axios instance used when authentication is required
On successful login, get the token. Token uses JWT.
The token was received in the form above and stored in local storage.
The token was divided into access token and refresh-token and stored in localStorage. If authentication is required, the access client imports the access Token in local storage to send the request.
When I send a request, the token information is well contained in the header, as shown in the picture above. There was no problem developing it so far. However, there was a problem refreshing the token.
(For now, the refresh process works very well.)
React-Axios Token Refresh
accessClient.interceptors.response.use
If http status code 401 is received using interceptors from axios, request token refresh.
Here, when token refresh is achieved, the process of sending the previous request again is required, and if you request action with hooks, you can use promise with new Promise((resolve, reject)
In this way, after the token refreshed, the token of the header is changed to the previous request and transferred.
I thought it was going well. But it wasn’t….)
localStorage.setItem(ACCESS_TOKEN, res.access);
The new token replaced the existing one in localStorage. The token is well changed when checked with developer tools and consoles.
axios.create header not change
But there was a problem.
This is why if the code works well, we must suspect it. :(
Can you see it? It’s infinitely refreshing..
After the token refreshed, all requests refresh the token again. I checked the header and thought, oh, my God.
The header has not a changed token. The token that it had initially remained intact. Is the instance created with axios.create not changed??
The answer was simple.
accessClient.interceptors.request.use
If the instance created after axios.create does not change, you can use interceptors.request to change the token of the header inside the instance before sending the request.
The code is simple, too.
Another solution
axios.defaults.headers
We can use axios.defaults.headers to change token.
I haven’t tried it myself yet, so I’ll check later to see if it actually works.