It’s fetch time or: How I stopped using http libraries

I still remember the first time when read about Fetch API few years ago somewhere in Chromium’s change log. I was excited by its simplicity and promised based API, compared to XMLHttpRequest. However, I couldn’t use it till ~1 year ago when finally browser support become better and there is good polyfill.

Why should we use it:

Or my few reasons:

  • really simple API and I have full control over it
  • it uses native Promises
  • no external library needed, so I could ship less code to my users
Fetch API browser support in 2017, all major browsers support it

How to use it basics

Nowadays almost every web app is SPA and connection to data is through REST API which typically returns JSON. It is pretty simple, pass the URL to the function which returns a promise, after that just convert the response to JSON.

fetch(‘http://httpbin.org/get’).then(response => response.json())

How I use it in real world project

I created a file api.js: first I need config file, in which specify API base URL, after that I create very simple function that uses fetch method, keep in mind that fetch doesn’t return JSON by “default” so we need to convert response object to JSON (chaining then methods).

Helpers

Usually, I make few helpers for every HTTP method: post / get / delete / patch / head.

Еrror handling

Error handling is a bit different compared to JS libraries, first of all, 404 ( or other errors codes ) does not throw an error, that means they don’t go to catch block. That’s why we need to check the status of page with response.ok or we could check status code response.status.

Auth token

User authorization is another application feature that appears very often. Nowadays that process happens via token (JSON Web Tokens). In general, that is just sending another header which contains the value of the token.

Adding async/await

If you want to simplify even more your async code you should start using async/await (part of ES2017) in that way your code looks more than synchronous one, but it isn’t.

Full example

That is the whole code that I use in almost every new project, to that, I add fetch polyfill.

#UseThePlatform

Use the platform, shipping 10kb extra for axios or another http library is not so much but, it is not needed either.