Axios vs Fetch: Which Should You Use?

Oct 28, 2020

Axios is Mastering JS' offically recommended HTTP client. We occasionally use superagent, but we almost never use the fetch() function. The reason is that Axios drastically reduces the amount of boilerplate you need for your average API request. Here's some reasons why:

Axios is isomorphic, fetch is not

The syntax for most basic Axios requests is the same in both Node.js and the browser. Since Node.js does not have a built-in fetch() function, you need to use a polyfill like node-fetch. And there are several known differences between node-fetch and browser fetch().

Axios throws an error when a request fails

One of the most annoying issues with fetch() is that it does not throw an error when the server responds with an HTTP error status, like 404 or 500.

fetch('https://httpbin.org/post').catch(err => {
  /* No error even though the server responded with 405 */
});

axios.get('https://httpbin.org/post').catch(err => {
  err.response.status; // 405 "METHOD NOT ALLOWED"
});

However, fetch() does throw an error if it can't reach the server, so you always need two distinct error handling paths with fetch(). The situation is even worse with async/await: every fetch() needs an extra then() to bubble up errors.

Axios error handling is much easier: just use catch().

Automatic JSON and Form-Encoded Serialization and Parsing

Most modern APIs use JSON or form encoding for request bodies. Axios handles JSON and form encoding automatically, as well as automatically serializing query strings.

// Serialize JSON body and query params with fetch:
body = JSON.stringify(body);
query = new URLSearchParams(query).toString();

const res = await fetch('/myendpoint?' + query, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body
});

// Serialize JSON body and query params with axios:
await axios.post('/myendpoint', { params: query, body });

Framework Features: Interceptors and Instances

With all these limitations, the unfortunate reality is that everybody who uses fetch() writes their own wrapper around fetch(). It is extremely difficult to build an app using fetch() directly.

Axios lets you go further by providing some framework-like features. You can use interceptors and instances to create your own API wrappers using Axios. For example, here's how you can build a Trello API client using instances and interceptors:

So Axios not only eliminates a lot of the boilerplate and rough edges of fetch(), and also makes it easier to build specific wrappers for different APIs.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Axios Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!