BACK
Split ways

Fetch vs Axios for HTTP requests

Alexandre Dubois

In this, my very first article, I have decided to look into something many developers seem to wonder about: What is the difference between Fetch and Axios and when should each be used? AJAX calls have been part of our daily routine for a while now and when I plan my code, Axios comes to mind right away. But what is Fetch, where does it come from and should we use it instead?

Please note that this is not a comprehensive study of any of these tools and won't dig deep into their existential aspects, their purpose nor their full usage possibilities, but will provide an overview of their key aspects and pros+cons of each.

First, here is a little refresher of what Axios is. Axios is a wrapper, a decorator pattern, an easy-to-use API / promise-based HTTP client. It offers a nice interface that many find convenient to use. It is a third-party tool (not Vanilla JavaScript) that can be used on both the client and server sides. One major aspect of Axios to be aware of is that it is not natively provided by the browser to JavaScript, it must be installed and imported (dependency) to be available for use. Before choosing Axios, there are two main points to consider. First, using a third party adds a considerable weight/load on your application or website and this extra weight should be evaluated even if your site has low traffic. Then, you must also keep in mind that it is not the standard, which means that you will be responsible to manage conflict possibilities that may arise. That being said, this third-party library is very popular and is well supported, even on IE11!

On the other end, Fetch is a more modern and cleaner solution that replaces the not so friendly XMLHttpRequest (XHR). It was introduced with ECMAScript 2015 (ES6) and is now supported by most major browsers (except for Internet Explorer). Fetch makes it easier to make asynchronous requests and handles responses more smoothly than with the older XMLHttpRequest. Another benefit of Fetch is that it is Vanilla JavaScript so there's no need to install or import it and you don't need to worry about potential conflicts as this is not a third-party library. Fetch resides in the browser and can be used with ease on the client side but it is not available on the server side.

NodeJS users have several options which includes Node-Fetch or Axios. Many sources of information claim that Fetch does not provide a request cancellation, in comparison with Axios, but it can certainly be accomplished with the recent arrival of the AbortController supported by most major browsers (except for Internet Explorer).

Let’s take a look at some of the different syntaxes used with Fetch and Axios.

This is a simple GET AJAX call using Axios:

  
    axios.get('https://some-url/api/some-endpoint')
  .then(response => console.log(response))
  .catch(error => console.log(error.message));
  

This is the equivalent, but with a different syntax using Fetch:

  
    fetch('https://some-url/api/some-endpoint')
  .then(response => {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log(error));
  

As you can see, when using Axios, you specify the HTTP method (GET, in this example) and it is the same syntax as other HTTP methods.

Below is an example of a POST call using Axios:

  
    const postData = { firstName: 'Korben', lastName: 'Dallas' };
const apiURL = 'https://top-movies.com/api/the-fifth-element/character';

axios({
  method: 'post',
  url: apiURL,
  data: postData,
})
  .then(response => console.log('Success: ', response))
  .catch(error => console.log('Error: ', error));
  

A simpler way of doing the same when configs are not necessary is:

  
    const postData = { firstName: 'Korben', lastName: 'Dallas' };
const apiURL = 'https://top-movies.com/api/the-fifth-element/character';

axios.post(apiURL, {
  ...postData
})
  .then(response => console.log('Success: ', response))
  .catch(error => console.log('Error: ', error));
  

But for Fetch, you don't need to specify the method for a GET which is implicit (default) when not specified. The other HTTP methods must be specified in the call options. The content/data must be converted to JSON before being sent through the body property of the options.

This is the equivalent, but with a different syntax using Fetch:

  
    const postData = { firstName: 'Korben', lastName: 'Dallas' };
const apiURL = 'https://top-movies.com/api/the-fifth-element/character';

fetch(apiURL, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(postData),
})
  .then(response => response.json())
  .then(jsonResponse => console.log('Success: ', jsonResponse))
  .catch(error => console.log('Error: ', error));
  

In comparison, when using Axios, the content/data is sent through the data property of the options and the JSON conversion is not necessary.

Another thing with Fetch is that there is an extra validation required on the response because Fetch always returns a response whether is it successful or not.

Here’s an example of an intentional non-successful response (400 : Bad Request):

Fetch Bad Request

This is why I added an extra validation on the response ok property. Note that the exception management is not optimized in this example:

  
    fetch('https://some-url/api/some-endpoint')
  .then(response => {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log(error));
  

Some developers claim that Axios offers a better response support than Fetch because you don't need to add the extra step of converting the response to get the handy JSON format. When using Fetch, you must convert it manually (which is not a big deal in my opinion):

  
    fetch('https://some-url/api/some-endpoint')
  .then(response => {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log(error));
  

Also, there is a lot of bad publicity around the good old XMLHttpRequest (XHR) but for simple cases, it can certainly and easily still satisfy the requirements. Let's see below a simple example using XHR:

  
    // Create an instance of the XHR request object
const xhr = new XMLHttpRequest();

// Initialize the request. Additional parameters can be added as required
xhr.open('GET', 'https://some-url/api/some-endpoint');

// Various response type can be specified (the default is 'string').
xhr.responseType = 'json';

// Send the request
xhr.send();

// Listen on the event for a response
xhr.onload = () => {
  if (xhr.status != 200) {
    // Note: this exception management should be improved
    alert('Error: ' + xhr.status);
    return;
  }
  // The response is obtained through the response property
  console.log('Response: ', xhr.response);
};
  

This method is more verbose in deed but it's still easy and an option to consider in some applicable situations.

Conclusion

I might disappoint the type of reader that expects a straight absolute and unconditional answer on the question that is "should I use Fetch or Axios" but that would not be fair because, as for many tools and programming languages available out there, I am one of those who believes they each have their purpose and opportunity to shine and can be the ideal solution when used correctly at the right moment.

Both Fetch and Axios offer advantageous features and although the syntax and simplicity of use differs, it is essential to keep in mind that the most pleasant or exciting solution for a developer might not be the most efficient or optimal in terms of performance for the product or a given project, and in turn the end user experience. A moment of reflection is always important when deciding which tools to use.


TL;DR;

For those always in a rush who seek shortcuts, here are the highlights for both tools:

Axios

PROS:

  • Promise based HTTP client for the browser and server (NodeJS)

  • Compatible with some older browsers (ie. IE11)

  • Provides Cancelling Request ⇒ that can also be done without Axios using AbortController)

  • Very popular third-party library actively supported

  • Wrapper / decorator pattern which offers nice and convenient interface

CONS:

  • Must be installed and imported (not native in JavaScript)

  • Not the standard so it is important to manage the conflict possibilities

  • Third-party libraries adds weight/load on the application or website (to be considered)

Fetch

PROS:

  • Native in modern browsers (no need to install/import)

  • Standard JavaScript (Vanilla)

  • Lightweight solution

  • Modern friendly solution that can replace the not so appreciated XMLHttpRequest (XHR)

CONS:

  • Must add extra step for JSON conversion for the request and on the response

  • Must manage the response and exceptions as Fetch always returns a response (even if not successful)

  • Not compatible with older browsers (ie. IE11)

  • Only available on client side (browser)


References

  1. Fetch API

  2. Fetch browser compatibility

  3. Axios documentation and browser compatibility

  4. Using AbortController

  5. AbortController browser compatibility

  6. XHR calls

Thanks you for reading!

Alexandre Dubois

Alexandre Dubois

Front-End Developper

A passionate developer, Alexandre works closely with his clients, adds value and contributes to their success.