DEV Community

Cover image for Axios vs Fetch

Axios vs Fetch

Caio on September 30, 2024

Both Axios and Fetch are popular tools for making HTTP requests in JavaScript, but they have some key differences. Here’s a breakdown: Ax...
Collapse
 
webjose profile image
José Pablo Ramírez Vargas

I don't understand the fixation of people with axios. It should just be a legacy package. This is no longer needed. Just go with a customized function that uses fetch. The customized function can replace all interception needs. Far simpler and no package dependencies.

Collapse
 
mistval profile image
Randall

Same, I just use fetch and if I need some sort of shared behavior I write a little wrapper around it. That's usually much simpler and more understandable even if it requires 2-3 extra lines of code compared to an axios equivalent.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

That's another thing: It is like 10 lines of code to just add an interceptor to axios. It is more lines of code most of the time.

Collapse
 
doccaio profile image
Caio

Me neither haha, but there are companies that still use.

Collapse
 
kadrigron profile image
🌬Agron • Edited

This would be a good opportunity to eventually refactor, remove Axios, and reduce the bundle size of the company's repository.

Collapse
 
collincity111 profile image
Chiagozie Okafor

Simple 😂😂😂

Collapse
 
florianrappl profile image
Florian Rappl • Edited

I really love the semi-knowledge in our industry reflected by some of the comments.

  1. fetch also provides a very simple (and standard) way to abort requests - using a generic AbortController
  2. There are many cases why you might still want to use Axios - one example is progress (e.g., for larger uploads) - this is not possible using fetch

I don't get why people are so extreme. Yes, you should prefer using fetch. No, somebody who uses Axios might still have a valid case - so stop burning people / their choices and embrace that we have options.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

UPload progress is now possible with fetch. There's a package that allows this. This is possible now because of stream support recently added to browsers.

I think the only valid reason for axios is to cover old browsers that don't provide fetch. Therefore, axios itself should now be legacy.

Collapse
 
florianrappl profile image
Florian Rappl

Hm which package do you mean? I only know npmjs.com/package/fetch-progress and this is for download progress. Surely, you can also add upload progress via a ReadableStream - but that's essentially my point: It's not supported out of the box from fetch (e.g., via a progress event) - so you need to write more code / use some package to get the functionality. axios adds a couple of things on top - now, personally I don't need them, but if you want those extra things then there is certainly nothing wrong with using axios.

Only a sith deals in absolutes - always be open minded!

Thread Thread
 
webjose profile image
José Pablo Ramírez Vargas

Nope. This one.

Thread Thread
 
webjose profile image
José Pablo Ramírez Vargas

I wouldn't download the entirety of legacy axios just for upload progress. I'd use the more modern package and that's it. Even if fetch doesn't provide it as a stock option, that's no justification to continue using something that should just be archived.

Thread Thread
 
florianrappl profile image
Florian Rappl

My feeling is that you either have not read or not understood what I wrote. I may have a problem communicating well here - so I take the blame.

