Deterministic Network Interception & HAR Replay
Live staging APIs flake tests on rate limits and drifting data, while stubbing window.fetch hides serialization and streaming bugs; intercepting at the browser network layer replays real HTTP frames deterministically.
About this page
Browser Network Interception & HAR Replay
Trace how CDP/Service Worker interception captures a real fetch() and replays a recorded HAR stream.
App calls fetch('/api/v2/cart'); browser attaches cookies, origin headers, and aborts signals.
const res = await fetch('/api/v2/cart', { credentials: 'include' });- layer
- Browser Network Stack
- url
- /api/v2/cart
- headersAttached
- true
Under the Hood#
Browser-level interception hooks below the fetch() and XMLHttpRequest bindings, keeping header normalization, status handling, and stream decoding intact.
- CDP / WebDriver BiDi Interception:
page.route()pauses the browser network stack before socket dispatch (Fetch.requestPaused), matching URL, method, and headers against handlers or an indexed.hararchive. - Service Worker Interception: Tools like MSW register a Service Worker on
self.onfetch, intercepting outgoing requests across tabs and returning syntheticResponseobjects with realReadableStreambodies. - HAR Replay Matching: A recorded
.harfile stores timestamped request/response pairs, headers, and base64 payloads so tests replay exact server responses offline.
// Replay recorded HTTP traffic including headers and status codes
await page.routeFromHAR('tests/fixtures/checkout.har', {
url: '**/api/v2/**',
update: false,
notFound: 'abort',
});Problem Genealogy#
- 2015 (
sinon.stub(window, 'fetch')): Fast unit mocks broke whenever code switched toXMLHttpRequest,sendBeacon, orResponse.body.getReader()streams. - 2018 (Record-and-Replay HTTP Proxies like PollyJS): Saved real wire payloads, but required managing external proxy ports and TLS certificates in CI.
- 2020 (MSW Service Workers & Playwright
routeFromHAR): Moved deterministic HTTP replay directly into the browser network pipeline with zero external proxy processes.
Production Pitfalls#
- Stale HAR Drift: Replaying a 6-month-old
.harfile hides breaking backend schema changes until production; pair HAR tests with schema contract validation. - Broken Streaming Simulation: Returning a single
JSON.stringify()string in a naive mock masks backpressure and incremental chunk-parsing bugs in SSE or AI-stream UIs.
Where this connects
Prerequisites
Service Worker Lifecycle
Service Worker fetch interception handles real browser Request/Response objects in-process.
Streams API and Backpressure Mechanics
Network-layer mocks must preserve ReadableStream chunking and backpressure for streaming responses.