May 2nd, 2022 × #javascript#webdev#axios#fetch#apicalls
Why do people still use Axios over Fetch?
Wes and Scott discuss why developers still use the Axios library instead of the native fetch API for network requests in JavaScript. They go over various features like interceptors, progress events, and adapters that make Axios powerful.
- Discussing Axios vs fetch for network requests
- Linode sponsor spot
- Sentry sponsor spot
- Axios allows avoiding double JSON promise with fetch
- Axios has interceptors like middleware
- Some are fine with default fetch capabilities
- Many use a framework that handles network requests
- No need to tack on double JSON promise with Axios
- Fetch can be enhanced to do anything Axios does
- Interceptors allow request manipulation
- Interceptors allow caching third party API data
- Interceptors allow token refresh on expired JWT
- Fetch works for most use cases, but can build on it
- Axios handles progress events for uploads/downloads
- Progress accuracy depends on file sizes known on client/server
- Axios validateStatus API handles tricky server responses
- Axios allows default headers and API keys
- Axios adapters useful for mocking HTTP requests
- Axios allows custom request timeouts
- Shouldn't use Axios just to avoid double promise
- Useful when working with tricky third-party APIs
- Postman generates Axios code snippets
Transcript
Announcer
Monday. Monday. Monday.
Announcer
Open wide dev fans, get ready to stuff your face with JavaScript, CSS, node modules, barbecue tips, get workflows, breakdancing, soft skill, web development, the hastiest, the craziest, the tastiest web development treats coming again hot. Here is Wes, Barracuda, Boss, and Scott
Scott Tolinski
CSD.
Scott Tolinski
Welcome to Syntax.
Discussing Axios vs fetch for network requests
Scott Tolinski
In this Monday, hasty treat, we're gonna be talking about it. Axios and why people still use Axios over fetch, instead of fetch, I should say. So my name is Scott I'm a developer from Denver, Colorado. And with me, as always, is the Axios user of the 2 of us, Wes Boss.
Scott Tolinski
Hey.
Wes Bos
Excited to talk about this. I'm I'm of the
Scott Tolinski
specific mind of the type of person who is looking at this episode and being like, yeah. Why? Why do you people use Axies over fetch? Because we've only ever used fetch.
Scott Tolinski
I'm very used to fetch, and I don't do a ton of complex stuff with it, but at the same time, I don't necessarily have any problems. So I'm interested in hearing Yeah. What exactly the use cases here, Why it's better? All of those lovely things. But before we get into that, let's talk about 2 of our amazing sponsors, 2 companies that are have been Sponsored us for a long time now, and some of our our favorite services out there, we have Linode and Sentry.
Wes Bos
Wes, do you wanna talk about Linode? Linode is cloud computing that developers trust.
Linode sponsor spot
Wes Bos
It's awesome. If you have you're a JavaScript developer listening to this episode, You wanna host that app that you just built somewhere? Well, Linode offers VPN or VPS, sorry, virtual private servers. You can Spin up a Linux server. You can use some of their, premade Node versions where you can just spin it up and you have Node installed for you, And you can host your website right on Linode. They offer all kinds of other stuff as well.
Wes Bos
Check it out at linode, l I n o d e, .comforward/syntax.
Wes Bos
That will get you a $100 in free credit, which is pretty sweet. Thank you, Linode, for sponsoring. This
Sentry sponsor spot
Scott Tolinski
episode is also sponsored by Sentry at Sentry dot io.
Scott Tolinski
Sentry is one of those tools that you just gotta have. It's a perfect place to capture, log all of your errors and exceptions. But more than just that, It helps you understand how your website is functioning at any given point in time, which release has made it more buggy, less buggy. If you have regressions, Things they've already fixed that have made their way back or perhaps things that you thought you fixed and you didn't actually fix them. Sentry's gonna let you know, and it'll even I send you a notification or an email saying, hey. There's been a regression here. You said this thing was fixed, and it wasn't.
Scott Tolinski
Sentry also is also always changing with either a custom dashboards being added or performance metric tracking tools. It's one of those tools that's been evolving for a long time, And you gotta love that. So check it out at century.io.
Scott Tolinski
Use the coupon code tasty treat, all lower case, all one word, and you will get 2 months for free. Thank you so much for Century for sponsoring.
Scott Tolinski
Okay. So Axios, Wes. Axios is spelled a x I o s is a library that people use instead Instead of the fetch API to do network requests. Correct? Exactly. Exactly. And,
Axios allows avoiding double JSON promise with fetch
Wes Bos
I thought we would have a little episode on, like, why do People still use it and, like, what features are there that you are not sure of? Because, Axios was Around long before fetch was, and it was it is that like the best, like, ergonomic library for actually firing off.
Wes Bos
I call AJAX requests to fetch data or images or literally anything you upload, upload something to the server.
Axios has interceptors like middleware
Wes Bos
It's it's great for that.
Wes Bos
And often you see, like, like, why people are just like, why would you ever use Axios? Now we have fetch, fetches in, and now it's in node. Fetches in all the browsers. I don't see why you would ever want to do that. So Let's just dive into some of the features that they have. And, I've got just a bunch of both different bullet points here.
Wes Bos
And the sort of I I think the probably the biggest one why someone wouldn't use Fetch is either sorry. Not Fetch. Axios It's either you're perfectly fine with fetch. It does absolutely everything you want. And I think for a lot of people that is that's true. For me, I would say in 90% of the use cases, Fetch does everything that I possibly want.
Wes Bos
And if there's something like I don't necessarily like the double the double, promise.
Some are fine with default fetch capabilities
Wes Bos
You just make a little, just make a little, function and they and and tuck that away in inside of a function. Right? Yeah. Yeah. Totally. And then you're like, you could just it. Fetch JSON function and and call it a day. So either people are fine with that or, and I suspect this is true with you, For your more complex stuff, you're not using fetch. You're using, like, a library that integrates with React or Svelte or, GraphQL, or it's being generated for you automatically
Scott Tolinski
in in a is that true with you? It's sort of true. It's true in the fact that I am using a library to do that, But what's not true is that or I guess a caveat here is I wrote the library. So the library is just using that, and I wrote that. And it is being generated, but it's calling it what's in my library is called g fetch or gquery yeah so it's running a g fetch which is really all it's doing is Taking a GraphQL query, turning it into the appropriate type of string in the body, and then calling fetch directly. So even that is just using Fetch as is. It's not using anything else, but I mean, I wrote it. So yeah. Yeah. It it is a lot. I think that's that's another thing is that,
Many use a framework that handles network requests
Wes Bos
with fetch can do anything you want.
Wes Bos
And before you know it, you say, oops, I wrote a library. Right? And and That that's good in in most cases. So let's go through it. So I think the the number one reason why people are still using Axios over fetch is because they started Before fetch was the thing, and there is no benefit to switching over. The the benefit, I think, would be is that You don't have the dependency of Axios in any of your code, which is which is very valid when you're doing client side code because you don't have to download that entire library.
Wes Bos
On server side, it's it's not so much. Right? Yeah. Totally. Next one is no need to tack on a double JSON promise. That's a pretty minor one. Yeah.
No need to tack on double JSON promise with Axios
Wes Bos
Having to like so in fact, you have to await the response, and then you have to await the response that's turned into, JSON. JSON or text or
Fetch can be enhanced to do anything Axios does
Scott Tolinski
whatever. Most likely, it's JSON. Right? What's funny is for me, Like, that that one doesn't necessarily hit me that hard, but that is the exact type of thing where I would use. Like, there's so many use cases where I would pick a library over another one because it doesn't make me do a double thing. I'm like, oh, it's 1 less line of code. That's cool with me. But in this particular case, for some reason, it just doesn't bother me. I don't know why. That's good.
Wes Bos
Next is so Axios has a huge feature called the interceptors, and an interceptor is Kind of like middleware in on the server side where you, you intercept a request. And on that request, you can do things like add API keys. You can add specific headers that need to be added.
Wes Bos
You can reject the request if The data being sent is not valid.
Interceptors allow request manipulation
Wes Bos
You can massage the data. So, maybe you're in a migration, and you used to send an object that was straight data, and now you need to send An object that has a data property inside of it. Like, that's that's a big one. Okay. We're making a a full API version change here.
Wes Bos
And in order to support some of the future stuff that we are doing, now we have to change how the data is being submitted to our Our back end in okay. We have a 100, Axios requests in our library, in our thing. You could just wipe 1 interceptor And say if there is no data property, then create a new object, stick all the data in a data property, and then keep going along. That'd be really handy in a migration Without having to do it all at once because you can't possibly do that all in in one go. Right? Yeah. It's fine. Is would you consider that it. Middleware in quotes here. I think so. Yeah. It's they call it a interceptor, but that's it I like the idea of calling that a middleware. Yeah. Because as you were explaining that, I was like, kinda feels like middleware, but I'm not quite sure if that doesn't fit the definition for some reason. So yeah. Yeah. Okay. We had a couple people on Twitter say that they use it.
Wes Bos
They use interceptors to cache third party data. So, again, like, we talked about this in the episode about, cloud functions.
Interceptors allow caching third party API data
Wes Bos
If you are hitting a third party API, for example, the weather API, and the weather API only gives you a 100 requests an hour Or or a 1,000 requests a day.
Wes Bos
What you can do is you can intercept those requests and say, okay. Given the The query that you have provided, have we already done that request in the last hour? If so, then just serve that up From cache, and a lot of people said we just stick our API data in Redis, and have a nice quick little cache to serve up from there. Pretty easy.
Interceptors allow token refresh on expired JWT
Wes Bos
We had, somebody on Twitter said, Interceptor cat caching sorry, catching An expired JWT and renewing it on the fly, and replaying the initial request with a new token is a huge Deal breaker. Can I do that with plain fetch? So, that's kind of an interesting one. If you got an app sitting around for 12 hours. Maybe it's a desktop app. Somebody makes a new request, they hit the refresh button. You can renew your JSON Web Token on the fly and replay it.
Wes Bos
And he said, Can I do that with plain fetch? And the answer to that is, Yeah, you can do anything with plain fetch.
Wes Bos
You just have to actually write the code to actually do that. Right? Like, fetch is kind of interesting because it is like a it's a fundamental, but it also Just works in most of the use cases as well. You don't necessarily need to build on top of it, but if you if you want to, you totally can. Interesting.
Fetch works for most use cases, but can build on it
Wes Bos
Progress. Upload, download progress.
Axios handles progress events for uploads/downloads
Wes Bos
If you want to be able to share with your user, let's say they're uploading 20 megs of images, you want to be able To handle progress events that are being sent back from the server and display that. Apparently, Axios does a really good job at Handling multipart uploads like that.
Scott Tolinski
Yeah. How how accurate is those types of progress things? I always wonder about that. So it's basically calculating, Yeah. I guess just the total data sent versus the total data is there. But is it On the on the client, you can tell how big images are.
Wes Bos
And on the server, it will tell you how much progress it is. Also, it should know know how large the image is that is being sent to it. Yeah.
Wes Bos
So it should be able to provide you with both of those. I've actually never had to write a
Scott Tolinski
progress upload I have my I I have in my brain, I I just think about, like, the Windows 95 progress ones, where it'd be, like You know, it's, like, 99% of the way on the progress meter, but it still is gonna take, like, another 4 hours even though this is totally inaccurate.
Wes Bos
Yeah. I think Those are inaccurate because they don't necessarily know the speed of your network and of the hard disk that it's writing to and how many files there are.
Progress accuracy depends on file sizes known on client/server
Wes Bos
And just uploading files, you know what is being requested to be uploaded. And the progress doesn't tell you how much time is left. You could estimate that based on how well it's going, But the progress should just tell you out of 10 megs, this is how many have been uploaded, and this is how many files have been uploaded. Word.
Wes Bos
This one is really interesting to me is the validate status API. Have you ever had this happens in my advanced React course. Have you ever had a successfully failed error in GraphQL?
Scott Tolinski
Yeah. That's almost in well, so the whole thing is that GraphQL always returns a 200 no matter what, Or at least it should. Like, that's the the way you're supposed to do. Requesting GraphQL is to return a 200. And then in the message, it. The data, you should declare whether or not there's been an error or not, which is honestly one of my least favorite parts of GraphQL. It's like, I just wanna, you know, return the correct browser status or whatever. It doesn't it doesn't throw when it's an error. So you have to check success if it's successfully errored.
Axios validateStatus API handles tricky server responses
Wes Bos
So in Axios, if for whatever reason, the The server you're working with is is giving you the wrong status code or you want to check the data and then change the status code based on the data that is returned, you can do that with a validate status.
Wes Bos
The validate status API is part of Axios. So, again, if you've got a Particularly tricky API that you're working with. You can write a little bit of normalization in there to to make it work how you're expecting, especially if you're If you're working building an app that interfaces with lots of different APIs out there And all the APIs don't work exactly the same. Like me making a real estate API and you're trying to trying to talk with Zillow and real turn, you know, and they don't all work exactly the same way. It's really hard to write, consistent code when all of them are different. So being able to write, like, again, kind of like a middleware, is really handy there.
Wes Bos
Defaults.
Wes Bos
So if you want to set API keys and default headers on all of your requests, You can set defaults in that, and it will go again. You you could also just make a a default object and send that along on every single fetch request or put that into a closure with fetch. You could do that easily, but that's like Axios offers.
Axios allows default headers and API keys
Wes Bos
Axios has adapters, Which is really handy for testing if you need to, like swap out An API for some fake data, potentially. Yeah. What does an adapter mean in this context? Let's let's pull up the The Axios docs, if they got a good example. So one one of these is the Axios mock adapter, where, if you are hitting an API, You could write an adapter that again, it's kind of like a middle where it steps in doesn't actually hit the API for that data, but it It will step in between and return some fake data. An adapter allows custom handling of requests makes makes testing easier. That's what they have in there. So again, not something I would probably leave that up to my testing library and to do mocking and spying on those network requests. That seems something that is better suited to put it at a test level. But again, it's it's in there. I'm sure there are some good use cases for that. You know what we do?
Axios adapters useful for mocking HTTP requests
Scott Tolinski
We use MSW mock service workers for mocking for our tests. And that's pretty neat because it steps in in the middle as a service worker Oh. And will return the data. That's exactly what service because our 4. Yeah. The only the only bummer is is that I have to turn off server side rendering for our a to e tests because then it still wants to return the data from the server if I want mock data. Oh, yeah. So that's that's the only bummer with that approach. Interesting.
Wes Bos
That's cool. Custom timeouts. This is a big one. If you want to be able to set a timer, Alright. Fetch this API, but only only try for 10 seconds or 2 seconds.
Wes Bos
Fetch doesn't have a time out. You'd have to set up your own timers with fetch if you wanted to put a custom time out on something.
Axios allows custom request timeouts
Wes Bos
So, again, that's probably not something people are hitting all the time. Right? But if they you specifically are working with a server I think a lot of these are if you're working with a server that could be tricky, Especially if that server is out of your control, then a lot of these use cases come in really, really handy.
Scott Tolinski
Yeah. I didn't know it was so full featured. I guess it. It, like, almost feels like a like a framework type of deal, like an express type of thing where you have all these nice little helpers. I thought it was really just, oh, You know, we'll reduce the double request on on fetch. Yeah. That's what and, honestly, that's what a lot of people a lot of people used it for, but,
Shouldn't use Axios just to avoid double promise
Wes Bos
I don't think that that is you shouldn't be using it if that's what all you're using it for. Well, see, that that's exactly why I was of the mind of, like, I don't get why
Scott Tolinski
Wes likes the singer uses this thing, so I'm glad that I got to be a little audience proxy for most of this here. Yeah. Like, we I also use it in my own application
Useful when working with tricky third-party APIs
Wes Bos
Where, we check if you are authenticated and you have the specific permissions on the client side. So when you send off a request, Evan, and if you're not logged in or if your login has expired, then it would just redirect you to a specific one, which is pretty cool. And then the last 1 here is, I use it because Postman auto generates Axios code.
Wes Bos
Call me lazy, but it's true. It's helped me move fast with quick no JS scripting efforts many times, so I thought that was funny. I would imagine that These Postman things would also be adapted for for fetch pretty soon as well because that's kind of cool. But That is why people still use Axios. It's a great little tool. Again, I probably still use fetch in 80% of my use cases, but For when you want a little bit more control and you feel like I'm kind of rewriting the wheel here. Is that a Rewriting? Yeah.
Postman generates Axios code snippets
Wes Bos
Reinventing the wheel here. Then there's probably a use case in Axios for that type of thing If you don't wanna have to rewrite your entire function yourself. Nice. Cool. Yeah. It it's a funny day. You you had that moment with reinventing the wheel.
Scott Tolinski
Wes, I, I've been listening to this new podcast where it's just 2 people reviewing Dateline episodes, and I don't even watch Dateline. It. But, you know, Dateline's kind of an outrageous show, and these people have, like, a whole system about it. And I found it to be super entertaining. But in one of the episodes that I was listening to, There's a guy who kept saying things that weren't real things or combining multiple sayings, and I was just thinking about how many times we both both do that because the one that the episode is like, Oh, yeah. She she's off her marbles.
Scott Tolinski
It's like, off her marbles or, like, lost her marbles off her rock or whatever That he was trying to say is just like mixing several different sayings together, and I was just cracking up every time because the poor guy could not come up with one real saying. I love I I love mixing up sayings or making your own sayings. Those are great drives people crazy. It does. Yes.
Wes Bos
All right, everybody, thank you so much for tuning in and we will catch you on Wednesday.
Wes Bos
Peace. Peace.
Scott Tolinski
Head on over to syntax.fm for a full archive of all of our shows, And don't forget to subscribe in your podcast player or drop a review if you like this show.