How do I intercept and monitor XHR requests in a React application using Playwright?


Intercepting XHR Requests

To intercept XHR requests in your React application using @playwright/test, use the browserContext.route() method. This method allows you to intercept and modify network requests made by any page created through the context. Pass in a URL pattern to match against the request URL, and provide a handler function that will be called whenever a matching request is made.

import { test, expect } from '@playwright/test';

test('intercept XHR requests', async ({ context }) => {
  // Intercept XHR requests
  context.route('**/*', (route, request) => {
    console.log('Request URL:', request.url());

  const page = await context.newPage();
  await page.goto('https://ray.run/');

Waiting for Page Hydration or Specific XHR Request

To wait for the page to be completely hydrated or for a specific XHR request, use Playwright's auto-waiting feature. This feature performs various checks on elements before making actions to ensure that they behave as expected.

For example, when using page.click(), Playwright will ensure that the element is attached to the DOM, visible, stable (not animating), receives events (not obscured by other elements), and enabled.

await page.click('#some-element');

You can also use page.waitForLoadState() to wait until the page reaches a particular state before continuing with your script. This method takes an optional parameter that specifies which load state to wait for ('load', 'domcontentloaded', or 'networkidle'). By default, it waits for 'load'.

await page.waitForLoadState('networkidle');

By combining the browserContext.route() method, auto-waiting feature, and various event listeners on both the context and individual pages, you can effectively capture all XHR requests from a React application and wait for either complete hydration or specific XHR requests.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.