DEV Community

Sidra Maqbool
Sidra Maqbool

Posted on

Comparing Axios and the Fetch API: Which One Should You Choose?

When it comes to making HTTP requests from JavaScript, there are a number of libraries and tools available. Among the most popular are Axios and the native Fetch API. This post aims to give a clear comparison between the two, highlighting their advantages and disadvantages to help you decide which one might be best for your needs.

What is Axios?

Axios is a popular JavaScript library used to make HTTP requests. It works in both the browser and Node.js environments. Axios provides a clean API for sending HTTP requests and handling responses.

What is the Fetch API?

The Fetch API is a modern interface in JavaScript for making web requests. It's built into most modern web browsers, eliminating the need for third-party libraries in many use-cases.

Comparing Axios and the Fetch API

1. Syntax and Ease of Use

Fetch: While Fetch provides a modern approach, it can get a bit verbose, especially when handling JSON data:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Axios: Axios offers a more concise syntax and automatically transforms JSON data:

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.log('Error:', error));
Enter fullscreen mode Exit fullscreen mode

2. Error Handling

Fetch: Fetch only rejects the promise for network errors. For HTTP errors (like 404 or 500), it still resolves the promise, but you have to check the response object:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

Axios: Axios considers any HTTP status outside the range 200-299 as an error, making error handling more intuitive:

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.log('Error:', error.response.statusText));
Enter fullscreen mode Exit fullscreen mode

3. Request and Response Interception

Fetch: Does not have built-in interceptors.
Axios: Allows you to intercept requests or responses before they are handled or sent. This can be especially useful for tasks like setting authentication headers or logging:

axios.interceptors.request.use(config => {
  config.headers['Authorization'] = 'Bearer token';
  return config;
});

Enter fullscreen mode Exit fullscreen mode

4. Browser Support

Fetch: Supported in most modern browsers but requires a polyfill for older browsers.
Axios: Works in all browsers and even in Node.js environments.

5. Cancellation

Fetch: Native Fetch doesn’t have a straightforward mechanism to cancel requests.
Axios Provides a cancellation mechanism using the CancelToken source:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('https://api.example.com/data', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  }
});

source.cancel('Operation canceled by the user.');
Enter fullscreen mode Exit fullscreen mode

Conclusion
Both Axios and the Fetch API have their strengths and are suitable for different use-cases. If you’re working on a project where you need more features like request/response interception, or simpler error handling, Axios might be the way to go. However, if you’re trying to minimize dependencies and are working in environments with modern browsers, the Fetch API can be a great choice.

Ultimately, the decision will come down to your specific requirements and your familiarity with the tool. Whether you choose Axios or the Fetch API, both provide reliable ways to make HTTP requests in JavaScript.

Top comments (2)

Collapse
 
lionelrowe profile image
lionel-rowe

Since the death of IE11, I don't think there's any excuse to increase your bundle size and add the performance overhead of using axios over fetch. If you're consistently finding you want the functionality of consuming the body data as JSON, throwing on codes ≥400, etc. you can always write your own tiny wrapper around fetch.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

fetch() uses and AbortController to perform cancelation. Furthermore, fetch() is also available in NodeJS.

On the personal side, I consider fetch() having the correct approach by resolving the promises on non 2xx status codes. Proper REST communicates a variety of non-exception conditions with status codes outside the 2xx range.

That leaves the one extra line to obtain JSON and interceptors in the axios side. Instead of an interceptor, I can quickly create a customized fetch-based function to handle both request and response interception, and the extra line I don't mind at all.