How to implement interceptors in Fetch?

•

Fri Mar 31 2023

•

4 min read

Interceptors allow you to modify, redirect, or block requests and responses as they flow through the Fetch API.

This gives you greater control over your network traffic and can be used to implement advanced features such as caching, logging, and error handling.

Types of Interceptors

In general, there are two types of interceptors:

  1. Request interceptor: Allows you to modify requests before they are sent to the server
  2. Response interceptor: Allows you to modify responses before they are processed by the client.

You can use one or both types of interceptors, depending on your needs.

Intercepting Requests with Fetch

Fetch API doesn’t support request interceptors out of the box, but we can create a wrapper on fetch to implement it. This wrapper will act as an interceptor and can be useful for adding headers, changing the request body, or even canceling the request entirely.

We will also use the Random Words API in our implementation. So please go ahead and subscribe to the API.

Loading component...
js
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [resource, options] = args;
if (resource.includes('rapidapi')) {
options.headers['X-RapidAPI-Key'] = 'your-rapid-key';
}
const response = await originalFetch(resource, options);
return response;
};

We have replaced the original fetch function with a new one that intercepts requests and modifies them as needed before sending them out.

The originalFetch function is assigned to a new variable so that it can be called later on in the code. Then, the new fetch function is defined with async keyword, which means it returns a promise. It takes in the arguments resource and options, which represent the URL and fetch options, respectively.

Then we have checked if the API endpoint includes rapidapi. If it does, we set the request header to include Rapid API key. This way, if the user is using multiple APIs from Rapid API Hub, they will not have to add API key in every request. The request interceptor will take care of it.

Finally, we call the originalFetch function with the modified resource and options objects and return the response.

Here is the complete code:

html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Fetch API Interceptors Example</title>
</head>
<body>
<h1>Fetch API Interceptors Example</h1>
<button id="fetch-button">Fetch Words</button>
<script>
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [resource, options] = args;
if (resource.includes('rapidapi')) {
options.headers['X-RapidAPI-Key'] = 'your-rapid-key';
}
const response = await originalFetch(resource, options);
return response;
};
function fetchWords() {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'random-words5.p.rapidapi.com',
},
};
fetch('https://random-words5.p.rapidapi.com/getMultipleRandom?count=5', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
}
const fetchButton = document.getElementById('fetch-button');
fetchButton.addEventListener('click', fetchWords);
</script>
</body>
</html>

To see if your Request Interceptor is working, you can add a custom header to it. For example, you can add a default content type header with a specific value to the request.

Then, when the request is sent out, you can inspect the outgoing request in the browser's developer tools to see if the URL or header has been modified according to your implementation.

Intercepting Responses

Response interceptors are similar to request interceptors, except that they allow you to intercept network requests and modify the corresponding responses before they are returned to the calling code. With response interceptors, you can modify the response headers, the response body, or both.

Here is the syntax of how you would implement it:

js
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
const response = await originalFetch(...args);
// Do something with the response object
return response;
};

In the response interceptor, we first call the original fetch method with the given arguments to get the response object. We can then perform any necessary transformations on the response object or log information about it before returning the response to the calling code.

Wrap up

Fetch API Interceptors can be useful in various use cases, such as modifying request headers, adding authentication tokens, or caching responses. By intercepting responses, developers can add or remove headers, modify the response body, or redirect the user to a different URL.

If you want to learn more about Fetch API, we have written lots of guides on it that you can find here.