You may not need Axios

This is not an attack on Axios.

Rather, it’s advocacy for the fetch API which has become quite capable. 🦄

Overview

I’ll be the first to say: I was an early hater of the fetch API. My first attempt turned into an entirely wasted weekend. I didn’t know I was using broken examples. #fail

The good news is that a large proportion of the documentation and corresponding examples have been improved, and I’ve included several code snippets with common uses cases below.

I’ve collected up-to-date code examples for the patterns which “unlocked” fetch for me.

Check out the head-to-head Feature Comparison; then browse my curated Fetch Examples I’ve accumulated over the past year.

Feature Comparison

fetch axios request Intercept request and response ✅ ✅ ✅ Transform request and response data ✅ ✅ ✅ Cancel requests ✅ ✅ ❌ Automatic transforms for JSON data ✅ ✅ ✅ Client side support for protecting against XSRF ✅ ✅ ✅ Progress ✅ ✅ ✅ Streaming ✅ ✅ ✅







When starting this article (late 2018) I assumed I’d end with a table of mixed check boxes. Surely there are special Use Cases which justified axios , request , r2 , superagent , got , etc. Well, as it turns out, I overestimated the need for 3rd party http libraries.

Despite using fetch for 2 years (including for non-trivial tasks: file uploads & error/retry support) I still had misconceptions of fetch ’s abilities and limits. (Specifically regarding progress updates or canceling requests.)

Fetch Examples

Click the links below to go directly to the code snippet.

Is your Use Case not listed? Let me know ✉️

Get JSON from a URL

Custom headers

HTTP Error Handling

CORS example

CORS is primarily checked at the server - so make sure your configuration is correct on the server-side.

The credentials option controls if your cookies are automatically included.

Posting JSON

Posting an HTML <form>

Form encoded data

To post data with a Content-Type of application/x-www-form-urlencoded we will use URLSearchParams to encode the data like a query string.

For example, new URLSearchParams({a: 1, b: 2}) yields a=1&b=2 .

Uploading a file

Uploading multiple files

Setup a file upload element with the multiple attribute:

Then use with something like:

Timeouts

Here’s a generic Promise timeout, using the “Partial Application” pattern. It’ll work with any Promise interface. Don’t do too much work in the supplied promise chain, it will keep running - and any failures have a way of creating long term memory leaks.

And a more complex example, featuring a tracking flag __timeout so you can intercept any costly work.

Download Progress Helper

This is included for completeness. You may still want to use a 3rd party library here. Browser streaming interfaces may lack browser compatibility (as of late 2018). Upload Progress is currently a bit buggy outside of Chrome.

The Progress Handler technique shown below avoids wrapping the fetch call in a closure. 👍

progressHelper has the following interface (source available below)

Let’s look at a usage example:

A reusable image downloader might look like getBlob() :

By the way, a Blob is a Binary Large Object.

It’s important to choose ONE of the 2 usage patterns below (they are functionally equivalent):

My preference is Option #1 . However, your scope design may force you to use Option #2 .

Finally, here’s the last part of this recipe, our progressHelper :

Source: Progress Helper

credit: Special thanks to Anthum Chris and his fantastic Progress+Fetch PoC shown here

Compatibility

“What about NodeJS and the poor IE people?!?”

Fear not, the fractional % of IE9-10 users can be polyfilled with the github/fetch package (maintained by some awesome team at GitHub). It’s possible to go as far back as IE8 - Your mileage may vary.

NodeJS can take advantage of the the fetch API with the node-fetch package:

npm install node-fetch

After polyfill+node-fetch: 99.99% compatible ✅

More coming soon.