If you carefully read what I wrote you'll find

  • I never advocated using axios over fetch (in contrary - I explicitly wrote that the preference should still be to use fetch)
  • I never wrote that upload progress is the only reason for sticking to it (it's one example - but there are many others)

among other things.

Thread Thread
 
webjose profile image
José Pablo Ramírez Vargas

"many others"? Care to enumerate? Because that's my point. There is probably so little to enumerate that axios shouldn't be worth under any circumstances, as more modern packages, that are more focused and less bulky, can do.

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
 
doccaio profile image
Caio

Thanks for letting me know, but he was sure I had done this before, I probably didn't save it haha

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Glad I helped you rethink that, an article with colored code, is easier to read and improves reading! 😎

Collapse
 
cookiemonsterdev profile image
Mykhailo Toporkov 🇺🇦 • Edited

Axios is good when you need to support old browsers, since it uses XHR under the hood. But from the other hand it slower than fetch API, I would recommend to use ky, it has same features like req, res interception and automatically rejection HTTP errors by status. Ky is using fetch as base so it faster.

Collapse
 
axi0m profile image
Matt

I love the fact that the JavaScript ecosystem is progressively adopting the same Web Standards APIs in both browsers and Node runtimes. It makes development experience so much nicer.
The only thing I regret about fetch compared to axios, is that HTTP status >= 400 are not considered as errors, and don't throw/reject, which is really painful when trying to implement a clean errors handling system.

To overcome that issue, I've implemented a small wrapper around fetch, that reproduces axios behaviour.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

A status code outside the range [200..300[ should not be a runtime error. This is some invention that came to be. This forces you to program logic using exceptions, which is a bad practice. The correct way to code is to use branching (IF or switch).

Collapse
 
crisclacerda profile image
Cristiano Lacerda

Bro it's 2024, there absolutely no use case for axios! Abolish this thing already!!

Collapse
 
michelangelo17 profile image
Michelangelo Markus

LOL I take it you haven't had to try and support progress indicators in an app recently. Fetch still doesn't support it. Have to fall back to XHR, which axios is built on and makes nicer.

There are use cases sadly since they didn't bother making fetch have feature parity with XMLHttpRequest

So while you don't need axios any more than you ever did, there are still valid use cases for it when you don't want to waste time reinventing the wheel just to save a dependency.

Collapse
 
crisclacerda profile image
Cristiano Lacerda

LOL.

So you're bringing in all that bloat for what? Progress events? Seriously, bro, just stick with XHR for that one case. There's no excuse for pulling Axios into your app when you can do the job without dragging in 30kb of overhead. Stop overcomplicating..

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Progress already possible with fetch.

Collapse
 
doccaio profile image
Caio

I see , but students still understand this, in addition, some back end systems use it, but of course it depends on the company, I prefer fetch , I think it's easier and more satisfying to use it.

Collapse
 
martinbaun profile image
Martin Baun

I use Axios for interceptors feature which afaik fetch doesn’t have.
Sure I could build my own, but then I’d have to build my own

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

The AI says this is what is needed to inject a token with an axios interceptor:

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://your-api-endpoint.com',
});

instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('authToken');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Use the Axios instance to make requests
instance.get('/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

This is code you must write.

If you simply write a custom fetching function, the same is something like:

function  myFecth(url, init) {
    const token = localStorage.getItem('authToken');
    if (token) {
      init.headers['Authorization'] = `Bearer ${token}`;
    }
    return fetch(url, init);
}
Enter fullscreen mode Exit fullscreen mode

And interception of responses is as easy. So axios is more work than plain fetch.

Collapse
 
martinbaun profile image
Martin Baun

Nice! Thanks!

Collapse
 
ianemv profile image
Ian Villanueva

I've been using fetch api since I've learned about 5 years ago I think since I don't want to add external modules such as axios. There could be more native JavaScript API nowadays so Id really like to use that as well

Collapse
 
tomasdevs profile image
Tomas Stveracek

Nice read. I wrote a similar article for those interested. Link here.

Collapse
 
vilce profile image
Ștefan Vîlce

Excellent presentation! very concise!
Good work!

Collapse
 
devabhi404 profile image
DevAbhi

Beginner friendly explanation, very helpful

Collapse
 
abdulmuminyqn profile image
Abdulmumin yaqeen

I think fetch satisfies most needs, but axios is good to have.

nice read!

Collapse
 
mannuelf profile image
Mannuel • Edited

yup, I once used this one called cross-fetch I still use in a project, it an API wrapper that could run in client or server. Yay for fetch

Collapse
 
chandan_e69c011b258e09242 profile image
Chandan

Thanks for sharing 🤝🏻👍🏻.

Collapse
 
boscodomingo profile image
Bosco Domingo

Please, aync/await have been a thing for years. Stop using .then and .catch...

And as many others have commented, stop using axios too. This article should've really been one line:
"Just use fetch. Use fetch wrappers for extra functionality. If you need performance, use undici"

Collapse
 
williamlongii profile image
William Long II • Edited

Before my take on things thought I would mention that despite anyone or everyone's opinions about any language, package, or tool the correct answer will always be use whatever fits your use case and or the requirements of the project. If they demand Axios use Axios etc. So I agree in most part with the author. It was a good write up and pretty good division of examples of either. That being said I personally have been making large strides to move all of our Axios calls over to utilize fetch instead for several reason.
Mainly for external dependency reduction this is always a goal of mine, personally I like to reduce the amount of external dependencies we have to a minimum to keep security issues and technical debt my app is absorbing as low as I can and to be able to only implement features I need / want for any given thing. Granted if the scope of what I am trying to accomplish is large enough like a framework or overtly complicated like encryption I don't obviously encourage re-inventing the wheel.
There's several things people have mentioned fetch lacking I noticed that are not true for sure. Some addressed the cancellation one already but you most definitely can easily cancel a fetch request utilizing the abort controller as they mentioned. There was also a progress one mentioned which is also not true, you can definitely utilize the readable stream to get progress of a download utilizing the content-length header as easy example but could also expand to accept and process part of the incoming stream if they send some known structure to get the size of download if it was passed in as bytes etc.. It's a little more code but could easily wrap the fetch call in it and use callbacks like example below or even emitters if you wanted to not rely on callbacks. A crude implementation would look something like below.

const fetchWithProgress = (params: {
  url: string;
  init?: RequestInit;
  onProgress: (progress: number) => void;
}) => {
  const { url, onProgress, init } = params;
  return fetch(url, init).then((response) => {
    if (!response.ok) {
      throw Error(response.status + ' ' + response.statusText);
    }
    if (!response.body) {
      throw Error('ReadableStream not yet supported in this browser.');
    }
    const contentLength = response.headers.get('Content-Length');
    const total = parseInt(contentLength, 10);
    let loaded = 0;

    return new Response(
      new ReadableStream({
        start(controller) {
          const reader = response.body.getReader();
          read();
          function read() {
            reader
              .read()
              .then(({ done, value }) => {
                if (done) {
                  controller.close();
                  return;
                }
                loaded += value.byteLength;
                onProgress(Math.round((loaded / total) * 100));
                controller.enqueue(value);
                read();
              })
              .catch((error) => {
                console.error(error);
                controller.error(error);
              });
          }
        },
      }),
    );
  });
};
Enter fullscreen mode Exit fullscreen mode

Could even break out init more here and take in body / method / etc.. and build the init if you wanted but point was just to show it could be done. Honestly like the author mentioned it will just rely heavily on your comfortableness with learning and utilizing native Api stuff. Honestly unless you are specifically required to there is definitely not a "need" to use Axios anymore in my opinion. It served its purpose and has ended up in the same bin as jQuery. Its freaking everywhere still somehow and you need to understand how it works because your going to run into it in codebases you have to touch. I would never use it or suggest it to anyone if given the choice though.

Collapse
 
daviddanielng profile image
David Daniel • Edited

axios is the worst js library I have ever used, it is so difficult to request images. I have tried but it just makes simple things more complex just like almost every other JS libraries. Now I use fetch for all my projects, so much simpler and less headaches.

Collapse
 
cast-el profile image
Vincent

Hello I have made my own light weight library for creating https request : npmjs.com/package/castelapi

Fully written in typescript, auto parse, cache management,etc.

Any contribution is welcome!

Collapse
 
nikhilroy2 profile image
Nikhil Chandra Roy

I am jquery ajax method lover, I have used it lot in django templates and still using it.

Collapse
 
gaetansenn profile image
SENN Gaetan

vs ofetch

Collapse
 
intermundos profile image
intermundos

Depends on your needs. I very much like the ky client.

Collapse
 
kizukuraudo profile image
John Keys Cloud

Should mention async functions.

Collapse
 
perseon profile image
perseon

I think this guy has a very pertinent explanation why a wrapper library is still needed
youtube.com/watch?v=O0-rb1B74xs