DEV Community

Cover image for How to override XHR/fetch method in Javascript?
Keval Rakholiya
Keval Rakholiya

Posted on • Edited on

How to override XHR/fetch method in Javascript?

Introduction

In this post, I'll explain how to override XHR or fetch requests in javascript. We will use a Proxy object of javascript to add hooks in XHR or fetch requests.

Prerequisite

Why Does it Matter?

Sometimes when we are working with API requests on the front side. And we face a scenario like we want to send data to all requests or we want to filter all the response data. Or when we are working with a third-party website, for example, We are a third-party app for the Shopify store. On the front side, we want to display a popup when the product is added to the cart by the user. We can add a hook in API calls and monitor the activities of the customer.

How to override XHR/fetch method in Javascript?

We are going to use Proxy object of javascript.
The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

Override XMLHttpRequest
XMLHttpRequest(XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XHR is a class base object. Here is the snippet for adding a hook in XHR.

XMLHttpRequest = new Proxy(XMLHttpRequest, {
      construct: function (target, args) {
        const xhr = new target(...args);
        // Do whatever you want with XHR request
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 1) {
            // Before sent request to server
            xhr.setRequestHeader("Authorization", "XXXX-XXXX-XXXX-XXXX");
          }
          if (xhr.readyState === 4) {
            // After complition of XHR request 
            if (xhr.status === 401) {
              alert("Session expired, please reload the page!");
            }
          }
        };
        return xhr;
      },
    });
Enter fullscreen mode Exit fullscreen mode

In the above example, we created a new copy of XHR with our code and re-assigned it to the XHR. We added a new header to all the requests which will be submitted from our page. We can check the response data also when the XHR is completed. We successfully injected our code into XHR request.

Override fetch API request
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network. Fetch is a function base object. Here is the snippet for adding a hook in the fetch request.

window.fetch = new Proxy(window.fetch, {
      apply: function (target, that, args) {
        // args holds argument of fetch function
        // Do whatever you want with fetch request
        let temp = target.apply(that, args);
        temp.then((res) => {
          // After completion of request
          if (res.status === 401) {
            alert("Session expired, please reload the page!");
          }
        });
        return temp;
      },
    });
Enter fullscreen mode Exit fullscreen mode

In the above fetch example, we created a copy of the fetch using a proxy and re-assigned it to the original fetch request. apply property of proxy takes a function as a value. The passed function will execute whenever fetch will calls. We have our hook in fetch request. We can add a custom header we can add/update or delete the payload of the request. After the successful completion of the API, we can filter the response header, and we can add/update, or delete response data.

I hope this will help and fulfill your requirements for all the developers who want to add hooks to API calls. Suggestions are most Wellcome. Reach me at Github.


Top comments (0)