HTTP Clients Core Knowledge
Full Reference: See advanced.md for token refresh flow, retry with exponential backoff, request cancellation, and type-safe API client patterns.
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: http-clients for comprehensive documentation.
Axios Setup
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
timeout: 10000,
headers: { 'Content-Type': 'application/json' },
});
// Request interceptor - add auth token
api.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const token = localStorage.getItem('accessToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor - handle errors
api.interceptors.response.use(
(response) => response,
(error: AxiosError) => {
if (error.response?.status === 401) {
window.location.href = '/login';
}
return Promise.reject(error);
}
);
Fetch API Wrapper
class ApiError extends Error {
constructor(public status: number, public statusText: string, public data?: unknown) {
super(`${status}: ${statusText}`);
}
}
async function fetchWithTimeout(url: string, options: RequestInit & { timeout?: number } = {}): Promise<Response> {
const { timeout = 10000, ...fetchOptions } = options;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
return await fetch(url, { ...fetchOptions, signal: controller.signal });
} finally {
clearTimeout(timeoutId);
}
}
export async function apiFetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const token = localStorage.getItem('accessToken');
const headers: HeadersInit = {
'Content-Type': 'application/json',
...(token && { Authorization: `Bearer ${token}` }),
};
const response = await fetchWithTimeout(`${API_URL}${endpoint}`, { ...options, headers });
if (!response.ok) {
throw new ApiError(response.status, response.statusText);
}
return response.json();
}
ky (Modern Fetch Wrapper)
import ky from 'ky';
const api = ky.create({
prefixUrl: process.env.NEXT_PUBLIC_API_URL,
timeout: 10000,
retry: {
limit: 2,
methods: ['get', 'put', 'delete'],
statusCodes: [408, 429, 500, 502, 503, 504],
},
hooks: {
beforeRequest: [
(request) => {
const token = localStorage.getItem('accessToken');
if (token) {
request.headers.set('Authorization', `Bearer ${token}`);
}
},
],
},
});
// Usage
const users = await api.get('users').json<User[]>();
const user = await api.post('users', { json: newUser }).json<User>();
ofetch (Universal Fetch)
import { ofetch } from 'ofetch';
const api = ofetch.create({
baseURL: process.env.NUXT_PUBLIC_API_URL,
retry: 2,
retryDelay: 500,
timeout: 10000,
async onRequest({ options }) {
const token = localStorage.getItem('accessToken');
if (token) {
options.headers = { ...options.headers, Authorization: `Bearer ${token}` };
}
},
});
// Works in Node.js and browser
const users = await api<User[]>('/users');
When NOT to Use This Skill
- Axios-specific configuration (use
axios skill)
- GraphQL client setup (use
graphql-codegen skill)
- tRPC client configuration (use
trpc skill)
- WebSocket or Server-Sent Events
Anti-Patterns
| Anti-Pattern |
Why It's Bad |
Solution |
| No timeout configured |
Hanging requests |
Set timeout on all clients |
| Hardcoded API URLs |
Environment coupling |
Use environment variables |
| No retry logic |
Poor UX on transient failures |
Implement exponential backoff |
| Ignoring token expiration |
401 errors |
Implement token refresh flow |
| Not canceling on unmount |
Memory leaks |
Use AbortController cleanup |
| Not typing responses |
Runtime errors |
Use TypeScript generics |
Quick Troubleshooting
| Issue |
Possible Cause |
Solution |
| CORS errors |
Server misconfiguration |
Configure CORS on backend |
| 401 after some time |
Token expired |
Implement token refresh |
| Memory leaks |
Not aborting on unmount |
Add cleanup in useEffect |
| Network timeout |
Server slow |
Increase timeout, add retry |
| Infinite refresh loop |
Refresh returns 401 |
Exclude refresh from interceptor |
Production Checklist
Reference Documentation
- Axios Configuration
- Fetch Patterns
- ky and ofetch
1---2name: http-clients3description: |4 HTTP clients for frontend and Node.js. Covers Axios, Fetch API, ky, and ofetch.5 Includes interceptors, error handling, retry logic, and auth token management.6 Use for configuring API clients and HTTP communication.78 USE WHEN: user mentions "HTTP client", "Fetch API", "ky", "ofetch", "HTTP wrapper",9 "retry logic", "token refresh", asks about "which HTTP client to use",10 "HTTP request library", "API client setup", "request interceptors"1112 DO NOT USE FOR: Axios-specific questions - use `axios` instead; GraphQL - use `graphql-codegen` instead;13 tRPC - use `trpc` instead; WebSocket connections14allowed-tools: Read, Grep, Glob, Write, Edit15metadata:16 source: https://skillmd.com/skills/claude-dev-suite/http-clients17---1819# HTTP Clients Core Knowledge2021> **Full Reference**: See [advanced.md](advanced.md) for token refresh flow, retry with exponential backoff, request cancellation, and type-safe API client patterns.2223> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `http-clients` for comprehensive documentation.2425## Axios Setup2627```typescript28import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';2930const api = axios.create({31 baseURL: process.env.NEXT_PUBLIC_API_URL,32 timeout: 10000,33 headers: { 'Content-Type': 'application/json' },34});3536// Request interceptor - add auth token37api.interceptors.request.use(38 (config: InternalAxiosRequestConfig) => {39 const token = localStorage.getItem('accessToken');40 if (token) {41 config.headers.Authorization = `Bearer ${token}`;42 }43 return config;44 },45 (error) => Promise.reject(error)46);4748// Response interceptor - handle errors49api.interceptors.response.use(50 (response) => response,51 (error: AxiosError) => {52 if (error.response?.status === 401) {53 window.location.href = '/login';54 }55 return Promise.reject(error);56 }57);58```5960## Fetch API Wrapper6162```typescript63class ApiError extends Error {64 constructor(public status: number, public statusText: string, public data?: unknown) {65 super(`${status}: ${statusText}`);66 }67}6869async function fetchWithTimeout(url: string, options: RequestInit & { timeout?: number } = {}): Promise<Response> {70 const { timeout = 10000, ...fetchOptions } = options;71 const controller = new AbortController();72 const timeoutId = setTimeout(() => controller.abort(), timeout);7374 try {75 return await fetch(url, { ...fetchOptions, signal: controller.signal });76 } finally {77 clearTimeout(timeoutId);78 }79}8081export async function apiFetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {82 const token = localStorage.getItem('accessToken');83 const headers: HeadersInit = {84 'Content-Type': 'application/json',85 ...(token && { Authorization: `Bearer ${token}` }),86 };8788 const response = await fetchWithTimeout(`${API_URL}${endpoint}`, { ...options, headers });8990 if (!response.ok) {91 throw new ApiError(response.status, response.statusText);92 }9394 return response.json();95}96```9798## ky (Modern Fetch Wrapper)99100```typescript101import ky from 'ky';102103const api = ky.create({104 prefixUrl: process.env.NEXT_PUBLIC_API_URL,105 timeout: 10000,106 retry: {107 limit: 2,108 methods: ['get', 'put', 'delete'],109 statusCodes: [408, 429, 500, 502, 503, 504],110 },111 hooks: {112 beforeRequest: [113 (request) => {114 const token = localStorage.getItem('accessToken');115 if (token) {116 request.headers.set('Authorization', `Bearer ${token}`);117 }118 },119 ],120 },121});122123// Usage124const users = await api.get('users').json<User[]>();125const user = await api.post('users', { json: newUser }).json<User>();126```127128## ofetch (Universal Fetch)129130```typescript131import { ofetch } from 'ofetch';132133const api = ofetch.create({134 baseURL: process.env.NUXT_PUBLIC_API_URL,135 retry: 2,136 retryDelay: 500,137 timeout: 10000,138139 async onRequest({ options }) {140 const token = localStorage.getItem('accessToken');141 if (token) {142 options.headers = { ...options.headers, Authorization: `Bearer ${token}` };143 }144 },145});146147// Works in Node.js and browser148const users = await api<User[]>('/users');149```150151## When NOT to Use This Skill152153- Axios-specific configuration (use `axios` skill)154- GraphQL client setup (use `graphql-codegen` skill)155- tRPC client configuration (use `trpc` skill)156- WebSocket or Server-Sent Events157158## Anti-Patterns159160| Anti-Pattern | Why It's Bad | Solution |161|--------------|--------------|----------|162| No timeout configured | Hanging requests | Set timeout on all clients |163| Hardcoded API URLs | Environment coupling | Use environment variables |164| No retry logic | Poor UX on transient failures | Implement exponential backoff |165| Ignoring token expiration | 401 errors | Implement token refresh flow |166| Not canceling on unmount | Memory leaks | Use AbortController cleanup |167| Not typing responses | Runtime errors | Use TypeScript generics |168169## Quick Troubleshooting170171| Issue | Possible Cause | Solution |172|-------|----------------|----------|173| CORS errors | Server misconfiguration | Configure CORS on backend |174| 401 after some time | Token expired | Implement token refresh |175| Memory leaks | Not aborting on unmount | Add cleanup in useEffect |176| Network timeout | Server slow | Increase timeout, add retry |177| Infinite refresh loop | Refresh returns 401 | Exclude refresh from interceptor |178179## Production Checklist180181- [ ] Base URL via environment182- [ ] Request timeout configured183- [ ] Auth token interceptor184- [ ] Token refresh logic185- [ ] Error response handling186- [ ] Retry with exponential backoff187- [ ] Request cancellation on unmount188- [ ] Type-safe API methods189190## Reference Documentation191- [Axios Configuration](quick-ref/axios.md)192- [Fetch Patterns](quick-ref/fetch.md)193- [ky and ofetch](quick-ref/ky-ofetch.md)