typescriptintermediate

HTTP Client with Axios Interceptors

Pre-configured Axios instance with request/response interceptors for auth headers, logging, and retry logic.

typescript
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.