import axios from 'axios'; import { AxiosError, AxiosRequestConfig } from 'axios'; import { AuthoriseUser } from '../services/Authorise/Authorise'; const Api = axios.create({ baseURL: 'http://localhost:5267/api/' }); const isAlreadyAuthUrl = (error: AxiosError) => { const full = error.request.responseURL as string; return full.endsWith('User/authorize'); }; Api.interceptors.response.use( (response) => response, // Normal success logic (error: AxiosError) => { if (error.request.status === 401 && !isAlreadyAuthUrl(error)) { // If 401 (Unauthorized) AuthoriseUser().then((response: any) => { // Re-auth if (!response) // If no response then just return return; return Api.request(error.config as AxiosRequestConfig); // Redo the request }); } else { throw error; // Otherwise throw error as normal } } ); export default Api;