Skip to content

Repository files navigation

@hsblabs/fetch-interceptor

Language: English | 日本語 | 简体中文 | 한국어

@hsblabs/fetch-interceptor is a lightweight TypeScript library for transparently intercepting browser fetch and XMLHttpRequest traffic.

Its key feature is that intercepted requests and responses are normalized to the standard Web API Request and Response objects. That lets you inspect and process XHR traffic without dealing with XHR-specific lifecycle complexity.

Features

  • Unified around standard APIs Both fetch and XHR traffic can be handled through Request and Response.
  • Fully type-safe The API is predictable and comfortable to use in TypeScript.
  • Safe lifecycle control A factory-based API lets you start interception when needed and restore native browser APIs cleanly.
  • Zero dependencies The library stays small and easy to embed.
  • Built for browser environments The API is intentionally simple for frontend integrations.

Installation

npm install @hsblabs/fetch-interceptor
# or
yarn add @hsblabs/fetch-interceptor
# or
pnpm add @hsblabs/fetch-interceptor
# or
bun add @hsblabs/fetch-interceptor

Development

pnpm test
pnpm test:e2e:node
pnpm test:e2e:browser

Before running browser E2E tests for the first time, install Playwright Chromium with pnpm test:e2e:install.

Usage

The library is designed to stay small at the call site. The example below intercepts only a specific API route and extracts JSON from the response.

import{createFetchInterceptor}from"@hsblabs/fetch-interceptor";constinterceptor=createFetchInterceptor({matcher: (request)=>{consturl=newURL(request.url);return(url.pathname.includes("/api/target-data")&&request.method==="GET");},onIntercept: async(request,response)=>{try{constdata=awaitresponse.json();console.log("Intercepted data:",data);// For example, forward data from a Chrome extension's main world// to an isolated world:// window.postMessage({ type: "INTERCEPTED_DATA", payload: data }, "*");}catch(error){console.error("Failed to parse intercepted response:",error);}},onError: (request,error)=>{console.error("Intercepted request failed:",request.url,error.transport,error.reason,error.cause,);},});interceptor.start();// ...do work...// interceptor.stop();

If matching, response normalization, or a consumer callback fails, the library reports the failure with console.error and preserves the original network result. Only an underlying fetch/XHR failure is passed to onError. An XHR load with status 0 is represented by Response.error(), the only standard Response value with status 0; its body and headers are therefore unavailable.

API Reference

createFetchInterceptor(options: FetchInterceptorOptions): FetchInterceptor

Creates an interceptor instance used to start and stop traffic interception.

FetchInterceptorOptions

PropertyTypeDescription
matcher((request: Request) => boolean)?Predicate that decides whether a request should be intercepted. When omitted, all traffic is intercepted. Exceptions are reported and treated as a non-match.
onIntercept(request: Request, response: Response) => void | Promise<void>Callback invoked when a matching request completes successfully. response is an independent clone for fetch, or an equivalent standard Response for XHR. Exceptions and rejected promises are reported without changing the original request outcome.
onError(request: Request, error: FetchInterceptorError) => void | Promise<void>Callback invoked only when the underlying transport fails before producing a response. Fetch can report error or abort; XHR can also report timeout. cause contains the raw fetch rejection or XHR terminal event.

FetchInterceptor

MethodDescription
start()Overrides fetch and XMLHttpRequest to begin interception. Calling it more than once is safe. If installation fails, completed patches are rolled back and the interceptor remains stopped.
stop()Attempts to restore every original browser API. If any restoration fails, it throws and keeps the failed work retriable through another stop() call without stacking adapters.

Use Cases

  • Data extraction in browser extensions Capture underlying REST or GraphQL responses directly from an SPA.
  • Debugging and logging Observe requests and responses for a specific API surface.
  • Test instrumentation Watch network activity and trigger test flow based on real responses.

Why This Library

Cross-cutting browser traffic tooling gets messy when fetch and XHR need separate handling. @hsblabs/fetch-interceptor removes that split so you can focus on monitoring, extraction, debugging, and automation with a single Request / Response mental model.

Contributing

Contributions are welcome.

See CONTRIBUTING.md for the contribution workflow and docs/label-policy.md for the issue label policy.

License

MIT

About

Intercept browser fetch and XMLHttpRequest traffic through standard Request and Response APIs.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages