Axios vs Fetch
Wafa Bergaoui

Wafa Bergaoui @wafa_bergaoui

About: Software engineer

Location:
Tunisia
Joined:
May 22, 2020

Axios vs Fetch

Publish Date: Jul 3 '24
172 47

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.

Comments 47 total

  • José Pablo Ramírez Vargas
    José Pablo Ramírez VargasJul 4, 2024

    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.

    • Andrew Bone
      Andrew BoneJul 4, 2024

      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.

      • Sheraz Manzoor
        Sheraz ManzoorJul 4, 2024

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

        • Mary Ahmed
          Mary AhmedJul 5, 2024

          Why isn't axios needed for nextjs?

    • harrigan knott
      harrigan knottJul 4, 2024

      Hi everyone. I’m rosela knott from montreal , canada. I was one of the victims of a crypto investment scam that saw me lose $302,000 worth of crypto. The crypto market is very volatile and a lot of individuals have lost some of their crypto coins and crypto assets to these online scams. My wallet address was compromised and I don’t know how they got a hold of my recovery phrase, but I was wiped out by these scam attacks. I lost all my crypto coins ( ethereum, Btc & USDT) and this left me devastated and depressed. I could have been homeless if it was not for the intervention of CYBER Computer specialist a well-known and highly trusted crypto company whom I contacted through a colleague of mine, I filed a complaint to CYBER Computer specialist and provided them with all the information including screenshots of the transactions. CYBER Computer specialist was able to recover my crypto assets in less than 48 hours. I was totally in awe of how quickly and efficiently CYBER Computer specialist was able to access my stolen crypto and recover my crypto wallet and assets. I’m highly impressed and I recommend their services to everyone. Truly information is very valuable and without the help of CYBER Computer specialist, I could have been homeless and left in a pitiful state. I’m very thankful for their help and I’m glad there is a safe way to fully recover crypto assets since the authorities cannot do anything to help get back lost funds. CYBER Computer specialist was able to help me trace these conmen with their sophisticated CYBER Computer specialist system. You can easily contact CYBER Computer specialist with the following information. Email

    • Mary Ahmed
      Mary AhmedJul 5, 2024

      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

      • Jesse Emana
        Jesse EmanaJul 5, 2024

        i'm switching to fetch right away

    • Sirajul Muneer
      Sirajul MuneerJul 6, 2024

      Axios is 2MB? Can you share more info?
      bundlephobia.com/package/axios@1.7.2
      A minified gzipped version is only 13.2KB. No one is going to serve unminified ungziped version in their production.

      Secondly axios is tree shakable, means only the required exports are being bundled, if the bundlers are configured properly.

      I so prefer using fetch over axios, but the facts provide should be fair and not manipulated. Do people care for a 13.2KB, depends on the project and management.

      • José Pablo Ramírez Vargas
        José Pablo Ramírez VargasJul 6, 2024

        npmjs.com/package/axios

        That says 2MB. True, I did not realize until now that it is unpacked size. Still, the 2MB is there. I'm not trying to manipulate anybody.

        • Sirajul Muneer
          Sirajul MuneerJul 6, 2024

          The same argument can be brought against majority of other packages too. Vue is 2.2MB unpacked. Vanilla Js is just 0 MB. What does Vue do which can’t be done with vanilla js?

          • José Pablo Ramírez Vargas
            José Pablo Ramírez VargasJul 6, 2024

            Now you're just being extremist, or you're missing the point entirely. One can forego the need of axios with very few additions that weigh very little; what Vue does for the developer is night and day: It allows control of the DOM declaratively. Vanilla JS doesn't have this capability. Therefore your argument is definitely false, and even misleading.

            • Monesul Haque
              Monesul HaqueJul 15, 2024

              13KB is not big deal also high chance is it will be serve from some cdn so user experience won't be that bad.

              • José Pablo Ramírez Vargas
                José Pablo Ramírez VargasJul 15, 2024

                I hear you. Still, 0B is better, or say 1 or 2 KB uncompressed of "infrastructure" code overhead. Basically, my point is that axios WAS a good thing. Now the standard caught up and axios should be a thing of the past.

                • Sirajul Muneer
                  Sirajul MuneerJul 17, 2024

                  Fetch cannot still replace upload or download progress offered by axios.

                  • José Pablo Ramírez Vargas
                    José Pablo Ramírez VargasJul 17, 2024

                    This doesn't seem to be the case anymore. The fetch-api-progress NPM package, which only weights 17kb uncompressed, not 2MB, provides progress report for fetch.

                    • Sirajul Muneer
                      Sirajul MuneerJul 24, 2024

                      Needing a third party library again defeats the purpose. Axios handles it better and battle tested.

                      • José Pablo Ramírez Vargas
                        José Pablo Ramírez VargasJul 24, 2024

                        LOL. Isn't axios a third party library? Let it go, let axios rest in peace.

                        • Sirajul Muneer
                          Sirajul MuneerAug 7, 2024

                          Then provide an example of doing upload progress with fetch without using any external libraries. 😂

                          • José Pablo Ramírez Vargas
                            José Pablo Ramírez VargasAug 7, 2024

                            Bro, the point of the argument is not "zero libraries". The point of the argument is that fetch can do everything axios can, that you don't need axios anymore, that even if you have to add a 20kb library for upload progress, axios is still dead weight. That's the argument, and an argument that cannot be refuted.

                            • Sirajul Muneer
                              Sirajul MuneerAug 8, 2024

                              I already said you axios can still do more things that fetch. If you want to use some random unknown, less used package to patch fetch and make it do things you can. For the time being axios is way more reliable and known and stable than some patchy library. When fetch equals axios, I'd happily switch over.

                              • José Pablo Ramírez Vargas
                                José Pablo Ramírez VargasAug 8, 2024

                                More things? Enumerate them here. Tell me, exactly, what things axios can do that fetch cannot cover. We already went through some and I have demonstrated that fetch can do them either by itself, or by bringing a small package to the picture.

                                "way more reliable". Where are the metrics for this? Show me metrics.

                                In the end, you can do what you want. You're clearly not understanding anything and have a closed mind. Really, try fetch() out even just for fun. That should clear your head.

                                • Sirajul Muneer
                                  Sirajul MuneerAug 9, 2024

                                  I already use fetch for many usecases. LOL. You are the one here with blind eyes and blind hate to axios. You need metrics for popularity of axios? Compare the poplularity of the fancy library you suggested with axios. The difference will be like an elephant and an ant.
                                  Didn’t you stupidly state axios bundles and send 2MB in payload? 🤣 That was your “best argument” against axios. 😂😂

                                  • José Pablo Ramírez Vargas
                                    José Pablo Ramírez VargasAug 10, 2024

                                    Couldn't it be that perhaps very few people need progress upload? Or are you saying that everyone downloading axios are in fact using progress upload? That's some f'd up logic.

                                    There could be many reasons why people don't don't download that NPM package and there could be many other reasons why people download axios.

                                    Feel free to keep commenting nonsense. It entertains me.

                                    • Sirajul Muneer
                                      Sirajul MuneerAug 10, 2024

                                      Your nonsense entertains me as well. You made a blanket statement axios is dead forever. Go touch some grass. 🤣 You claimed fetch can do everything, I proved it can’t. They you are like “well, there is some third party library for it”. Exactly that was what I said, and axios is one of those 3rd party library. 😂 Axios is way popular than you at the very least. 😂

                                      • José Pablo Ramírez Vargas
                                        José Pablo Ramírez VargasAug 10, 2024

                                        You know when someone has lost an argument by the number of emoji they use. Emoji are that: Emotion. You are out of arguments and are only left with emoji, to try to appeal to my emotion.

                                        Is logic and reasoning too hard for you? I'm sorry. If you can't understand English, maybe I can try to translate it for you? Let me know. I'll try to help before you run out of emojis.

                                        • Sirajul Muneer
                                          Sirajul MuneerAug 13, 2024

                                          Yes please translate in note less than 200 pages. Keep your word if you are a man. Waiting to learn from your 200 page learning document.

                                          • José Pablo Ramírez Vargas
                                            José Pablo Ramírez VargasAug 13, 2024

                                            Do you want emojis in the document? You know, just so you understand it better. Just asking. 😄

                                            • Sirajul Muneer
                                              Sirajul MuneerAug 18, 2024

                                              Yes please if that is not difficult for you. When can I expect it btw? 😂🤡

                                              • José Pablo Ramírez Vargas
                                                José Pablo Ramírez VargasAug 18, 2024

                                                Well, I need to get acquainted with the emoji system you seem to understand so well. It is kind of difficult for me because I have never written emotional pieces, but hang in there! Be sure to follow me so you don't miss it!!

                                                • Sirajul Muneer
                                                  Sirajul MuneerAug 21, 2024

                                                  Oh, that’s bad! I thought you were great and amazing! My hopes have shattered. You are not good in adding emotions to your words, or even not acquainted in using emojis.
                                                  Alas! I cannot follow a man who canst keepth his troth! Thou must forbear thyself from scribing!

    • Maanik sharma
      Maanik sharmaJul 9, 2024

      the thing sir you saying about wrapper then you have to pass everything down to that inner function .And more customization leads to cumbersome code. Axios defaults feature and less boilerplate code.

      • José Pablo Ramírez Vargas
        José Pablo Ramírez VargasJul 9, 2024

        What's the complication of writing myFetch() instead of fetch()?? Where's the complication in that? If you're doing it after the fact, just do a mass Replace. You're done with all calls in 1 second. It is literally nothing the difference between writing fetch and myFetch.

        Cumbersome code. Hmmm. I'm no axios user so maybe you can enlighten me. Bing's Copilot says this is a simple interceptor example to add an interceptor that injects a token:

        // Create an instance of axios
        const apiClient = axios.create({
          baseURL: 'https://api.example.com', // Replace with your API base URL
        });
        
        // Add a request interceptor
        apiClient.interceptors.request.use(
          function (config) {
            // Get the token from local storage or any other storage
            const token = localStorage.getItem('authToken');
        
            // If the token exists, add it to the headers
            if (token) {
              config.headers.Authorization = `Bearer ${token}`;
            }
        
            return config;
          },
          function (error) {
            // Do something with request error
            return Promise.reject(error);
          }
        );
        
        Enter fullscreen mode Exit fullscreen mode

        That vs. my code. OMG!! What a shot in the foot axios is, if Copilot is correct.

        Now, back to your comment: Are you saying that this is cleaner? Are you saying that this "cleanliness" from axios is unbeatable unless I write, say, 1MB worth of infrastructure code? Come on, really?

  • Sheraz Manzoor
    Sheraz ManzoorJul 4, 2024

    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.

    • Iain Simmons
      Iain SimmonsJul 5, 2024

      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!

  • Thomas Bnt
    Thomas BntJul 4, 2024

    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

  • Martin Baun
    Martin BaunJul 4, 2024

    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.

  • Rahul Vijayvergiya
    Rahul VijayvergiyaJul 4, 2024

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

  • harrigan knott
    harrigan knottJul 4, 2024

    Hi everyone. I’m rosela knott from montreal , canada. I was one of the victims of a crypto investment scam that saw me lose $302,000 worth of crypto. The crypto market is very volatile and a lot of individuals have lost some of their crypto coins and crypto assets to these online scams. My wallet address was compromised and I don’t know how they got a hold of my recovery phrase, but I was wiped out by these scam attacks. I lost all my crypto coins ( ethereum, Btc & USDT) and this left me devastated and depressed. I could have been homeless if it was not for the intervention of CYBER Computer specialist a well-known and highly trusted crypto company whom I contacted through a colleague of mine, I filed a complaint to CYBER Computer specialist and provided them with all the information including screenshots of the transactions. CYBER Computer specialist was able to recover my crypto assets in less than 48 hours. I was totally in awe of how quickly and efficiently CYBER Computer specialist was able to access my stolen crypto and recover my crypto wallet and assets. I’m highly impressed and I recommend their services to everyone. Truly information is very valuable and without the help of CYBER Computer specialist, I could have been homeless and left in a pitiful state. I’m very thankful for their help and I’m glad there is a safe way to fully recover crypto assets since the authorities cannot do anything to help get back lost funds. CYBER Computer specialist was able to help me trace these conmen with their sophisticated CYBER Computer specialist system. You can easily contact CYBER Computer specialist with the following information. Email

  • Emmanuel (Emmo00)
    Emmanuel (Emmo00)Jul 5, 2024

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

  • Carlos Espinoza
    Carlos EspinozaJul 5, 2024

    Thank you for the information.

  • CitronBrick
    CitronBrickJul 5, 2024

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

  • Fernando Alves
    Fernando AlvesJul 5, 2024

    Great article!

  • lokesh kumawat
    lokesh kumawatJul 7, 2024

    I just learned the conversion from fetch to axios and changed some of the routes in my project to
    axios - async and await
    and here everyone says fetch is better

    Image description

    Image description

  • Charles Jordan
    Charles JordanJul 8, 2024

    Excellent

  • Pawat Chomphoosang
    Pawat ChomphoosangJul 10, 2024

    great information.

  • Alexey Kunitsky
    Alexey KunitskyJul 10, 2024

    I suggest you to try npmjs.com/package/ky/v/0.9.0. It's way smaller than axios, but still covers the basics.

  • Gary Fung
    Gary FungJul 10, 2024

    Dumb article. Best practice in the serverless and especially Edge runtime world, is just stick with web standard fetch(). Axios is a dinosaur and keep making breaking changes, just move off.

Add comment