What is the difference between fetch and axios?
Axios is built on top of the fetch equivalent in the browser, and it adds the things that fetch leaves to you. There are six differences worth knowing.
// Both libraries share the same underlying idea: a promise of a response.
// Here is the raw fetch shape.
async function fetchJson(url) {
const response = await fetch(url, {
method: "GET",
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
// The same idea with axios, which throws on a bad status by default:
// const response = await axios.get(url, { timeout: 2000 });
// console.log(response.data);
// And the error shapes are different.
try {
throw new Error("Request failed with status 500");
} catch (err) {
console.log(err.message); // "Request failed with status 500"
}
console.log(typeof fetchJson); // "function"Error handling. Fetch resolves for any response, including a 404 or a 500, so you have to check the ok property yourself. Axios rejects by default when the status is outside the two hundreds, and the error it throws already carries the response, the status and the data.
Timeouts. Fetch has no timeout option. You have to build one with an abort controller and race it against the request. Axios takes a timeout directly.
Interceptors. Axios lets you attach a handler that runs before every request and after every response, which is where you put authentication headers, logging and error normalisation. Fetch has no equivalent, so you write a wrapper function instead.
Data handling. Axios serialises a plain object into a JSON body and sets the content type for you. Fetch does not, so you call the json method on the request options and set the header yourself. The other side of the difference is that axios parses JSON responses automatically, while fetch gives you the raw body to parse.
Cancellation. Fetch uses the standard abort signal, which is a platform feature. Axios has its own cancellation object as well as supporting the abort signal, so it works either way.
Size. Fetch is built into the platform, so it costs nothing to download. Axios is a dependency, roughly fifteen kilobytes compressed.