API AUTOMATIONINTERMEDIATE

Network Interception & API Mocking with Playwright

Intercept, mock, and modify network requests to test edge cases, offline states, and slow backends deterministically.

iff Solution Academy July 5, 2026 11 min read Updated July 5, 2026
Playwright Mocking Network route()

Why Mock?

Real APIs are slow, flaky, and hard to force into edge states. Mocking gives you deterministic tests for error banners, empty states, rate limits, and offline modes.

Basic page.route()

ts
await page.route('**/api/users', (route) =>
  route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify([{ id: 1, name: 'Ada' }]),
  })
);

Modify Real Responses

ts
await page.route('**/api/users', async (route) => {
  const response = await route.fetch();
  const json = await response.json();
  json.push({ id: 999, name: 'Injected' });
  await route.fulfill({ response, json });
});

Abort & Simulate Errors

ts
await page.route('**/api/**', (route) => route.abort('failed'));
// Or return a specific error status
await page.route('**/api/orders', (route) => route.fulfill({ status: 500 }));

Recording with HAR

Record traffic once, then replay it for fast, deterministic runs:

ts
await page.routeFromHAR('fixtures/api.har', { update: false });

Get Playwright tutorials in your inbox

Weekly tips, real-world examples, and framework patterns – no spam, unsubscribe anytime.

Recommended Next Articles