react-query-auth icon indicating copy to clipboard operation
react-query-auth copied to clipboard

Refresh token

Open mohdaqib57 opened this issue 3 years ago • 2 comments

Is there a specific function where I am supposed to put the refreshing users auth tokens logic? Following the doc doesnt seem to mention it.

mohdaqib57 avatar Jan 30 '22 23:01 mohdaqib57

If you are using Axios, you can handle it with an interceptor like such:

httpClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  async (error) => {
    // TODO: revalidate cookie if we have an auth error once
    const message = error.response?.data?.message || error.message;

    if (message === 'Invalid token.') {
      // do something to update your token

      // retry the request
      return httpClient.request(error.config);
    }

    return Promise.reject(new Error(message as string));
  }
);

fmonper1 avatar Apr 18 '22 22:04 fmonper1

Hi there,

Yes, as @fmonper1 says, it should be handled outside of this library, at the API client layer which is why using axios is a good idea. There is also a package that helps with creating that kind of interceptor on the axios instance if you don't want to do it on your own: https://github.com/Flyrell/axios-auth-refresh

alan2207 avatar Apr 19 '22 06:04 alan2207