typescriptintermediate
HTTP Client with Axios Interceptors
Pre-configured Axios instance with request/response interceptors for auth headers, logging, and retry logic.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptbeginner
Native HTTP Server
Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.
Best for: Lightweight API server without frameworks
#nodejs#http
javaintermediate
Java Built-in HTTP Server
Create a lightweight HTTP server with com.sun.net.httpserver: routing, JSON responses, file serving.
Best for: Lightweight HTTP servers for testing and prototyping
#java#http
javaintermediate
Spring Boot — RestClient HTTP Calls
Make HTTP requests with Spring RestClient (6.1+): GET, POST, error handling, interceptors, and timeouts.
Best for: REST API consumption in Spring Boot services
#spring-boot#rest-client
scalaintermediate
HTTP Client with sttp
Make HTTP requests with sttp: GET, POST, headers, JSON bodies, and async backends.
Best for: REST API integration
#scala#http