Axios Setup

A production-grade axios layer: one instance with auth, token refresh, retries and typed errors, a services folder per resource, and request/response types.

Skills

What it sets up

Without a layer like this, components call axios.get directly, and the base URL, token handling and error parsing get copied into every call. This skill sets up three layers instead, each with one job.

api/ is the only place that knows about axios. services/ has one typed object per resource, and components call these. types/ holds every request and response shape. Before writing any types, the agent reads your real API (its spec, DTOs or a live response), so the types match what the server actually sends.

What you get

  • One configured instanceBase URL from env, a 15s timeout, JSON headers and cookies, set once in api/axios-instance.ts.
  • Auth on every requestThe access token is added from memory, never localStorage. skipAuth opts out for login and public calls.
  • Single-flight refreshWhen the token expires, every 401 waits on one /auth/refresh, then each request is replayed once.
  • Safe retriesGET, HEAD and OPTIONS retry twice on network errors and 5xx, with backoff and jitter. POST never does.
  • One error typeEvery failure becomes an ApiError with kind, status and fieldErrors, so the UI never reads AxiosError.
  • Cancellable readsEach service takes an AbortSignal, so TanStack Query and effect cleanups cancel what they no longer need.

How a request travels

  1. Component
  2. userService.list()
  3. http.get<T>()
  4. axios instance
  5. Your API

On the way back, http.ts returns just the response body and the instance turns any failure into an ApiError, so the component gets either typed data or one known error.

Files it creates

src/api/axios-instance.ts
import axios, { type AxiosInstance, type InternalAxiosRequestConfig } from "axios";
import { API_CONFIG } from "./config";
import { ENDPOINTS } from "./endpoints";
import { tokenStore } from "./token-store";
import { toApiError } from "./api-error";
import type { RefreshResponse } from "@/types/auth.types";

// Per-request switches, typed once instead of `as any` at call sites.
declare module "axios" {
interface AxiosRequestConfig {
// Send without the Authorization header and never try a refresh:
// login, refresh, and public endpoints.
skipAuth?: boolean;
// Internal bookkeeping for the interceptors below.
_authRetried?: boolean;
_retryCount?: number;
}
}

export type ApiClientOptions = {
baseURL: string;
timeoutMs: number;
maxRetries: number;
getAccessToken: () => string | null | Promise<string | null>;
// Return a fresh access token, or throw if the session is over. Omit to
// disable refresh (e.g. on the server).
refreshAccessToken?: () => Promise<string>;
// Called once when a refresh fails: clear caches, redirect to login.
onSessionExpired?: () => void;
};

const IDEMPOTENT = new Set(["get", "head", "options"]);

type Signal = InternalAxiosRequestConfig["signal"];

// Backoff that a cancelled request does not sit through.
const wait = (ms: number, signal?: Signal) =>
new Promise<void>((resolve, reject) => {
if (signal?.aborted) return reject(new axios.CanceledError());
const t = setTimeout(resolve, ms);
signal?.addEventListener?.("abort", () => {
clearTimeout(t);
reject(new axios.CanceledError());
});
});

// A factory, not just a singleton: server code (Next.js route handlers, server
// components) must build a client per request with that request's token, or
// one user's token leaks into another's requests.
export function createApiClient(options: ApiClientOptions): AxiosInstance {
const client = axios.create({
baseURL: options.baseURL,
timeout: options.timeoutMs,
headers: { Accept: "application/json" },
withCredentials: true,
});

client.interceptors.request.use(async (config) => {
if (!config.skipAuth) {
const token = await options.getAccessToken();
if (token) config.headers.set("Authorization", `Bearer ${token}`);
}
return config;
});

// Many requests can 401 at once when the token expires. They all wait on
// one refresh instead of each firing their own.
let refreshing: Promise<string> | null = null;
const refreshOnce = () => {
refreshing ??= options.refreshAccessToken!().finally(() => {
refreshing = null;
});
return refreshing;
};

client.interceptors.response.use(undefined, async (error: unknown) => {
if (!axios.isAxiosError(error) || !error.config) throw toApiError(error);
const config = error.config;
const status = error.response?.status;

// 1. Expired access token: refresh once, replay the request once.
if (status === 401 && !config.skipAuth && !config._authRetried && options.refreshAccessToken) {
config._authRetried = true;
try {
const token = await refreshOnce();
config.headers.set("Authorization", `Bearer ${token}`);
return client(config);
} catch (refreshError) {
options.onSessionExpired?.();
throw toApiError(refreshError);
}
}

// 2. Flaky network or 5xx on a request that is safe to repeat.
const transient = !error.response || (status !== undefined && status >= 500);
const method = (config.method ?? "get").toLowerCase();
const attempt = config._retryCount ?? 0;
if (transient && IDEMPOTENT.has(method) && attempt < options.maxRetries && !axios.isCancel(error)) {
config._retryCount = attempt + 1;
const delay = 300 * 2 ** attempt + Math.random() * 200;
await wait(delay, config.signal);
return client(config);
}

throw toApiError(error);
});

return client;
}

// The browser's client. A bare axios call does the refresh, so a 401 from
// /auth/refresh can never loop back through these interceptors.
export const api = createApiClient({
...API_CONFIG,
getAccessToken: tokenStore.get,
refreshAccessToken: async () => {
const { data } = await axios.post<RefreshResponse>(
ENDPOINTS.auth.refresh,
null,
{ baseURL: API_CONFIG.baseURL, withCredentials: true, timeout: API_CONFIG.timeoutMs },
);
tokenStore.set(data.accessToken);
return data.accessToken;
},
onSessionExpired: () => {
tokenStore.clear();
if (typeof window !== "undefined") window.dispatchEvent(new Event("auth:session-expired"));
},
});