Deterministic Network Interception & HAR Replay
Mocking globalThis.fetch in JavaScript bypasses browser CORS, cookie jars, and ReadableStream decoding. Intercepting requests at the browser network layer via CDP page.route(), HAR replay, or a Service Worker exercises real HTTP serialization with zero staging-server flakiness.
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.
- When not to use Network Interception: Never mock or HAR-replay authentication redirects, CDN cache-control headers, or WebSocket upgrade handshakes in release-gate E2E suites; those require a real backend or staging environment.
Connections & Logical Next Steps
Service Worker fetch interception handles real browser Request/Response objects in-process.
Network-layer mocks must preserve ReadableStream chunking and backpressure for streaming responses.