JavaScriptEasy
What is Axios?
Axios is a popular third-party HTTP client library with a promise-based API that adds conveniences on top of the platform's request functions, such as automatic JSON handling, interceptors, rejecting on HTTP errors and instance-wide defaults.
What it adds compared to fetch
- Rejects on HTTP errors (4xx/5xx) by default, so a failed request goes straight to
catch. - Automatic JSON: request bodies are serialised and responses parsed (
response.data). - Interceptors: run code before every request (attach auth tokens) or after every response (refresh tokens, central error logging).
- Instances:
axios.create({ baseURL, timeout, headers })for each API. - Timeouts via a simple option, and upload/download progress events.
- Works the same in the browser and Node.
fetch today
Native fetch is now available everywhere (browsers, Node 18+, Deno, Bun, edge runtimes) and supports AbortSignal.timeout, streaming and the Next.js caching extensions. Many teams now write a 20-line fetch wrapper instead of adding a dependency. Axios still makes sense when you want interceptors and its conventions across a large codebase.
Things to know
- Axios errors carry
error.response(server replied with an error status),error.request(no response) or neither (setup error). - Cancel requests with an
AbortControllersignal (the oldCancelTokenis deprecated). - In Next.js, prefer
fetchin Server Components so you get built-in caching and revalidation.
Code example
js
1// Requires: npm install axios2import axios from "axios";34const api = axios.create({5 baseURL: "https://api.example.com",6 timeout: 5000,7 headers: { Accept: "application/json" },8});910// Attach a token to every request11api.interceptors.request.use((config) => {12 const token = getToken();13 if (token) config.headers.Authorization = `Bearer ${token}`;14 return config;15});1617// Central error handling18api.interceptors.response.use(19 (response) => response,20 (error) => {21 if (error.response?.status === 401) redirectToLogin();22 return Promise.reject(error);23 }24);2526export async function createTodo(title) {27 try {28 const { data } = await api.post("/todos", { title }); // body serialised for you29 return data; // already parsed JSON30 } catch (err) {31 if (err.response) throw new Error(`Server error ${err.response.status}`);32 if (err.request) throw new Error("No response (network or timeout)");33 throw err;34 }35}
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 JavaScript set.