Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

send refresh token in axios interceptor

import axios from "axios";
import { fetchProps } from "store/types/CommonType";
import { getLoginCredentials, setLogout } from "utils/helper";

const rootURL = process.env.REACT_APP_ROOT_URL;
let isRefreshing = false;
let refreshSubscribers: any = [];
const localData: any = localStorage.getItem("Auth");
const parsData = JSON.parse(localData);

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    const status = error?.response?.data?.error?.status;
    const originalRequest = error?.config;
    
    if (status === 401) {
      if (!isRefreshing) {
        isRefreshing = true;
        axios
          .post(`${rootURL}refresh`, {
            refreshToken: parsData?.tokens?.refreshToken,
          })
          .then(({ data }) => {
            isRefreshing = false;
            const valueToRefresh = {
              ...parsData,
              token: data?.accessToken,
              tokens: {
                accessToken: data?.accessToken,
                refreshToken: parsData?.tokens?.refreshToken,
              },
            };
            localStorage.setItem("Auth", JSON.stringify(valueToRefresh));
            onRefreshes(data?.accessToken);
          })
          .catch((e) => {
            setLogout(window?.history);
          });
      }
      const retryOrigReq = new Promise((resolve, reject) => {
        subscribeTokenRefresh((accessToken: any) => {
          originalRequest.headers["Authorization"] = "Bearer " + accessToken;
          resolve(axios(originalRequest));
        });
      });
      return retryOrigReq;
    } else {
      return Promise.reject(error);
    }
  }
);

function subscribeTokenRefresh(cb: any) {
  refreshSubscribers.push(cb);
}

function onRefreshes(accessToken: any) {
  refreshSubscribers.map((cb: any) => cb(accessToken));
}

const fetchHandler = (
  { url, method = "GET", actionType, body, secure }: fetchProps,
  successHandler?: (p: object) => void,
  errorHandler?: (p: object) => void
) => {
  const getMethod: any = method;
  const authValue = getLoginCredentials();

  axios({
    method: getMethod,
    headers: {
      "Content-Type": "application/json",
      ...(secure && { Authorization: `Bearer ${authValue?.token}` }),
      "Access-Control-Allow-Origin": "*",
    },
    url: `${rootURL}${url}`,
    ...(method !== "GET" && { data: body }),
  })
    .then((response) => {
      return triggerSuccessHandler(response);
    })
    .catch((err) => {
      return errorHandler && errorHandler(err);
    });

  const triggerSuccessHandler = (response: any) => {
    return successHandler ? successHandler(response?.data) : null;
  };
};
export default fetchHandler;
Comment

PREVIOUS NEXT
Code Example
Javascript :: convert response to json javascript 
Javascript :: set multiple attributes css javascript 
Javascript :: access to static file nodejs 
Javascript :: exit from fullscreen 
Javascript :: placeholder js 
Javascript :: jquery get selected dropdown item 
Javascript :: nextsibling vs nextelementsibling 
Javascript :: errors in Joi 
Javascript :: unload in jquery 
Javascript :: jquery event keycode 
Javascript :: node get absolute path 
Javascript :: object keys javascript 
Javascript :: js json stringfy beutify 
Javascript :: split string in angular 8 
Javascript :: send url by whatsapp in javascript 
Javascript :: npm install global vs local 
Javascript :: js is array 
Javascript :: How to check if array includes a value from another array in JavaScript 
Javascript :: select all elements javascript 
Javascript :: copy to clipboard javascript dom 
Javascript :: validate password javascript 
Javascript :: sort array of objects by string property value 
Javascript :: getitem localstorage 
Javascript :: package.json set environment variables 
Javascript :: ref css in jsp 
Javascript :: access key of object javascript 
Javascript :: how to map objects in react native 
Javascript :: how to remove identical string in javascript 
Javascript :: factorialization in javascript 
Javascript :: nl2br javascript 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =