Control the World Around the Page

A Playwright page never lives alone: it requests APIs, follows redirects, loads images, reads authentication state, and responds to the environment in which its browser context runs. This chapter focuses on the network and environment boundary around that page. The reader’s task is to choose deliberately among observing real traffic, fully mocking a response, modifying a real response, or replaying recorded traffic—and to understand what each choice makes reliable and what it can no longer prove.

The request path is a test boundary

Playwright can monitor and modify HTTP and HTTPS traffic made by a page, including fetch and XHR requests. A route can be attached to a page when the rule belongs to one page, or to a browser context when the same rule should apply to pages in that context. This scope is significant. A context-level route can establish a condition for a whole scenario, while a page-level route can isolate one interaction without silently changing every page that the test creates.

The route sits on the browser side of the boundary. It sees the traffic the page is attempting to make and can decide how that traffic reaches the outside world. It does not replace the application’s server, rewrite the server’s database, or prove that a real deployment would return the same result. If a test fulfills a route with a custom response, the browser receives that response through Playwright’s controlled path; the production API may never have been called.

A useful example is an account page that loads a list of projects. The page’s rendering and empty-state behavior may be the subject of the test, while the live project service is slow, unavailable, or difficult to seed with a precise response. A context route can return a known project list, an empty list, or an error-shaped response. The page still navigates and renders through its normal client code. The test isolates the UI question from the service’s current data, but it must not describe the result as proof that the service produced that response.

The route can also allow the real request to proceed. Playwright can observe request and response events, so a test or diagnostic run can record which method and URL were used and what status came back. That is useful when the question is integration behavior: did the page send the request, did the service answer, and did the UI respond to the returned status? Observing real traffic preserves more of the deployed relationship, but it also inherits the service’s availability, data, authentication, latency, and rate limits.