HTTP Client with Axios Interceptors
Pre-configured Axios instance with request/response interceptors for auth headers, logging, and retry logic.
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
const client = axios.create({
baseURL: process.env.API_BASE_URL,
timeout: 10_000,
headers: { 'Content-Type': 'application/json' },
});
client.interceptors.request.use((config: InternalAxiosRequestConfig) => {
const token = process.env.API_TOKEN;
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
client.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const config = error.config;
const retryCount = (config as any)?.__retryCount ?? 0;
if (error.response?.status === 429 && retryCount < 3) {
(config as any).__retryCount = retryCount + 1;
const delay = Math.pow(2, retryCount) * 1000;
await new Promise((r) => setTimeout(r, delay));
return client(config!);
}
return Promise.reject(error);
}
);
export default client;
// Usage:
// const { data } = await client.get('/users');
// const { data } = await client.post('/users', { name: 'Ada' });Use Cases
- Consuming third-party APIs
- Microservice communication
- Automatic retry on rate limits
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Optimistic Update Pattern
Apply UI changes immediately before server confirmation with automatic rollback on failure.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Streaming API Response
Stream long-running API responses using ReadableStream and TransformStream for real-time data delivery.
Async HTTP Client with httpx
Production-ready async HTTP client using httpx with retries, timeouts, and connection pooling.