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

fetchAxios
Installationbuilt independency (adds bundle size)
JSONawait res.json()automatic response.data
HTTP errors (404, 500)resolves; check res.okrejects with an AxiosError
Request bodyJSON.stringify + headerobjects serialized automatically
Interceptorswrite a wrapperaxios.interceptors.request/response
TimeoutAbortSignal.timeout(5000)timeout option
CancellationAbortControllerAbortController (signal)
Upload progressnot directly (streams)onUploadProgress
Streaming responsesyes (res.body)limited in browsers
Framework caching (Next.js)integrates with fetch cachingnot 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: ky and ofetch are small fetch wrappers 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 wrapper
2export 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/5xx
10 return res.status === 204 ? (undefined as T) : res.json();
11}
12
13// const user = await http<{ id: string }>("/users", { method: "POST", json: { name: "Ada" } });
14
15// Axios equivalent
16import axios from "axios";
17
18export 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.

Open in study app