Mock API Responses in Playwright

From the Playwright cheat sheet ยท Network Mocking & Interception ยท verified Jul 2026

Mock API Responses

Intercept API calls and return custom data without hitting the server

typescript
// Mock an API endpoint
await page.route('**/api/users', async (route) => {
  await route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify([{ id: 1, name: 'John' }]),
  });
});
await page.goto('/users');
await expect(page.getByText('John')).toBeVisible();
๐Ÿ’ก Use route.fulfill({ json }) as a shorthand โ€” Playwright sets content-type automatically
โšก route.fetch() lets you intercept the real response and modify it before returning
๐Ÿ“Œ Route patterns use glob syntax โ€” ** matches any path segment, * matches within a segment
๐ŸŸข Mock routes before page.goto() to ensure requests are intercepted from the start
mocknetworkrouteapi
Back to the full Playwright cheat sheet