Writing a custom interceptor for fetch in JS
Interceptor helps in intercepting a request or a response made to the backend from the frontend. These can come in handy in certain situations where you want to intecept every request, modify request parameters, make changes around the body of the request etc. Same goes with reponse interceptor where based on the response of the request, you can make changes to the body of the response, log errors to console, display toast notifications etc. These can be completely designed to suit the requirements of the project. These can also be customised to block certain request based on the request url. The most famous axios library also supports adding custom interceptors.
Here, in this article, I am using the in built fetch function, and overriding it with my own custom fetch which suports interceptors.
At first, I will take a copy of the original fetch, so that I can reuse it in my custom fetch
const originalFetch = window.fetch;
Now, I will write a custom fetch function with request and response interceptors and then override it with the original fetch.
const originalFetch = window.fetch;
const customFetch = async (resource, options) => {
console.log("request intercepted here");
const response = await originalFetch(resource, options);
console.log("response intercepted here");
return response;
};
Now, when I make a fetch call, it will log the request and response interceptors in the console.
const originalFetch = window.fetch;
const customFetch = async (resource, options) => {
console.log("request intercepted here");
const response = await originalFetch(resource, options);
console.log("response intercepted here");
return response;
};
window.fetch = customFetch;
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => console.log(json));
The console would print something like this,
request intercepted here
{userId: 1, id: 1, title: "delectus aut autem", completed: false}
response intercepted here
The above code explains a simple technique to write custom interceptors by overrinding the default fetch function.