Testing & Verification

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
READ
2 min
Interactive Simulator

Browser Network Interception & HAR Replay

Trace how CDP/Service Worker interception captures a real fetch() and replays a recorded HAR stream.

App fetch()
CDP / SW Hook
HAR Archive
Step 1 / 3: 1. Browser Dispatches Real Request

App calls fetch('/api/v2/cart'); browser attaches cookies, origin headers, and aborts signals.

const res = await fetch('/api/v2/cart', { credentials: 'include' });
Internal State / Memory
layer
Browser Network Stack
url
/api/v2/cart
headersAttached
true
Browser Network Interception & HAR Replay

Under the Hood#

Browser-level interception hooks below the fetch() and XMLHttpRequest bindings, keeping header normalization, status handling, and stream decoding intact.

  1. 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 .har archive.
  2. Service Worker Interception: Tools like MSW register a Service Worker on self.onfetch, intercepting outgoing requests across tabs and returning synthetic Response objects with real ReadableStream bodies.
  3. HAR Replay Matching: A recorded .har file stores timestamped request/response pairs, headers, and base64 payloads so tests replay exact server responses offline.
TS
// 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 to XMLHttpRequest, sendBeacon, or Response.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 .har file 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

Network & Performance

Service Worker Lifecycle

Service Worker fetch interception handles real browser Request/Response objects in-process.