Sandro Lain Personal Blog

A simple fetch() interceptor with VanillaJS

The introduction of the Fetch API brought a modern and comprehensive method of making HTTP calls to browsers.

In the development of more complex web applications, however, there is a need to have more control over the requests and their responses.

Some frameworks and libraries provide alternative or similar methods to fetch(), and with it some tools to intercept the requests before they are made or the responses before they are digested, allowing their manipulation to normalize them according to business needs (e.g. add authentication HTTP headers), or to perform predefined actions in some circumstances (e.g. toast notifications in case of error responses).

A Vanilla.js interceptor

Here below I report the ES6 class code of an interceptor, which proves to be very simple and tries to exploit the already rich native fetch API without distorting them, therefore it does not force to adopt proprietary formats when creating the request or reading the response.

An example of use

Here is an example of use, very simple in this case. By taking advantage of the ES modules and dividing the code over different files, you can develop a modern and simple method to make fetch() calls.

View Live Example

In my HTNA-tools repository on github you can find the original TypeScript version: Click here to go to the exact line.

Share this page