Axios vs. Fetch: which should I use?

Featured on daily.dev

Subscribe to my newsletter and never miss my upcoming articles

When we enter the world of computing, there are so many packages, options and paths to follow that it is normal to feel a little lost.

For example, when we are making HTTP requests, which way should we go? In this post, I will cover the Axios library and the Fetch API comparatively, showing their differences. Remember: which one to use is up to you, but it is good to think about the pros and cons, okay?! 😁

But... what are they?

When we want to communicate with servers through the HTTP protocol, sending requests and fetching data, it is quite common to hear about Axios or Fetch. We can call this operation AJAX (Asynchronous JavaScript And XML). But, what are they?

Axios

Axios is a JavaScript library used to make HTTP requests from node.js or XMLHttpRequests from browsers, with the support of the Promise API, which is native to JS ES6. According to its documentation, it can:

  • Make XMLHttpRequests from the browser
  • Make HTTP requests from node.js
  • Support Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client-side support for protecting against XSRF

As the Axios library is not native to the JavaScript API, we have to import it into the project. You can check the installation step by step directly here!

Fetch API

The Fetch API provides an interface for fetching resources. According to its documentation, Fetch provides a generic definition of objects for requests and response. It also uses Promises and provides a global fetch() method. This method only requires, as a mandatory argument, the path to the resource you want to fetch. It returns a promise that resolves the response for this request, whether successful or not.

Compatibility

Despite their similarity and their compatibility with Google Chrome, Safari, Opera, and Edge, the compatibility of Axios with previous versions of browsers is better. For IE 11, Fetch is not compatible, while Axios offers good support without any problem. The following image about Fetch compatibility was obtained from the Can I Use website:

image.png

Safety

At this point, Axios is less vulnerable. It has client-side protection against XSRF (Cross Site Request Forgery), which is one of the most well-known attacks since... ever?! Basically, it occurs in situations where an HTTP request is made between websites, where one tries to impersonate a system user. The idea is to create a fake request, guaranteeing privileged access to the fraudulent user. A better and deeper explanation can be seen here!

Syntax

When comparing Axios and Fetch, it is important to notice that they are clearly different in basic syntax. I will use the PokéAPI - a Pokémon-based RESTful API to compare them. Check the GET method of Axios and Fetch:

const url = 'https://pokeapi.co/api/v2/pokemon/ninetales';

// Axios
axios.get(url)
  .then(response => console.log(response));

// Fetch
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));

If you have never seen anything about them, I am sure you will wonder why the .json() method was used in the case of Fetch. Actually, this also happens with Axios, but it automatically serializes to JSON when the request is resolved! One less step is always good, right?!

Intercepting requests and responses

In general, HTTP interceptors are good for examining HTTP requests made from our application to the server. They are good for making code executions or changing requests/responses before they are started. Fetch does not guarantee a way to intercept HTTP requests, but it is possible to get around this by overriding the global fetch() method, creating its own interceptor.

Meanwhile, Axios already has its interceptor, which is executed even before the promises of .then or.catch. To illustrate this:

