Comment by beart
25 days ago
> nearly every other project uses it for some reason instead of fetch (I never understood why).
Fetch wasn't added to Node.js as a core package until version 18, and wasn't considered stable until version 21. Axios has been around much longer and was made part of popular frameworks and tutorials, which helps continue to propagate it's usage.
Also it has interceptors, which allow you to build easily reusable pieces of code - loggers, oauth, retriers, execution time trackers etc.
These are so much better than the interface fetch offers you, unfortunately.
You can do all of that in fetch really easily with the init object.
})
There are pretty much two usage patterns that come up all the time:
1- automatically add bearer tokens to requests rather than manually specifying them every single time
2- automatically dispatch some event or function when a 401 response is returned to clear the stale user session and return them to a login page.
There's no reason to repeat this logic in every single place you make an API call.
Likewise, every response I get is JSON. There's no reason to manually unwrap the response into JSON every time.
Finally, there's some nice mocking utilities for axios for unit testing different responses and error codes.
You're either going to copy/paste code everywhere, or you will write your own helper functions and never touch fetch directly. Axios... just works. No need to reinvent anything, and there's a ton of other handy features the GP mentioned as well you may or may not find yourself needing.
16 replies →
What does an interceptor in the RequestInit look like?
1 reply →
It also supports proxies which is important to some corporate back-end scenarios
fetch supports proxies
Before that we had node-fetch. If you already use a dependency why not one that's pretty much what will come natively to every JS runtime soon.
The fetch API is designed for browsers. It's not designed for servers. Fetch may work for a particular use case on the server, it may not. Servers have needs over and above what a browser allows the client to do.
Now I'm curious, because we have a big server side code base using fetch(). What are you using that doesn't work with fetch? Especially since axios nowadays has a fetch adapter.
Right. Though I would've used the built in xhr then. Not going to install a dep just to make http calls.