Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle JWT Token Refresh cycle with React and RTK Query: Refetching the failed queries automaticallly

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.

like image 229
damdafayton Avatar asked Jan 31 '26 05:01

damdafayton


1 Answers

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

like image 79
minlare Avatar answered Feb 01 '26 18:02

minlare