axios-custom
v1.0.3
Published
A configurable axios wrapper with UI-agnostic 401 handling
Downloads
39
Readme
axios-custom
A small axios wrapper for frontend projects. It keeps axios configurable, adds token injection, supports request-level token overrides, and provides UI-agnostic 401 handling.
Install
npm install axios-custom axiosaxios is a peer dependency, so the application should install it.
Basic Usage
import { createAxiosClient } from "axios-custom";
export const request = createAxiosClient({
baseURL: import.meta.env.VITE_API_URL,
getToken: () => localStorage.getItem("token"),
});Then use it like a normal axios instance:
const res = await request({
url: `/goods/cake/brand/list/dgss/20/${page.value}`,
method: "get",
});By default, the client adds this header when a token exists:
Authorization: Bearer <token>Request-Level Token
Use token when one project needs different tokens for different APIs:
const res = await request({
baseURL: import.meta.env.VITE_API_URL,
url: `/goods/cake/brand/list/dgss/20/${page.value}`,
method: "get",
token: goodsToken,
});If token already starts with Bearer , it will be used as-is. Otherwise, the wrapper will add the Bearer prefix.
You can also pass the header yourself:
await request({
url: "/profile",
method: "get",
headers: {
Authorization: `Bearer ${userToken}`,
},
});An explicit Authorization header has priority over automatic token injection.
Skip Auth
Set noAuth: true for public APIs:
await request({
url: "/login",
method: "post",
noAuth: true,
data: {
username,
password,
},
});Multiple Clients
For separate business domains, create separate clients:
export const userRequest = createAxiosClient({
baseURL: import.meta.env.VITE_USER_API_URL,
getToken: () => localStorage.getItem("userToken"),
});
export const adminRequest = createAxiosClient({
baseURL: import.meta.env.VITE_ADMIN_API_URL,
getToken: () => localStorage.getItem("adminToken"),
});Options
createAxiosClient({
baseURL: "",
timeout: 10000,
headers: {},
getToken: () => localStorage.getItem("token"),
attachToken: true,
beforeRequest: (config) => config,
transformResponse: (response) => response.data,
onAuthFail: (error, ctx) => ctx.defaultRedirect("/login"),
routerPush: (path) => router.push(path),
showError: (msg) => message.error(msg),
showInfo: (msg) => message.info(msg),
});Token Lookup Order
When attachToken is enabled and noAuth is not set, the client uses the first available value:
config.headers.Authorizationconfig.tokengetToken()localStorage.getItem("token")sessionStorage.getItem("token")document.cookievalue namedtoken
Response Handling
The default response interceptor supports common response shapes:
{ code: 0, data: ... }
{ success: true, result: ... }For other backend formats, use transformResponse:
const request = createAxiosClient({
transformResponse(response) {
const data = response.data;
if (data.status === "ok") return data.payload;
throw new Error(data.message || "Request Error");
},
});401 Handling
Use onAuthFail to handle authorization failures without coupling this package to a UI framework:
const request = createAxiosClient({
onAuthFail(error, ctx) {
localStorage.removeItem("token");
ctx.defaultRedirect("/login");
},
});TypeScript
This package ships with type declarations and augments axios request config with:
interface AxiosRequestConfig {
noAuth?: boolean;
token?: string | null;
}