View profile

Should You Use Axios or Fetch?

Axios is our preferred HTTP client for JavaScript. It's isomorphic, has widespread adoption, and just
Should You Use Axios or Fetch?
By Mastering JS Weekly • Issue #27 • View online
Axios is our preferred HTTP client for JavaScript. It’s isomorphic, has widespread adoption, and just enough features to be useful. But why use Axios when most JavaScript browsers come with fetch() built in?
Here’s a few reasons why we prefer Axios to fetch:
  • Node.js support. Browsers support the fetch API, but you still need a fetch polyfill for Node.js.
  • Automatic JSON serialization and JSON parsing. The fetch API is designed to support streaming response bodies, so it doesn’t automatically serialize and deserialize for you. In our opinion, streaming an HTTP response is an incredibly niche use case and you shouldn’t design a general API around it. But we aren’t on TC39.

`fetch()` returns a promise that resolves to a stream (the first .then above)
`fetch()` returns a promise that resolves to a stream (the first .then above)
  • Axios instances. Axios’ `create()` function lets you encapsulate certain defaults into an Axios instance, so you don’t need to write your own wrapper around Axios to set the base URL and various headers. This means Axios doubles as a lightweight HTTP framework, whereas fetch is just a library.
Create an Axios instance with defaults to keep your code DRY
Create an Axios instance with defaults to keep your code DRY
  • Interceptors. Most HTTP clients return poorly formatted errors. Neither Axios nor fetch is an exception, their error messages aren’t very helpful. Normally, Axios error messages look like “Request failed with status code 404”. But Axios has just enough elements of a framework to let you transform errors in a way that makes sense for your application.
Axios interceptors can transform error messages
Axios interceptors can transform error messages
We use Axios almost everywhere, including to test Mastering JS’ Express tutorials. Occasionally we use superagent, but we rarely use fetch.
Most Recent Tutorials
Other Interesting Reads
GitHub OAuth Login with Node.js | www.thecodebarbarian.com
Replace axios with a simple custom fetch wrapper
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue