React JS: Interceptors with Fetch API
Snigdho Dip Howlader
Posted on September 15, 2022
What are Interceptors?
Interceptors are a way to trigger specific functionalities before or after a request is made, or a response is received respectively. One of the most commonly used reasons for interception is authentication on the frontend, or re-routing an API URL to something other than the original.
Fetch API
The Fetch API is a very simple and effective way to handle requests and responses with JavaScript or any JavaScript frontend libraries. Namely, React JS has used it quite a lot before the rise of the extremely popular Axios library. Axios actually has some in-built ways to handle interception, both for requests and responses.
However, when working with or maintaining code that is a bit older, Axios may not have been as widely used then as it is used today - and the Fetch API was the only way to advance.
Intercepting with the Fetch API
To put it simply, Fetch API interception is quite easy to do because all that's needed to be done is re-write the fetch function itself. The fetch function takes in two parameters, the resource (the URL) and the config, after which the Promise can be handled.
The following is an easy way to understand the fetch API function. Destructuring the _originalFetch _ function from the window.fetch, you can use it to then get the resource and config mentioned earlier from the arguments of window.fetch.
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [resource, config] = args;
const response = await originalFetch(resource, config);
return response;
};
Any functionality you write here will be executed each time a fetch call is made once this code chunk has been loaded into React JS. For testing, you can simply put this inside a useEffect in App.js, and log something into the console inside this function. Every time onwards a fetch call is made, that particular console log will be executed.
How to intercept requests with React JS
For this demonstration, we are attempting to re-route a fetch call to a dummy JSON generator for posts, to one for quotes instead. Every call made to get posts will instead be re-directed to get quotes and shown in the frontend instead.
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [resource, config] = args;
const URLcutOff = "https://dummyjson.com";
const trailing = resource.slice(URLcutOff.length);
if (trailing.startsWith("/posts")) {
resource = `https://dummyjson.com/quotes?limit=5`;
}
const response = await originalFetch(resource, config);
return response;
};
This is the code that will be doing it. Essentially, it is going to remove the base part of the resource URL and check if it has a trailing section that contains the characters "/posts", it will instead be replaced by "/quotes". Since the resource is being changed mid-way, the originalFetch function will now use the changed resource and return the response that is sent back from it.
It is that simple! You can re-write this code to try out your own API calls instead of the two that are provided here. A React project is set up for you to try this out on your own from. It has a frontend with a pair of buttons. One button (Posts) to return the data for posts, and another button (Intercept) that will stop making calls to the posts resource every time you click the Posts button, and instead make calls to the quotes resource.
Demonstration:
When the Posts
button is clicked:
When the Posts
button is clicked after clicking the Intercept
button:
You can even see in the inspect tab, that the quotes API is called even after the Posts button is being clicked.
That was it for a simple demonstration of monkey patching with request interception using the Fetch API. Here's a link to the repository that contains all the source code in React JS.
Source Code: https://github.com/snigdho611/fetch-interceptor
By: Snigdho Dip Howlader
Posted on September 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.