ReactEasy
Axios vs Fetch?
fetch is the built-in Web API available in browsers, Node.js 18+, Deno, Bun and edge runtimes; it returns a Response you parse yourself and does not reject on HTTP errors. Axios is a library (version 1.x) with conveniences: automatic JSON handling, rejecting on non-2xx statuses, interceptors, timeouts, upload progress and instances with base URLs. Many teams now use fetch with a small wrapper.
Differences
fetch | Axios | |
|---|---|---|
| Installation | built in | dependency (adds bundle size) |
| JSON | await res.json() | automatic response.data |
| HTTP errors (404, 500) | resolves; check res.ok | rejects with an AxiosError |
| Request body | JSON.stringify + header | objects serialized automatically |
| Interceptors | write a wrapper | axios.interceptors.request/response |
| Timeout | AbortSignal.timeout(5000) | timeout option |
| Cancellation | AbortController | AbortController (signal) |
| Upload progress | not directly (streams) | onUploadProgress |
| Streaming responses | yes (res.body) | limited in browsers |
| Framework caching (Next.js) | integrates with fetch caching | not covered |
Choosing
fetch: default for most apps, works everywhere and is what frameworks optimize for. Add a 20-line wrapper for base URL, JSON, error throwing and auth headers.- Axios: existing codebases, heavy use of interceptors (token refresh), upload progress, or old browser support.
- Alternatives:
kyandofetchare smallfetchwrappers with Axios-like ergonomics.
Security note
Keep HTTP client libraries updated; Axios has had security fixes (for example SSRF-related issues) that require recent versions.
Code example
tsx
1// fetch with a small wrapper2export async function http<T>(path: string, init: RequestInit & { json?: unknown } = {}): Promise<T> {3 const res = await fetch(`/api${path}`, {4 ...init,5 headers: { "Content-Type": "application/json", ...init.headers },6 body: init.json !== undefined ? JSON.stringify(init.json) : init.body,7 signal: init.signal ?? AbortSignal.timeout(10_000),8 });9 if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`); // fetch does not throw on 4xx/5xx10 return res.status === 204 ? (undefined as T) : res.json();11}1213// const user = await http<{ id: string }>("/users", { method: "POST", json: { name: "Ada" } });1415// Axios equivalent16import axios from "axios";1718export const api = axios.create({ baseURL: "/api", timeout: 10_000 });19api.interceptors.request.use((config) => {20 config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;21 return config;22});23// const { data } = await api.post("/users", { name: "Ada" }); // throws AxiosError on 4xx/5xx
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.