In my application I have a token refresh endpoint /refresh which sets new JWT refresh token in a cookie and sends back new JWT access token as json.
Since access token expires after 5 minutes, I need to implement an under the hood refresh logic to kick in whenever access token is expired.
Currently what I am doing is to call the api through RTK Query and if api rejects the query, I call the refreshTokens mutation.
And I need to put this logic in all api queries like this:
updateProfile(body)
.unwrap()
.catch((error) => {
if (error && error.status === 403) {
refreshTokens(null); // RTK Query Mutation
updateProfile(body); // RTK Query Mutation
}
});
Doing this seems repetition of code since it needs to be implemented to all the calls to the api.
I wonder if there is a global solution to automatically call the refresh token endpoint when the queries are rejected.
For people coming here in 2022, redux toolkit now has good examples for how to achieve this.
https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#automatic-re-authorization-by-extending-fetchbasequery
https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#preventing-multiple-unauthorized-errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With