axios.interceptors.request.use(
  config => {
    // something can be done with your request data here
    console.log('A request has been sent!');
    return config;
  }, (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  config => {
    // something can be done with your response data here
    console.log('A response has been received!');
    return config;
  }, (error) => {
    return Promise.reject(error);
  }
);

axios.get('https://pokeapi.co/api/v2/pokemon/ninetales')
  .then(response => console.log(response));

Timeout and Progress

One of the things I find really cool about Axios that Fetch does not provide is the timeout as one of its settings, which is the time limit before a request is aborted. Timeout is a possible setting option that is passed in the config object in millisecond units. It is important to remember that the timeout is a response timeout and not a connection timeout. For example:

axios.get(
  'https://pokeapi.co/api/v2/pokemon/ninetales',
  {
    timeout: 10
  }
)
  .then(response => console.log(response));

But there is a way to create the timeout using the Fetch API, an example:

const controller = new AbortController();
const timeoutValue = 10000;
const timeout = setTimeout(() => controller.abort(), timeoutValue);
fetch('https://pokeapi.co/api/v2/pokemon/ninetales', { signal: controller.signal })
  .then(response => response.json())
  .then(data => console.log(data));

In terms of progress, we have another reason to prefer Axios: it presents a simple way to access the progress of your request. It is a way of giving feedback on requests from users who have a slower Internet or who are making a very large one. OnUploadProgress is also one of the optional settings passed in the configuration object.

Error Handling

With Axios, handling errors is much easier since bad responses are automatically rejected, unlike Fetch, which even 404 or 500 errors, for example, are still resolved. In the instance, the backend returns a “500 Internal Server Error” code, Fetch will handle in the same way that it handles the code "200 OK". To deal with this in Fetch, we can use the "ok" flag:

fetch('https://pokeapi.co/api/v2/pokemon/a*b/') // 404 error
  .then(response => {
    if (!response.ok) {
      throw Error(response.statusText)
    }
    return response.json()
  })
  .then(data => {
    console.log(data)
  })
  .catch(error => console.error(error))

In the case of Axios, a simple example of error handling can be seen below:

axios
  .get('https://pokeapi.co/api/v2/pokemon/a*b/') // 404 error
  .then(response => {
    console.log("response", response)
  })
  .catch(error => console.log(error))

Conclusion

It is clear that Axios has greater ease of use when compared to Fetch. Another point that can also be taken into account is page weight: Axios weighs 4.52 kB (Minified + Gzipped), while Fetch is already built into the browser, ie it weighs total 0k. I prefer to use Axios in my projects, but this is not a rule!

This is my first post, and I would like to thank you for reading it! You can also leave suggestions, tips and questions in the comments, or send me via email/social networks.

Stela IS's photo

Thank you so much for this article, it is exactly what I needed. I am definitely copying you, and trying Axios. An excellent review for beginners :)

Edidiong Asikpo's photo

I can say for a fact that it's finally good to know the reasons behind using one over another. In my case, I just went with using Fetch because Axios seemed really hard for me to grasp.

Interesting article Luísa Ribeiro Bezerra.

Luísa Ribeiro Bezerra's photo

Thank you, Edidiong! :D

Mohammed Nokri's photo

Amazing job! 👌🏼 Great article!

William Hall's photo

Great first article Luisa. Thank you

Chris Bekas's photo

Thanks for sharing, I'm leaning towards Axios now!

Luísa Ribeiro Bezerra's photo

Thank you and good and enjoy your studies!

Lee Hansel Solevilla's photo

I think you are comparing two different things here. Axios is a library while Fetch is a native function on modern browsers. It will always be performant to use native functions but a library will always be easier to use due to its abstractions.

I think it would be better if you will be comparing Axios vs another library that abstracts HTTP Calls, or comparing Fetch vs XHTTP.

Good story though.

Luísa Ribeiro Bezerra's photo

Yeah the main idea about comparing both of them is because they are quite different, I think :)

But I got your point! Thanks for the feedback!

Suyash Pradhan's photo

Well Written!

Bob Fornal's photo

Great article.

I've used both for various projects. Your insights confirm a lot of the things that I've been thinking about.

Yann Thibodeau's photo

Very interesting article, my friend and I just were just debating about that recently and as I can see we made the right decision to go with axios ;)

Luísa Ribeiro Bezerra's photo

ohhh thanks <3 good to know that!

Don Alfons Nisnoni's photo

I also have the same situation but as expected if its just about security and compability

Yair Cohen's photo

Great article:) Thank you

Carlos Carneiro's photo

O artigo ficou bem didático e direto ao ponto. Parabéns Luisa!

Luísa Ribeiro Bezerra's photo

Obrigada, Carlos!! :)

Thintinos Gerardo's photo

Great post! Thank you for sharing.