How to refresh JWT tokens in React.js Application?
If you are using Axios (which I highly recommend), you can declare your token refreshing behaviours in the response's interceptors. This will apply to all https requests made by Axios.
The process is something like
- Checking if the error status is 401
-
- If there is a valid refresh token: use it to get the access token
- if there is no valid refresh token: log the user out and return
- Redo the request again with the new token.
Here is an example:
axios.interceptors.response.use(
(response) => {
return response
},
(error) => {
return new Promise((resolve) => {
const originalRequest = error.config
const refreshToken = localStorage.get('refresh_token')
if (error.response && error.response.status === 401 && error.config && !error.config.__isRetryRequest && refreshToken) {
originalRequest._retry = true
const response = fetch(api.refreshToken, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
refresh: refreshToken,
}),
})
.then((res) => res.json())
.then((res) => {
localStorage.set(res.access, 'token')
return axios(originalRequest)
})
resolve(response)
}
return Promise.reject(error)
})
},
)
Related videos on Youtube
Ruby
Updated on September 15, 2022Comments
-
Ruby over 1 year
I checked all the similar questions here but none has what I need. I'm securing the routs in my App and sending the JWT with every request and everything is fine here. The issue is when the JWT expires, instead of logging out the user, I need to know how to refresh that token and keep the user logged in.
Everyone is talking about creating a "Middleware" that handles that, but no one says how to create that middleware and what's in it?
So, what is the best practice in doing that? Should I check for JWT expiration date before sending any request? or should I wait for a "401" response then try to refresh the token (which I don't know how to do), or what exactly?
If anyone has a working example of such a middleware or a package or a project on Github that can help me with this it would be great.
I'm only interested in the front-end part of the process, what to send from react and what should I expect to receive and what to do with it.
-
Ruby about 5 yearsCould you please use that middleware in a react.js example?
-
Ruby over 3 yearsI ended up doing the exact same thing, with different code of course, but the same idea, using Axios interceptors. I accepted your answer as the correct answer.
-
Tom el Safadi almost 3 yearsI am not a fan of that because it promotes using an expired token unless an HTTP call is made. Sending an API request with an expired token is an unnecessary request. I would rather implement an auth service which provides a getToken method. Every time that method gets called, you check if the token has expired. If it expired, refresh it and return the new one. If it hasn‘t, return the one from storage. Use this method in your request interceptor where you add the token to the header.
-
Jalil Markel over 2 yearsSaving refresh token on client-side is not safe, is it?