Skip to content

Instantly share code, notes, and snippets.

@imroca
Created June 3, 2025 14:21
Show Gist options
  • Save imroca/e15e7b7eb6cf8e7424a7fe106394c02a to your computer and use it in GitHub Desktop.
Save imroca/e15e7b7eb6cf8e7424a7fe106394c02a to your computer and use it in GitHub Desktop.
Axios Api Client
import Axios, { isAxiosError } from "axios";
import type {
CreateAxiosDefaults,
AxiosInstance,
AxiosResponse,
InternalAxiosRequestConfig,
} from "axios";
export const createApiClient = (
config: CreateAxiosDefaults,
errorlog: boolean = false
): AxiosInstance => {
const api = Axios.create(config);
api.interceptors.request.use((config: InternalAxiosRequestConfig) => {
if (config.headers) {
config.headers.Accept = "application/json";
}
config.withCredentials = true;
return config;
});
api.interceptors.response.use(
(response: AxiosResponse) => {
if (response.status >= 200 && response.status < 300) {
return response.data;
}
throw new Error(`HTTP error! status: ${response.status}`);
},
(error) => {
if (isAxiosError(error)) {
if (errorlog) {
console.error("[Axios] Message:", error.message);
}
if (error.response) {
if (errorlog) {
console.error(
"[Axios] Response - Status code:",
error.response.status
);
console.error("[Axios] Response - Data:", error.response.data);
}
} else if (error.request) {
if (errorlog) {
console.error("[Axios] Request:", error.request);
}
}
} else {
if (errorlog) {
console.error("[Axios] An unexpected error occurred:", error);
}
}
return Promise.reject(error);
}
);
return api;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment