Interceptors are code blocks that you can use to preprocess or post-process HTTP calls, helping with global error handling, authentication, logging, and more. In this article, you’ll learn how to intercept JavaScript Fetch API calls.
There are two types of events for which you may want to intercept HTTP calls, request and response events. The request interceptor should be executed before the actual HTTP request is sent, whereas the response interceptor should be executed before it reaches the application code that made the call.
Before diving into the code, we need to understand a few important factors. For one, the Fetch API doesn’t support interceptors natively. Additionally, extra packages are required to use the Fetch API in Node.js.
The JavaScript Fetch API
First, let’s cover some fundamentals of the Fetch API, for example, the syntax:
resource
defines the resource you want to fetch, which can be either a Request object or a URL. init
is an optional object that will contain any custom configuration you want to apply to this particular request.
The Fetch API is promise-based. Therefore, when you call the Fetch method, you’ll get a response promise back. Here, it is referred to as fetchResponsePromise
, as seen in the example above.
By default, Fetch uses the GET
method for API calls, as shown below:
Below is an example of a POST
request with Fetch:
The POST
call must have a body
. Take a look at the Fetch documentation for more details.
Implementing interceptors
There are two ways to add interceptors to our Fetch API calls; we can either use monkey patching or the fetch-intercept
library.
Monkey patching with Fetch
One way to create an interceptor for any JavaScript function or method is to monkey patch it. Monkey patching is an approach to override the original functionality with your version of the function.
Let’s take a step-by-step look at how you can create an interceptor for the Fetch API with monkey patching:
The code above overrides the original Fetch method with a custom implementation and calls the original Fetch method inside it. You’ll use this boilerplate code to create request and response interceptors.
Request interceptor
In the following example, we’ll create a simple request interceptor that changes the resource URL of an illustration:
This API call would fetch data from https://jsonplaceholder.typicode.com/todos/2
instead of https://jsonplaceholder.typicode.com/todos/1
, as shown by the ID 2
of the todo
.
Note: One of the most common use cases for request interceptors is to change the headers for authentication.
Response interceptor
The response interceptor would intercept the API response before it is delivered to the actual caller. Let’s take a look at the following code:
In the code above, we changed the JSON method to return some custom data instead of the original data. Check out the documentation to learn more about the properties that you can change.
Note: Responses are only allowed to be consumed once. Therefore, you need to clone the response each time you want to use it.
Handling errors
You can easily handle errors for requests by checking the values for response.ok
and response.status
. In the code snippet below, you can intercept 404
errors:
Node.js
You can use the same approach in Node.js. However, Node.js doesn’t support the Fetch API natively (though native support for the Fetch API will be available in future versions of Node.js). For now, you need to install the Node Fetch package, then monkey patch the fetch
method.
Using fetch-intercept library
If you’re not a fan of doing the dirty
work (pun intended), the fetch-intercept library allows you to register interceptors with a cleaner API. You can use npm or Yarn to install the library as follows:
Note: The fetch-intercept library only supports browsers and won’t work in Node.js. Also, it requires whatwg-fetch as dependency to work.
With the code below, we can implement the same request and response interceptors as in our monkey patching example:
The register
method allows you to register the interceptors for Fetch API calls. It takes an object with the request
, requestError
, response
, and responseError
callbacks. The register
method returns another method that can be used to unregister the interceptors.
The Fetch API doesn’t support interceptors natively. However, there are other libraries for making HTTP calls that support interceptors. Take a look at Axios, which provides this functionality out of the box.
Summary
In this article, we covered what JavaScript interceptors are, learning how to create interceptors both by monkey patching the Fetch API and using the fetch-intercept library.
Originally introduced by Angular, interceptors are helpful for a wide variety of use cases, like helping with global error handling, authentication, logging, and more. You can use the methods described in this article to add interceptors to your JavaScript applications, however, keep in mind the additional required dependencies for Node.js.
I hope you enjoyed this article, be sure to leave a comment if you have any questions. Happy coding!