Axios vs. Fetch: which should I use?

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.

#axios#fetch#javascript
 
Share this