spotty-amberS
Refine3y ago
17 replies
spotty-amber

while using POST, PUT, or PATCH if my access token has been expired user will be logged out

I have used axios as my HTTP client and using axios-auth-refresh for refreshing my access token from a server. Everything is working fine except when my access token is expired and if I send any of the above mentioned request then the user will be logged out from the system and redirected to the login page instead of refreshing the access token and retrying the request again. My code for instantiating axiosInstance is as below:

import {
  API_BASE_URL, API_KEY, TOKEN_KEY, TOKEN_REFRESH_KEY, USER_DETAILS_KEY
} from "config";

function getAuthToken(token = localStorage.getItem(TOKEN_KEY)) {
  return `Bearer ${token}`;
}

export const axiosInstance: AxiosInstance = axios.create();

axiosInstance.interceptors.request.use(
  (request: AxiosRequestConfig) => {
      if (request.headers) {
          request.headers["x-api-key"] = API_KEY;
      } else {
          request.headers = { "x-api-key": API_KEY };
      }
      return request;
  },
);

const refreshAuthLogic = async (failedRequest: AxiosError) => {
  const refreshToken = localStorage.getItem(TOKEN_REFRESH_KEY);
  if (refreshToken) {
    try {
      const { data } = await axios
      .post(`${API_BASE_URL}/token/refresh/`, {
        refresh: refreshToken,
      });
      const { access, refresh } = data;
      // save token to storage
      axiosInstance.defaults.headers.common["Authorization"] = getAuthToken(access);
      return Promise.resolve();
    } catch {
      // remove token from storage
      return Promise.reject(failedRequest);
    }
  }
  // remove token from storage
  return Promise.reject(failedRequest);
};

createAuthRefreshInterceptor(
  axiosInstance,
  refreshAuthLogic,
  {
    pauseInstanceWhileRefreshing: true,
  }
);


and in my App.ts I am using this axiosInstance in Refine config as
<Refine
  dataProvider={restDataProvider(API_BASE_URL, axiosInstance)}
  // other configs
/>
Was this page helpful?