Building an API Client
A reusable, type-safe API client class with interceptors, base URL, and automatic auth
Skills taught: api.api-client-class, api.request-interceptor, api.response-interceptor, api.token-refresh
A production-ready API client
class ApiError extends Error {
constructor(public status: number, public body: unknown) {
super(typeof body === 'object' && body !== null && 'message' in body
? String((body as any).message) : `HTTP ${status}`);
this.name = 'ApiError';
}
}
type Options = Omit<RequestInit, 'body'> & { body?: unknown };
class ApiClient {
private token: string | null = null;
private refreshing: Promise<string> | null = null;
private requestInterceptors: ((config: RequestInit) => RequestInit)[] = [];
private responseInterceptors: ((res: Response) => Response)[] = [];
constructor(
private baseUrl: string,
private defaultTimeout = 10_000,
) {
// Default: inject auth header
this.use(config => ({
...config,
headers: {
...config.headers,
...(this.token ? { 'Authorization': `Bearer ${this.token}` } : {}),
'X-Request-ID': crypto.randomUUID(),
},
}));
}
/** Set the access token */
setToken(token: string | null) { this.token = token; }
/** Add a request interceptor */
use(fn: (config: RequestInit) => RequestInit) {
this.requestInterceptors.push(fn);
return this;
}
private async request<T>(method: string, path: string, opts: Options = {}): Promise<T> {
const { body, ...rest } = opts;
let config: RequestInit = {
method,
signal: AbortSignal.timeout(this.defaultTimeout),
...rest,
headers: {
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
...rest.headers,
},
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
};
// Apply request interceptors
config = this.requestInterceptors.reduce((c, fn) => fn(c), config);
let res: Response;
try {
res = await fetch(this.baseUrl + path, config);
} catch (err: any) {
throw err.name === 'AbortError'
? new Error('Request timed out')
: new Error('Network error');
}
// Auto token refresh on 401
if (res.status === 401 && this.token && !path.includes('/auth/')) {
try {
const newToken = await this.refreshToken();
this.setToken(newToken);
config.headers = { ...(config.headers as object), 'Authorization': `Bearer ${newToken}` };
res = await fetch(this.baseUrl + path, config);
} catch {
this.setToken(null);
throw new ApiError(401, { message: 'Session expired — please log in again' });
}
}
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new ApiError(res.status, body);
}
if (res.status === 204) return null as T;
return res.json();
}
private async refreshToken(): Promise<string> {
// Deduplicate: if already refreshing, wait for it
if (this.refreshing) return this.refreshing;
this.refreshing = this.request<{ token: string }>('POST', '/auth/refresh')
.then(r => r.token)
.finally(() => { this.refreshing = null; });
return this.refreshing;
}
get<T>(path: string, opts?: Options) { return this.request<T>('GET', path, opts); }
post<T>(path: string, body: unknown) { return this.request<T>('POST', path, { body }); }
patch<T>(path: string, body: unknown) { return this.request<T>('PATCH', path, { body }); }
put<T>(path: string, body: unknown) { return this.request<T>('PUT', path, { body }); }
del<T>(path: string) { return this.request<T>('DELETE', path); }
}
// ── Usage ──
export const api = new ApiClient('https://api.example.com');
// After login:
api.setToken(loginResponse.token);
// Type-safe calls:
const user = await api.get<User>('/users/me');
const created = await api.post<Post>('/posts', { title: 'Hello', body: 'World' });
await api.del(`/posts/${postId}`);
Frequently Asked Questions
Should I build my own API client or use Axios?
Both work. **fetch()**: built into every browser and Node.js 18+ — no dependency needed. Handles all modern use cases. The client in this lesson is ~60 lines. **Axios**: well-tested library with interceptors, automatic JSON parsing, progress events, request cancellation. Adds ~14KB. **TanStack Query / SWR**: if your main concern is async state (loading states, caching, background refresh), these solve more problems than a plain client. In practice: build your own fetch wrapper for new projects — you understand every line. Use Axios if your team knows it well. Use TanStack Query for React apps with complex data fetching.