DEV Community

Cover image for Axios vs Fetch
Wafa Bergaoui
Wafa Bergaoui

Posted on

Axios vs Fetch

Introduction

In modern web development, making HTTP requests is a fundamental task. Whether you're fetching data from a server, submitting forms, or interacting with APIs, you need reliable tools to handle these operations. While JavaScript provides a built-in fetch API for making HTTP requests, many developers opt for third-party libraries like Axios for added functionality and convenience.

Why Do We Need HTTP Request Tools?

Handling HTTP requests and responses can be complex, especially when considering error handling, response parsing, and request configuration. Tools like Axios and Fetch simplify these tasks by providing abstractions and utilities that streamline the process. They help address common problems such as:

Boilerplate Code: Simplifying repetitive tasks like setting headers and handling JSON responses.
Error Handling: Providing more consistent and manageable error handling mechanisms.
Interceptors: Allowing pre-processing of requests or responses, such as adding authentication tokens.

Fetch API

The Fetch API is a modern, built-in JavaScript method for making HTTP requests. It is promise-based, providing a more straightforward way to work with asynchronous operations compared to older methods like XMLHttpRequest.

Example

// Making a GET request using Fetch
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))
  .catch(error => console.error('There was a problem with the fetch operation:', error));

Enter fullscreen mode Exit fullscreen mode

Axios

Axios is a popular third-party library for making HTTP requests. It is promise-based like Fetch but includes many additional features that make it more convenient and powerful.

Example

// Making a GET request using Axios
axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error('There was a problem with the axios request:', error));

Enter fullscreen mode Exit fullscreen mode

Key Differences

1. Default Handling of JSON

- Fetch:
Requires manual conversion of response data to JSON.

fetch('https://api.example.com/data')
  .then(response => response.json()) // Manual conversion
  .then(data => console.log(data));

Enter fullscreen mode Exit fullscreen mode

- Axios:
Automatically parses JSON responses.

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data)); // Automatic conversion

Enter fullscreen mode Exit fullscreen mode

2. Error Handling

- Fetch:
Only rejects a promise for network errors, not for HTTP errors (e.g., 404 or 500 status codes).

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .catch(error => console.error('Fetch error:', error));

Enter fullscreen mode Exit fullscreen mode

- Axios:
Rejects a promise for both network errors and HTTP errors.

axios.get('https://api.example.com/data')
  .catch(error => console.error('Axios error:', error));

Enter fullscreen mode Exit fullscreen mode

3. Request Configuration

- Fetch:
Requires manual configuration of options like headers and method

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
});

Enter fullscreen mode Exit fullscreen mode

- Axios:
Provides a more concise and readable syntax for configuration.

axios.post('https://api.example.com/data', { key: 'value' }, {
  headers: {
    'Content-Type': 'application/json'
  }
});

Enter fullscreen mode Exit fullscreen mode

Interceptors

Interceptors are a powerful feature in Axios that allow you to intercept requests or responses before they are handled by then or catch. They are useful for tasks like adding authentication tokens to every request or handling errors globally.

Example of Axios Interceptors

// Adding a request interceptor
axios.interceptors.request.use(config => {
  // Add an authorization header to every request
  const token = 'your_token';
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, error => {
  // Handle request error
  return Promise.reject(error);
});

// Adding a response interceptor
axios.interceptors.response.use(response => {
  // Handle successful response
  return response;
}, error => {
  // Handle response error
  if (error.response.status === 401) {
    // Handle unauthorized error
    console.error('Unauthorized');
  }
  return Promise.reject(error);
});

Enter fullscreen mode Exit fullscreen mode

Conclusion

Both Fetch and Axios are capable tools for making HTTP requests, but they offer different levels of convenience and functionality. Fetch is a native, modern option that works well for simple use cases, while Axios provides a richer feature set, including automatic JSON handling, better error management, and interceptors for request and response manipulation. Choosing between them depends on the specific needs of your project and your preference for simplicity versus functionality.

By understanding the strengths and differences of each tool, you can make more informed decisions and write more efficient and maintainable code.

Top comments (15)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Hmmm, so let's see about this: The current axios NPM package weighs 2MB. In exchange for adding a significant chunk of those 2MB, we get things like errors on HTTP non-OK responses, which is bad for me (and I bet others) because, for example, I want to collect the body respones for HTTP 400 responses to provide the feedback to users. HTTP response 401 is another example: I need it in order to redirect the user to a login screen.

Sure, I can always do a catch. But, with fetch, which costs 0 bytes and is also available in Node, I don't need the catch. I merely need to do a switch on the statusCode property, or an if on the ok property.

Now, interceptors. Do I download 2MB to get a JSON token added to the header? Or do I do this?

const response = await fetch(url, {
    headers: {
        'Authorization': `Bearer ${token}`
    }
});
Enter fullscreen mode Exit fullscreen mode

"But then you'll have to do it for every data-retrieving function you have!" Eh, nope. Basic programming principles applied, I just create a myFetch function, a wrapper of the stock fetch function that injects the token every time, with just a couple hundred bytes. Response interception? Same thing.

So, is really axios a necessary, or even attractive enough package? Not all. Not for me, anyway. It adds very little value, IMHO.

Collapse
 
link2twenty profile image
Andrew Bone

When axios was first being written fetch wasn't in the spec and then took a while to be everywhere. We had to use XMLHttpRequest everywhere and that really wasn't a nice experience.

Axios these days just uses fetch directly, though does still have XMLHttpRequest as a fallback.

All this to say I understand why axios exists and when people like something it tends to survive a long time even if it's not really needed anymore. I personally always use fetch directly.

Collapse
 
sheraz4194 profile image
Sheraz Manzoor

Likewise, but I use nextjs, so I get all benefits of axios without even using it.

Thread Thread
 
mseager profile image
Mary Ahmed

Why isn't axios needed for nextjs?

Collapse
 
mseager profile image
Mary Ahmed

We've been using axios for all our API endpoints but all these comments have almost convinced me to change to fetch 😅 We're building a social network and performance really matters

Collapse
 
jessseemana profile image
Jesse Emana

i'm switching to fetch right away

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
martinbaun profile image
Martin Baun

I really enjoy fetch. I removed Axios from my latest React project. I always prefer to depend as little as possible on third party packages.

Collapse
 
rahulvijayvergiya profile image
Rahul Vijayvergiya

Thanks for the information.
Intestingly, I wrote similar article today :)
dev.to/rahulvijayvergiya/fetch-vs-...

Collapse
 
sheraz4194 profile image
Sheraz Manzoor

Once again, Nextjs is very kind with us. We can achieve all the benefits of axios even using fetch API in Nextjs. Love You Nextjs. Nice article by the way.

Collapse
 
iainsimmons profile image
Iain Simmons

You don't get that for free. Next is overwriting the native fetch with its own implementation, which, while likely smaller than Axios, is still part of the relatively large bundle size you will have in any Next app.

It would probably be better than trying to roll your own with React and Axios though!

Collapse
 
charldev profile image
Carlos Espinoza

Thank you for the information.

Collapse
 
fernandoadms profile image
Fernando Alves

Great article!

Collapse
 
emmo00 profile image
Emmanuel (Emmo00)

Most times, I feel axios is overkill in most cases. Fetch serves fine

Collapse
 
citronbrick profile image
CitronBrick

Code can be enclosed within triple backticks to enable syntax highlighting in Dev.to

Some comments may only be visible to logged-in visitors. Sign in to view all comments.