Introduction to Playwright Network Hooks

Many critical behaviours in web applications depend on network traffic rather than just DOM state. Playwright gives you rich APIs to observe, log and assert on requests and responses, which lets QA engineers catch integration issues that pure UI checks would miss.

Listening to Network Events in Playwright

You can subscribe to request and response events on the page or context objects. This is useful for debugging, logging and building targeted assertions around specific calls.

// network-hooks-intro.spec.ts
import { test, expect } from '@playwright/test';

test('logs API calls during dashboard load', async ({ page }) => {
  const requests: string[] = [];

  page.on('request', req => {
    if (req.url().includes('/api/')) {
      requests.push(`${req.method()} ${req.url()}`);
    }
  });

  await page.goto('https://demo.myshop.com/dashboard');

  expect(requests.length).toBeGreaterThan(0);
});
Note: Network event handlers run for every matching request, so keep their logic lightweight to avoid slowing tests.
Tip: Log only the method, URL and status code rather than full payloads unless you specifically need body content for debugging.
Warning: Avoid printing large request or response bodies in CI by default; this can make logs noisy and slow.

Once you understand what traffic your app generates, you can design more precise assertions and stubs around that behaviour.

Common Mistakes

Mistake 1 โ€” Ignoring network traffic entirely

This misses integration bugs.

โŒ Wrong: Only checking DOM changes without verifying that the right APIs were called.

โœ… Correct: Use network listeners or waits to confirm that critical endpoints are hit.

Mistake 2 โ€” Doing heavy processing in network callbacks

This can slow tests.

โŒ Wrong: Parsing and storing entire JSON bodies for every request.

โœ… Correct: Capture minimal information during the test and do deeper analysis only when needed.

🧠 Test Yourself

Why should UI tests pay attention to network traffic?