By

Monitoring performance of your Fetch API

The fetch API allows you to make network requests similar to XMLHttpRequest (XHR). We already wrote a blog about how Fetch API are simple and yet powerful compared to XHR.

Atatus now supports Fetch API monitoring out of the box. You don’t need any special configuration to measure performances of the Fetch API.

Fetch API vs XHR

The main difference between XHR and the Fetch APIs is the lines of code needed for similar tasks. Lets see example of getting a JSON resource with XHR and Fetch.

Using XHR:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.acme.com/some.json');
xhr.responseType = 'json';

xhr.onload = function() {
    console.log("Response", xhr.response);
};
xhr.onerror = function() {
    console.log("Opps, Something went wrong!");
};

xhr.send();

Using Fetch:

fetch('https://api.acme.com/some.json')
.then(function(response) {
    return response.json();
}).then(function(jsonData) {
    console.log(jsonData);
}).catch(function(err) {
    console.log("Opps, Something went wrong!", err);
})

How we collect timing metrics from a Fetch API

In Atatus, we internally wrap Fetch API to measure the start and end time of the fetch calls. If it is fetch polyfill, we will not wrap, because Fetch plolfill is an already wrapper around XHR requests. Since we are already monitoring XHR request, we will not do any double wrap to Fetch polyfills.

This is the sample abstract code for monitoring the Fetch API. The production version is lot more different from this abstract code.

var originalFetch = window.fetch;
window.fetch =  (function (originalFetch) {
  return function (fn, t) { // preserve arity

      // Start measuring Fetch API

      return originalFetch.apply(this, args).then(function (response) {

          if (typeof response.status === 'number' && response.status < 400) {
              // Capture timing of Fetch API
          }

          return response;
      });
  };
})(originalFetch);

A solid monitoring system like Atatus in place will give an objective view of how Fetch APIs are performing, and data to improve better user experience. Atatus is the one place for monitoring your entire stack, Start today with free 14 day trial – no credit card required.

Written by
Developer

With Atatus, Get to know exactly how your users are experiencing your app.

Start your free 14-day trial