Skip to content

Instantly share code, notes, and snippets.

@karpolan
Last active October 6, 2022 22:15
Show Gist options
  • Save karpolan/60ac730965a1b981e7130bc8aa348ebc to your computer and use it in GitHub Desktop.
Save karpolan/60ac730965a1b981e7130bc8aa348ebc to your computer and use it in GitHub Desktop.
Preconfigured instance of Axios to use in React Apps with TypeScript
import axios from 'axios';
import { api } from '.';
import { log } from '../utils/log';
import { addTrailingSlash } from '../utils/path';
// Note: Use Local storage to override API base path
export const API_URL = addTrailingSlash(process.env.REACT_APP_API || 'http://localhost:3030');
/**
* Pre-configured instance of Axios
*/
const axiosInstance = axios.create({
baseURL: API_URL,
heders: {
'Access-Control-Allow-Origin': '*', // Solving CORS issue
}
});
/**
* Interceptor to automatically add Authorization headers into all requests
*/
const requestInterceptorApplyAuthToken = (config: AxiosRequestConfig) => {
if (!config.headers) {
config.headers = {};
}
config.headers['Authorization'] = `Bearer ${api.accessToken}`; // TODO: Check do we use Bearer or not
return config;
};
/**
* Interceptor to automatically logout current user if any API call returns 401
* Note: Should be ejected before auth/login flow, due to 401 codes as correct response.
*/
const responseInterceptorOnError = (error: AxiosError) => {
if (error?.response && Number(error?.response?.status) === 401) {
log.error(error);
api?.logout(); // We got 401, Logout user and reload Application
}
return Promise.reject(error);
};
/**
* axios interceptor's management
*/
let _interceptorsResponseHandle: number | null = null;
let _interceptorsRequestHandle: number | null = null;
export function axiosInterceptorsOn() {
if (!_interceptorsRequestHandle) {
_interceptorsRequestHandle = axiosInstance.interceptors.request.use(requestInterceptorApplyAuthToken);
}
if (!_interceptorsResponseHandle) {
_interceptorsResponseHandle = axiosInstance.interceptors.response.use(undefined, responseInterceptorOnError);
}
log.warn('axios interceptors on');
}
export function axiosInterceptorsOff() {
if (_interceptorsRequestHandle) {
axiosInstance.interceptors.request.eject(_interceptorsRequestHandle);
_interceptorsRequestHandle = null;
}
if (_interceptorsResponseHandle) {
axiosInstance.interceptors.response.eject(_interceptorsResponseHandle);
_interceptorsResponseHandle = null;
}
log.warn('axios interceptors off');
}
export default axiosInstance;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment