Explain it simply
Axios in plain language
Axios is a popular JavaScript library for sending HTTP requests. Unlike fetch, it is not built into browsers or Node, so you add it with npm install axios. Think of it as conveniences layered on the same job: it converts JSON automatically, throws on 404 and 500, has a timeout option, and offers interceptors that run your code on every request.
fetch is like an engine: powerful and available everywhere, but you assemble more yourself. Axios is like a car that already has GPS and cruise control: easier to drive, but you have to buy it, as a dependency, and keep it updated.
Problem → Why → Solution
The problem: a retry interceptor that never stops
When the access token expires you get a 401, so you write a response interceptor that refreshes the token and resends the request. It works on normal days. But on the day the refresh token itself has expired, the retried request gets another 401, so the interceptor refreshes and retries again, and again. The browser tab fires thousands of requests until the API rate-limits it.
import axios from "axios";
const api = axios.create({ baseURL: "/api" });
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
await refreshToken();
return api(error.config); // retries forever if the 401 comes back
}
return Promise.reject(error);
},
);Why it loops
The retried request passes through the very same interceptor. Without a marker recording that a request has already been retried, every 401 starts a new retry. The fix is to set a marker such as _retry on the config and never retry a request that already carries it, or to cap a retry count.
Core concept: one place for config, one shape for responses
Every axios function returns a Promise. The response from axios.get(url, config) or axios.post(url, data, config) carries data (the already-parsed body), status, headers and config, so there is no extra await response.json() as with fetch. When you POST a plain object as data, axios serialises it to JSON and sets the Content-Type header for you. Query strings can be passed as { params: { page: 2 } }.
The biggest difference from fetch is error handling. By default axios rejects for every status outside 2xx, which the validateStatus option can change. The error object separates three situations: if error.response exists, the server answered with an error status; if there is no error.response but there is error.request, the request went out and no response came back (network failure or timeout); if neither exists, something failed while setting up the request. axios.isAxiosError(error) tells you whether an error came from axios.
axios.create({ baseURL, timeout, headers }) makes an instance with shared settings. The default timeout is 0, meaning none, so set one yourself. Interceptors let you run code before every request leaves an instance (request interceptors) and after every response arrives (response interceptors): adding auth headers, normalising errors, refreshing tokens. To cancel a request, current versions accept an AbortController signal just like fetch; the older CancelToken API is deprecated.
The API is the same wherever axios runs: one piece of code works in browsers and in Node.js, and behind the scenes axios picks an adapter that suits the environment. It is still a dependency, though, so it adds to your bundle size and you must keep up with its security updates; add it when you will really use these features.
| Task | fetch | axios |
|---|---|---|
| Install | built in | npm install axios |
| Read a JSON body | await res.json() | res.data |
| 404 / 500 | fulfils; check res.ok | rejects; error.response |
| Timeout | AbortController | timeout option |
| Hook every request | your own wrapper | interceptors |
- Instance holds baseURL and timeout
- Request interceptor adds headers
- Non-2xx statuses reject
- Response interceptor shapes errors
- The caller receives response.data
A request resent from an interceptor passes through the interceptor again; always keep a marker.
General pattern (with axios installed)
import axios from "axios";
const api = axios.create({ baseURL: "https://api.example.com", timeout: 5000 });
api.interceptors.request.use((config) => {
config.headers.Authorization = `Bearer ${getToken()}`;
return config;
});
const { data } = await api.get("/posts", { params: { page: 1 } });
const created = await api.post("/posts", { title: "Hi" }); // JSON bodyCreate one instance with shared settings, put per-request needs in an interceptor, then call get and post with short paths. This code needs the axios package, which is why the runnable examples in this lesson use a fetch-based client instead.
Worked example: an axios-style client built on fetch
This is not the real axios: it is a small client written with fetch to make visible what axios does on top of fetch, namely joining baseURL, serialising JSON, exposing response.data, rejecting non-2xx responses with error.response attached, and adding a timeout. It shows a failure as well as a success, because error handling is where axios differs most from plain fetch. A stub server means it runs with no npm install and no network. The error message follows axios's own wording.
// NOT the real axios: a small fetch-based client that copies axios's API
// shape, so this file runs in plain Node with no npm install.
function createClient({ baseURL = "", timeout = 0, headers = {}, fetchFn = fetch } = {}) {
async function request(method, url, data) {
const controller = new AbortController();
const timer = timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null;
const allHeaders = { Accept: "application/json", ...headers };
if (data !== undefined) allHeaders["Content-Type"] = "application/json";
try {
const res = await fetchFn(baseURL + url, {
method,
headers: allHeaders,
body: data === undefined ? undefined : JSON.stringify(data), // like axios
signal: controller.signal,
});
const text = await res.text();
const response = { status: res.status, data: text ? JSON.parse(text) : null };
if (res.status < 200 || res.status >= 300) {
// like axios: non-2xx statuses reject, with the response attached
const error = new Error(`Request failed with status code ${res.status}`);
error.response = response;
throw error;
}
return response;
} finally {
if (timer) clearTimeout(timer);
}
}
return {
get: (url) => request("GET", url),
post: (url, data) => request("POST", url, data),
};
}
// Stub server so the example is deterministic and needs no network
async function fakeFetch(url, { method, body }) {
const path = new URL(url).pathname;
if (method === "GET" && path === "/posts/1") {
return Response.json({ id: 1, title: "Sample Post" });
}
if (method === "POST" && path === "/posts") {
return Response.json({ id: 2, ...JSON.parse(body) }, { status: 201 });
}
return Response.json({ message: "Not found" }, { status: 404 });
}
const api = createClient({
baseURL: "https://api.example.com",
timeout: 5000,
fetchFn: fakeFetch,
});
async function main() {
const res = await api.get("/posts/1");
console.log("Status:", res.status);
console.log("Data:", res.data);
const created = await api.post("/posts", { title: "New Post", body: "Content here" });
console.log("Created:", created.status, created.data);
try {
await api.get("/posts/99");
} catch (error) {
console.log("Error:", error.message);
console.log("Server said:", error.response.status, error.response.data);
}
}
main();Code breakdown
- Shared config
function createClient({ baseURL = "", timeout = 0, headers = {}, fetchFn = fetch } = {}) {Like axios.create, baseURL, timeout and headers are given once and shared by every request on the client. The default timeout of 0 means 'no limit', as in axios.
- Automatic JSON body
body: data === undefined ? undefined : JSON.stringify(data), // like axiosThe caller passes a plain object and the client stringifies it and sets Content-Type. With bare fetch you would do both yourself.
- Reject non-2xx
if (res.status < 200 || res.status >= 300) {Like axios's default validateStatus, anything outside 2xx throws, with the status and the server's data placed on error.response.
- Read response.data
console.log("Data:", res.data);The client has already parsed the body, so the caller reads res.data directly without awaiting json().
- Inspect the failure
console.log("Server said:", error.response.status, error.response.data);For the 404, the catch block reads the server's status and message from error.response, the same shape a real axios error has.
Status: 200
Data: { id: 1, title: 'Sample Post' }
Created: 201 { id: 2, title: 'New Post', body: 'Content here' }
Error: Request failed with status code 404
Server said: 404 { message: 'Not found' }Handling the three error cases in real axios
In a real project, checking an axios error always follows the same order: look for a response first, then for a request, and only then treat it as a setup error. The table suggests what to show the user in each branch. If you aborted the request yourself, axios.isCancel(error) is true and you can skip the message quietly.
| Check | Meaning | What to show |
|---|---|---|
| error.response | server answered 4xx or 5xx | a message per status |
| error.request | no response (network, timeout) | 'check your connection' |
| neither | bad config or a code bug | log it, show a generic error |
In real projects
Axios in real projects
Most projects that use axios create a single instance in a file such as src/api/client.js and import it across the app. The base URL, timeout, auth interceptor and error-normalising interceptor are written once, in that file.
- A request interceptor puts the stored access token into the Authorization header, and a response interceptor tries a refresh only once per 401. If the refresh also fails, it sends the user to the login page.
- A response interceptor turns every axios error into one app-specific shape such as { status, message }, so components never need to know about axios.
- Before adding the library, weigh its bundle size and maintenance. For an app with only a few requests, a small wrapper around fetch is often enough.
Common mistakes
Common mistakes with axios
An interceptor retry without a marker
Refreshing and retrying on every 401 sends requests without end on the day the refresh itself fails. Set a marker such as error.config._retry = true and reject requests that already carry it. Never retry the /refresh endpoint itself either.
Calling response.json() out of fetch habit
An axios response has no json() method; the body is already parsed in response.data. Converting fetch code to axios often produces a 'response.json is not a function' TypeError.
Checking status instead of catching
Axios rejects for 404 and 500, so a check like if (res.status !== 200) never sees an error: execution jumps straight to the catch. Catch the error with try/catch and read error.response?.status there.
Best practices
Best practices
- Create one axios instance for the app instead of changing the global axios defaults.
- Set a timeout on every instance; the default of 0 waits forever.
- Whenever an interceptor resends a request, always check a marker or a count first.
Mini challenge
Mini challenge: a client that refreshes only once
Write, in a fetch-based client, what two axios interceptors would do: add an Authorization header to every request (request interceptor), and on a 401 refresh the token and retry exactly once (response interceptor). Show with a request count that a refresh returning a bad token does not cause a loop.
- withAuth returns a new config with the Authorization header, without mutating the original
- send calls refreshToken and resends with _retry: true only on a 401 when config._retry is not set
- Other non-2xx responses throw "Request failed with status code N" with error.response attached
- Both scenarios make exactly 3 requests: original, refresh, retry
// Fake auth server: /me needs "Bearer fresh-token"; /refresh hands out tokens.
let requests = 0;
let refreshGivesBadToken = false;
async function authServer(url, { headers = {} } = {}) {
requests += 1;
const path = new URL(url).pathname;
if (path === "/refresh") {
const token = refreshGivesBadToken ? "still-bad" : "fresh-token";
return Response.json({ token });
}
if (headers.Authorization !== "Bearer fresh-token") {
return Response.json({ message: "token expired" }, { status: 401 });
}
return Response.json({ id: 7, name: "Aung Kyaw" });
}
function createApi({ baseURL, fetchFn, getToken, refreshToken }) {
const withAuth = (config) => {
// TODO: return a copy of config whose headers include Authorization
};
async function send(config) {
// TODO: fetch baseURL + config.url with withAuth(config), parse JSON
// TODO: ok -> return { status, data }
// TODO: 401 and no config._retry -> await refreshToken(), resend once
// TODO: otherwise throw an axios-style error with error.response
}
return { get: (url) => send({ url, method: "GET", headers: {} }) };
}
// TODO: let token = "expired-token"; build api with a refreshToken that
// calls /refresh and stores the new token
// TODO: main(): 1) get /me and print data + request count
// 2) reset token, set refreshGivesBadToken = true, requests = 0,
// get /me again and print the error message + request countExpected: Two lines: first try: { id: 7, name: 'Aung Kyaw' } (3 requests) and second try: Request failed with status code 401 (3 requests, no loop).
Show hint
Resend a new config, { ...config, _retry: true }, so a second 401 sees the marker and throws. Have refreshToken call fetchFn directly rather than send, so the refresh request is never retried.
Show solution
// Fake auth server: /me needs "Bearer fresh-token"; /refresh hands out tokens.
let requests = 0;
let refreshGivesBadToken = false;
async function authServer(url, { headers = {} } = {}) {
requests += 1;
const path = new URL(url).pathname;
if (path === "/refresh") {
const token = refreshGivesBadToken ? "still-bad" : "fresh-token";
return Response.json({ token });
}
if (headers.Authorization !== "Bearer fresh-token") {
return Response.json({ message: "token expired" }, { status: 401 });
}
return Response.json({ id: 7, name: "Aung Kyaw" });
}
function createApi({ baseURL, fetchFn, getToken, refreshToken }) {
// request "interceptor": runs before every request
const withAuth = (config) => ({
...config,
headers: { ...config.headers, Authorization: `Bearer ${getToken()}` },
});
async function send(config) {
const res = await fetchFn(baseURL + config.url, withAuth(config));
const data = await res.json();
if (res.ok) return { status: res.status, data };
// response "interceptor": refresh once on 401, never loop
if (res.status === 401 && !config._retry) {
await refreshToken();
return send({ ...config, _retry: true });
}
const error = new Error(`Request failed with status code ${res.status}`);
error.response = { status: res.status, data };
throw error;
}
return { get: (url) => send({ url, method: "GET", headers: {} }) };
}
let token = "expired-token";
const api = createApi({
baseURL: "https://api.example.com",
fetchFn: authServer,
getToken: () => token,
refreshToken: async () => {
const res = await authServer("https://api.example.com/refresh");
token = (await res.json()).token;
},
});
async function main() {
const me = await api.get("/me");
console.log("first try:", me.data, `(${requests} requests)`);
token = "expired-token";
refreshGivesBadToken = true;
requests = 0;
try {
await api.get("/me");
} catch (error) {
console.log("second try:", error.message, `(${requests} requests, no loop)`);
}
}
main();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Axios is an npm package that gives the parsed body in response.data and serialises object data to JSON for you.
- Unlike fetch, axios rejects on non-2xx; distinguish error.response, error.request and setup errors.
- Keep baseURL, a timeout (the default is 0, none) and interceptors together in one axios.create instance.
- Guard every retry inside an interceptor with a marker such as _retry or a count to prevent loops.