Skip to content

createHttpInterceptor

function createHttpInterceptor(): HttpInterceptor;

Defined in: intercept-http.ts:232

Create an HTTP interceptor that patches fetch and XMLHttpRequest to capture requests/responses based on configurable rules. Each transport is patched only if the runtime has it: on a server (no XMLHttpRequest) only fetch is patched, and restore() puts back exactly what was replaced.

HttpInterceptor

An HttpInterceptor with addRule, clearAll, and restore methods.

const interceptor = createHttpInterceptor();
const handle = interceptor.addRule({
path: "/api/users",
onIntercept: (e) => console.log(e.status, e.response.body),
});
// With custom matching
interceptor.addRule({
match: (url) => url.includes("/api/") && !url.includes("/health"),
method: "POST",
onIntercept: (e) => analytics.track("api_call", e),
});
// Listen via EventTarget
handle.events.addEventListener("intercept", (e) => {
console.log((e as CustomEvent<InterceptEvent>).detail);
});
// Cleanup
handle.stop(); // remove one rule
interceptor.clearAll(); // remove all rules
interceptor.restore(); // remove all rules + restore original fetch/XHR