Axios vs fetch
Axios and fetch both request a URL and return a promise. fetch is part of the browser platform and of Node.js 18 and later. Axios is the axios package. The axios vs fetch choice shows up on the first call, because one of them parses JSON and rejects HTTP error statuses for you, and the other leaves both steps to your code.
The examples below use axios 1.21.1.
A GET request
axios.get reads the response body before it resolves. fetch resolves when the headers arrive, and you read the body with a second call.
const axiosResponse = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
console.log(axiosResponse.data);
const fetchResponse = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const fetchData = await fetchResponse.json();
console.log(fetchData);
axios.get sends the GET and resolves to an object. data is the body. With the default transform, a string body goes through JSON.parse. If the text is not JSON, axios leaves it as a string, because silent JSON parsing is on unless you set responseType: "json" and turn transitional.silentJSONParsing off. status, statusText, headers, config, and request sit on that same object.
fetch resolves to a Response. json() reads the stream and parses it. The Fetch standard types that method as Promise<any>, so the parsed value is not checked against a type you pass in. response.json(), response.text(), and response.blob() each consume the body. After that call, bodyUsed is true, and a second read throws.
Axios can type that body from the call. axios.get<Post>(url) types response.data as Post. The types ship in the package.
A POST request
Pass axios a plain object and it sends JSON. fetch has no such step. Its body is a string, Blob, BufferSource, FormData, URLSearchParams, or ReadableStream.
await axios.post("https://example.com/users", { name: "ada" });
await fetch("https://example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "ada" }),
});
axios.post takes the URL and the data. The default request transform sees a plain object, sets Content-Type to application/json when that header is still empty, and sends JSON.stringify of the object. A string is not treated as JSON. On post, put, and patch, a string body that still has no Content-Type is sent as application/x-www-form-urlencoded.
The fetch call sets method because the default is GET. JSON.stringify produces the body string. The header tells the server the bytes are JSON. A string body with no Content-Type is text/plain;charset=UTF-8, which is the type the Fetch standard assigns to a string.
The same shape exists for the other methods. Axios exposes get, post, put, patch, delete, head, and options. Anything past a GET on fetch goes through the init object.
A reused base URL is an axios instance.
const api = axios.create({
baseURL: "https://example.com",
timeout: 5000,
headers: { "X-Custom-Header": "foobar" },
});
const response = await api.get("/users/1");
axios.create copies that config onto the instance. api.get("/users/1") joins it to the base URL. fetch has no instance object. A small function that calls fetch with the same prefix and headers is the stand-in.
HTTP error statuses
Axios rejects the promise when the status is outside 200 to 299. fetch does not. A 404 or a 500 still fulfills fetch, and the promise rejects when the request fails before a response arrives.
try {
const response = await axios.get("https://example.com/missing");
console.log(response.data);
} catch (error) {
if (error.response) {
console.log(error.response.status, error.response.data);
}
}
const response = await fetch("https://example.com/missing");
if (!response.ok) {
throw new Error("Response status: " + response.status);
}
const data = await response.json();
The default validateStatus returns true only when status >= 200 && status < 300. A 404 fails that check, so axios.get rejects with an AxiosError. On a 404 from the server, error.response is the response, error.response.status is 404, and error.response.data is the parsed body. The code is ERR_BAD_REQUEST. If error.response is missing and error.request is set, the call was sent and no response arrived. error.message is the short description on the error.
fetch assigns the status on the Response and sets ok to false outside 200 to 299. The if throws before json(), so the caller does not treat an error page as data. Skip that check and a 404 looks like success.
To make axios resolve a 404, pass a different validateStatus. This one accepts every status below 500:
await axios.get("https://example.com/missing", {
validateStatus(status) {
return status < 500;
},
});
Interceptors
An interceptor is a function axios runs on every request or response for that instance. fetch does not have one. You wrap fetch, or you replace the global function.
const token = "token";
axios.interceptors.request.use(function (config) {
config.headers.Authorization = "Bearer " + token;
return config;
});
axios.interceptors.response.use(
function (response) {
return response;
},
function (error) {
return Promise.reject(error);
}
);
token is the credential string. The request function runs before the request is sent. It returns the config, including the Authorization header added on this line. The first response function runs for a 2xx response and returns that response. The second runs for a status outside 2xx and returns a rejected promise, so the caller still sees the error. Returning a response from that second function would resolve the original call instead.
Timeouts and cancellation
Axios takes a timeout in milliseconds. The default timeout is 0, which means no timer. fetch takes an AbortSignal.
await axios.get("https://example.com/data", { timeout: 5000 });
await fetch("https://example.com/data", { signal: AbortSignal.timeout(5000) });
If the axios call lasts longer than 5000 milliseconds, the promise rejects. The code is ECONNABORTED unless transitional.clarifyTimeoutError is true, in which case the code is ETIMEDOUT. AbortSignal.timeout(5000) aborts on its own. The fetch promise rejects with a TimeoutError.
Cancelling a call uses the same signal for both. Axios also still has CancelToken, deprecated since axios 0.22.0.
const controller = new AbortController();
axios.get("https://example.com/data", { signal: controller.signal });
fetch("https://example.com/data", { signal: controller.signal });
controller.abort();
abort() rejects the axios promise with CanceledError and the code ERR_CANCELED. The fetch promise rejects with AbortError.
Upload and download progress
Axios can call you as bytes go out or come in. fetch has no progress callback. For a download, you count bytes while reading response.body.
await axios.post("https://example.com/upload", { name: "ada" }, {
onUploadProgress(event) {
console.log(event.loaded, event.total, event.progress);
},
});
loaded is how many bytes have been transferred. total is the size when axios knows it. progress runs from 0 to 1 when total is present. onDownloadProgress uses the same event shape for the response. Progress events are limited to 3 times per second. Capturing FormData upload progress is not supported in Node.js.
A download with fetch reads the stream:
const response = await fetch("https://example.com/file");
const reader = response.body.getReader();
let loaded = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
loaded += value.byteLength;
}
getReader() locks response.body. Each read() returns the next chunk in value. value.byteLength is that chunk’s size, and loaded is the sum. done is true when the stream ends. Content-Length, when the server sent it, is the total. After this loop the body is consumed, so response.json() cannot read it again.
Bundle size and where the function comes from
fetch is already in the runtime, so there is no package to ship. Axios 1.21.1 publishes dist/axios.min.js for the browser. That file is 77,016 bytes, and 26,330 bytes with gzip level 9.
Node.js has had a global fetch since 18.0.0, when it stopped requiring --experimental-fetch. As of Node 21.0.0 it is no longer experimental. The implementation is undici. Axios runs in Node through its HTTP adapter. The default adapter list is xhr, then http, then fetch. The fetch adapter, added in axios 1.7.0, is used when the earlier adapters are missing, or when you pass adapter: "fetch".
The Axios 1.x migration guide says the 0.x line supported IE11 and 1.x requires modern browsers.
For a cross-origin request, cookies go out only if you ask. fetch defaults credentials to same-origin, so you set credentials: "include" to send cookies to another origin. Axios defaults withCredentials to false, and that flag applies to cross-site requests. withCredentials: true is the matching switch. The browser enforces CORS either way. Putting Access-Control-Allow-Origin on the request header does not grant access. The server sends that header.
axios.all and axios.spread are deprecated. Promise.all runs the requests together for either API.
Use axios when you want a plain object posted as JSON, a non-2xx status rejected, one place to add a header, a timeout number, and upload progress. Use fetch when you want no extra file in the bundle and you will check response.ok yourself. Node 18 or a current browser already has fetch.