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: HTTP clients for frontend and Node.js. Covers Axios, Fetch API, ky, and ofetch. Includes interceptors, error handling, retry logic, and auth token management. Use for configuring API clients and HTTP communication. USE WHEN: user mentions "HTTP client", "Fetch API", "ky", "ofetch", "HTTP wrapper", "retry logic", "token refresh", asks about "which HTTP client to use", "HTTP request library", "API client setup", "request interceptors" DO NOT USE FOR: Axios-specific questions - use `axios` instead; GraphQL - use `graphql-codegen` instead; tRPC - use `trpc` instead; WebSocket connections4---5# HTTP Clients Core Knowledge67> **Full Reference**: See [advanced.md](advanced.md) for token refresh flow, retry with exponential backoff, request cancellation, and type-safe API client patterns.89> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `http-clients` for comprehensive documentation.1011## Axios Setup1213```typescript14import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';1516const api = axios.create({17 baseURL: process.env.NEXT_PUBLIC_API_URL,18 timeout: 10000,19 headers: { 'Content-Type': 'application/json' },20});2122// Request interceptor - add auth token23api.interceptors.request.use(24 (config: InternalAxiosRequestConfig) => {25 const token = localStorage.getItem('accessToken');26 if (token) {27 config.headers.Authorization = `Bearer ${token}`;28 }29 return config;30 },31 (error) => Promise.reject(error)32);3334// Response interceptor - handle errors35api.interceptors.response.use(36 (response) => response,37 (error: AxiosError) => {38 if (error.response?.status === 401) {39 window.location.href = '/login';40 }41 return Promise.reject(error);42 }43);44```4546## Fetch API Wrapper4748```typescript49class ApiError extends Error {50 constructor(public status: number, public statusText: string, public data?: unknown) {51 super(`${status}: ${statusText}`);52 }53}5455async function fetchWithTimeout(url: string, options: RequestInit & { timeout?: number } = {}): Promise<Response> {56 const { timeout = 10000, ...fetchOptions } = options;57 const controller = new AbortController();58 const timeoutId = setTimeout(() => controller.abort(), timeout);5960 try {61 return await fetch(url, { ...fetchOptions, signal: controller.signal });62 } finally {63 clearTimeout(timeoutId);64 }65}6667export async function apiFetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {68 const token = localStorage.getItem('accessToken');69 const headers: HeadersInit = {70 'Content-Type': 'application/json',71 ...(token && { Authorization: `Bearer ${token}` }),72 };7374 const response = await fetchWithTimeout(`${API_URL}${endpoint}`, { ...options, headers });7576 if (!response.ok) {77 throw new ApiError(response.status, response.statusText);78 }7980 return response.json();81}82```8384## ky (Modern Fetch Wrapper)8586```typescript87import ky from 'ky';8889const api = ky.create({90 prefixUrl: process.env.NEXT_PUBLIC_API_URL,91 timeout: 10000,92 retry: {93 limit: 2,94 methods: ['get', 'put', 'delete'],95 statusCodes: [408, 429, 500, 502, 503, 504],96 },97 hooks: {98 beforeRequest: [99 (request) => {100 const token = localStorage.getItem('accessToken');101 if (token) {102 request.headers.set('Authorization', `Bearer ${token}`);103 }104 },105 ],106 },107});108109// Usage110const users = await api.get('users').json<User[]>();111const user = await api.post('users', { json: newUser }).json<User>();112```113114## ofetch (Universal Fetch)115116```typescript117import { ofetch } from 'ofetch';118119const api = ofetch.create({120 baseURL: process.env.NUXT_PUBLIC_API_URL,121 retry: 2,122 retryDelay: 500,123 timeout: 10000,124125 async onRequest({ options }) {126 const token = localStorage.getItem('accessToken');127 if (token) {128 options.headers = { ...options.headers, Authorization: `Bearer ${token}` };129 }130 },131});132133// Works in Node.js and browser134const users = await api<User[]>('/users');135```136137## When NOT to Use This Skill138139- Axios-specific configuration (use `axios` skill)140- GraphQL client setup (use `graphql-codegen` skill)141- tRPC client configuration (use `trpc` skill)142- WebSocket or Server-Sent Events143144## Anti-Patterns145146| Anti-Pattern | Why It's Bad | Solution |147|--------------|--------------|----------|148| No timeout configured | Hanging requests | Set timeout on all clients |149| Hardcoded API URLs | Environment coupling | Use environment variables |150| No retry logic | Poor UX on transient failures | Implement exponential backoff |151| Ignoring token expiration | 401 errors | Implement token refresh flow |152| Not canceling on unmount | Memory leaks | Use AbortController cleanup |153| Not typing responses | Runtime errors | Use TypeScript generics |154155## Quick Troubleshooting156157| Issue | Possible Cause | Solution |158|-------|----------------|----------|159| CORS errors | Server misconfiguration | Configure CORS on backend |160| 401 after some time | Token expired | Implement token refresh |161| Memory leaks | Not aborting on unmount | Add cleanup in useEffect |162| Network timeout | Server slow | Increase timeout, add retry |163| Infinite refresh loop | Refresh returns 401 | Exclude refresh from interceptor |164165## Production Checklist166167- [ ] Base URL via environment168- [ ] Request timeout configured169- [ ] Auth token interceptor170- [ ] Token refresh logic171- [ ] Error response handling172- [ ] Retry with exponential backoff173- [ ] Request cancellation on unmount174- [ ] Type-safe API methods175176## Reference Documentation177- [Axios Configuration](quick-ref/axios.md)178- [Fetch Patterns](quick-ref/fetch.md)179- [ky and ofetch](quick-ref/ky-ofetch.md)