Control Network Traffic in Playwright Tests
On This Page What interception means in PlaywrightWh
- What interception means in Playwright
- Why intercept HTTP in tests?
- How Playwright treat interception internally
- Playwright APIs for interception
- Intercepting and alter HTTP requests
- Mocking API responses with route interception
- Blocking and abort meshwork requests in Playwright
- URL patterns and conditional interception
- Handling multiple and concurrent intercept
- Validating request and response datum
- Intercepting in Single Page Applications
- Common mistakes with interception
- Performance and constancy consideration
- Debugging failed or miss intercepts
- Best practices for HTTP interception using Playwright
- Limitations of Playwright & # 8217; s interception
- How Requestly Helps with HTTP Interception in Playwright
Intercepting HTTP Requests with Playwright
Modern web apps look heavily on XHR/fetch calls, GraphQL, and, which means UI tests are only as stable as the meshwork they rely on. Playwright & # 8217; s built-in request interception countenance you decouple test from flaky or slow backends by bemock, modifying, or blocking traffic directly in the browser automation layer.
Intercepting HTTP requests in afford you fine-grained control over how your application talks to backend service, making tests quicker, more reliable, and easier to debug.
Overview
Best practices for HTTP interception using Playwright
- Intercept only specific routes instead of broad wildcards
- Register page.route () before trip the network request
- Use route.fulfill () for mocks and route.continue () for pass-through modification
- Keep mocked responses aligned with real API structure and status codes
- Store mock payload in extraneous JSON fixtures, not inline
- Use conditional logic inside a single itinerary for multiple scenarios
- Assert request headers and payloads, not just responses
- Scope or remove path after each test to forefend leakage
- Avoid mocking critical end-to-end backend stream
- Do not use interception as a synchronising or wait mechanics
This article walks through how Playwright & # 8217; s mesh interception works, the key APIs, common patterns, and good practices with hardheaded, test-oriented examples.
What interception mean in Playwright
In Playwright, intercepting HTTP requests means pausing outbound postulation that check a pattern and deciding programmatically whether to continue, modify, action, or abort them. This interception happens before the browser really sends the request over the network or processes the answer, giving tests complete control over both direction of traffic.
Why intercept HTTP in tests?
Teams intercept asking in Playwright tests chiefly to:
- Mockunstable or third-party APIs so examination are deterministic and do not depend on external uptime or rate limits.
- Speed upsuites by skipping dim resources (face, analytics, ads) and reducing server round-trips.
- Simulate edge caseslike server mistake, timeouts, partial data, or different user roles without needing specific backend fixtures.
Read More:
How Playwright handles interception internally
Playwright sits between your test code and the browser, using a lasting WebSocket connection to control browser engine like Chromium, Firefox, and WebKit.
When a matching asking occurs, the browser notifies Playwright, which exposes it as a Route and Request object for your test to cover synchronously or asynchronously. If you do nothing in that handler, the request stalls; you must explicitly call route.continue (), route.fulfill (), or route.abort () to restart the flow.
Playwright APIs for interception
The nucleus interception-related APIs in the JavaScript/TypeScript test runner are:
- page.route (url, handler)& # 8211; register a path coach to intercept gibe request.
- page.unroute (url, handler?)& # 8211; remove a specific handler or all handler for a matcher.
- browserContext.route (url, handler)& # 8211; utilise interception across every page in the context, useful for global mocks.
- route.request ()& # 8211; inspect the intercepted Request (URL, method, headers, postData, etc.).
- route.continue (options?)& # 8211; let the request proceed, optionally modifying it.
- route.fulfill (selection)& # 8211; short-circuit and provide a complete mocked response.
- route.abort (errorCode?)& # 8211; scrub the request with an optional erroneousness understanding (e.g., miscarry, blockedbyclient).
Intercepting and modifying HTTP requests
To, use page.route (or context.route) with a glob, regex, or predicate:
await page.route (& # 8216; * * /signup/partners & # 8217;, async (itinerary, request) = & gt; {const body = request.postDataJSON ();
const modifiedBody = {
& # 8230; body,
agentId: & # 8216; test-agent & # 8217;,
};
await route.continue ({
postData: JSON.stringify (modifiedBody),
});
});
This pattern is useful when:
- Sanitizing or normalizing payloads (e.g., random IDs, timestamps) so assertions stay stable.
- Injecting lineament flags, header, or auth item without altering application codification.
Running request-interception tests locally oftentimes hides environment-specific issues like proxy behavior, browser quirks, or header sport. With, Playwright interception logic can be validated on real browsers and OS combinations at scale, ensuring asking limiting behave consistently across production-like environments.
For advanced request rewriting, header injectant, and payload use beyond trial code,Requestlycomplement Playwright by enabling alive HTTP nullification without changing application or quiz logic-making complex meshwork scenarios easier to simulate and debug in CI pipelines
Mocking API responses with route interception
is the most mutual use of interception: you bug a request and respond with synthetic data via route.fulfill.
await page.route (& # 8216; * * /api/v1/fruits & # 8217;, async (itinerary) = & gt; {const json = [{id: 21, name: & # 8216; Strawberry & # 8217;}];
await route.fulfill ({json});
});Key capability when mocking:
- Return JSON, schoolbook, or binary body with usage status code and headers.
- Wrap an survive real response using page.request.fetch (route.request ()) and then mutate body or headers before fulfilling.
- Simulate error states like 500 or 503 to corroborate UI erroneousness handling.
Read More:
Blocking and abort network requests in Playwright
For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
Use route.abort () when you want to cancel requests entirely, such as:
- Blocking analytics, tracking pel, and third-party ads to reduce racket and speed up tests.
- Preventing large asset downloads (images, fonts) during headless runs for performance.
Example:
await page.route (& # 8216; * * / * & # 8217;, (route) = & gt; {const url = route.request () .url ();
if (url.includes (& # 8216; google-analytics & # 8217;) || url.endsWith (& # 8216; .png & # 8217;)) {
return route.abort ();
}
return route.continue ();
});Being too broad (& # 8216; * * / * & # 8217;) can accidentally hinder navigations, so route conditions must be carefully tuned.
URL patterns and conditional interception
Playwright back several ways to target requests:
- Glob patterns: & # 8216; * * /api/ * * & # 8217;, & # 8216; * * / * .json & # 8217;.
- Regular expressions: //graphql? operation=GetUser/.
- Predicate part: (route) = & gt; route.request () .postData ()? .includes (& # 8216; priority=high & # 8217;).
Predicate-based routing is ideal when matching on:
- HTTP method ().
- Query parameters, head, or JSON body shapes.
- Specific microservice domains in a micro-frontend architecture.
Read More:
Handling multiple and concurrent intercept
Complex apps may discharge several postulation in parallel, and route manager must remain deterministic and non-blocking. Good pattern include:
- Keeping road handlers short and async-safe, forfend heavy computation.
- Composing separate handler per URL pattern instead of one huge & # 8220; catch-all & # 8221; that branch on every condition.
- Using page.waitForResponse with a predicate when you need to wait on various coincidental API calls triggered by a single user action.
const [resUser, resOrders] = await Promise.all ([page.waitForResponse (r = & gt; r.url () .includes (& # 8216; /api/user & # 8217;) & amp; & amp; r.status () === 200),
page.waitForResponse (r = & gt; r.url () .includes (& # 8216; /api/orders & # 8217;) & amp; & amp; r.status () === 200),
page.click (& # 8216; button.load-dashboard & # 8217;),
]);
Validating request and reply data
Interception also enables making assertions at the meshwork layer, not exactly the UI. Common patterns:
- Assert lading contents in route handlers, then name route.continue () or route.fulfill () only if they match anticipation.
- Capture values from response (IDs, tokens, counts) and give them into later test steps.
Example of validating a POST body:
await page.route (& # 8216; * * /api/checkout & # 8217;, async (route) = & gt; {const payload = route.request () .postDataJSON ();
expect (payload.items) .toHaveLength (3);
expect (payload.total) .toBeGreaterThan (0);
await route.continue ();
});Validating request and response datum locally does not always reflect real-world traffic shape across browsers and operating system. With, Playwright tests that assert payloads, headers, and answer data can be action on existent browsers at scale, facilitate get environment-specific inconsistencies and ensure network-level substantiation remain reliable in CI pipelines.
Intercepting in Single Page Applications
Single Page Applications (SPAs) often bank on client-side routing and background fetch, so interception must start before the SPA triggers requests. Recommended shape:
- Register page.route or context.route before page.gotoso initial data-loading request are moderate.
- Combine interception with SPA-specific delay, likepage.waitForResponse and locator.waitFor, to avoid racing against async state updates.
In frameworks like Next.js, server-side requests usually can not be intercepted from the browser context; instead, intercept the client-side calls or mock at the HTTP layer if needed.
Common mistakes with interception
Typical pitfalls when working with Playwright routes include:
- Registering routesafter page.goto, causing other request to skid through unmocked.
- Using overly all-inclusive patterns like& # 8216; * * / * & # 8217;without conditional chit, blocking critical assets and navigations.
- Forgetting to ringroute.continue, route.fulfill, or route.abort, which leave requests hanging and tests timing out.
- Conflicts cause by multiplepage.routehandler that match the like URL; only the terminal matching handler is apply.
Performance and stability consideration
Playwright interception runs on every matching request, so ineffective handlers can degrade examination performance. To keep rooms fast and stable:
- Prefer browserContext.routefor global, reusable mocks rather of re-registering routes on every page.
- Avoid expensive computation or I/O in path handler; pre-compute fixtures and keep handlers focused on routing logic.
- Be mindful that mocking too much can diverge from real-world behavior, so keep a small subset of “ full-stack ” tests against real backends.
Read More:
Debugging fail or missed intercept
When interception execute not behave as expected, rivet on visibility and timing. Helpful proficiency:
- Log the URL, method, and headers inside route handlers to verify what is really being correspond.
- Use Playwright trace or web views to corroborate whether a petition was fulfilled or actually send to the server.
- Check for service proletarian that may wiretap traffic before Playwright and disable them with {serviceWorkers: & # 8216; block & # 8217;} on the circumstance when necessary.
const circumstance = await browser.newContext ({serviceWorkers: & # 8216; cube & # 8217;});Read More:
Better practices for HTTP interception expend Playwright
To keep your interception scheme maintainable and test-friendly:
- Define partake helper utilities for common mock (auth, characteristic iris, base data) and reuse them across tests.
- Scope mock narrowly using exact URL patterns, methods, and predicates to avoid accidental interference.
- Always add at least one assertion that proves your mock was actually used (e.g., UI text from bemock data, or a petition enumeration check).
- Remove or reset routes between tests using page.unroute or new circumstance to forefend cross-test bleed-through.
Read More:
Limitations of Playwright & # 8217; s interception
Despite its power, there are practical limitations:
- Server-to-server or backend-only requests are not seeable to Playwright; it but sees traffic originate from the browser context.
- Some service workers and caching behavior can mask or bypass interception unless explicitly disabled.
- Interception logic lives in test code, so overly complex mock can make tests harder to understand and maintain than tantamount backend-level test doubles.
Intercepting HTTP requests without breaking tests?
How Requestly Helps with HTTP Interception in Playwright
Playwright provides native APIs like page.route () for intercepting network Call, but managing those intercepts at scale becomes hard as test suites grow. Requestly simplifies HTTP interception by moving network control outside test code while nevertheless working seamlessly with Playwright.
- Intercept requests without indite routing logic in exam:Instead of embedding conditional page.route () manager in every test, Requestly expend rule-based interception. Requests can be mocked, redirect, modified, or stymie without changing Playwright test files, continue tests pore on UI behavior.
- Mock APIs and third-party services reliably:Requestly permit static and dynamic mock response for backend APIs, payment gateways, analytics tools, or characteristic masthead services. This ensures tests are not regard by backend downtime or pace limits.
- Modify request and response payloads on the fly:Headers, query params, condition code, and reaction bodies can be change during runtime. This makes it easier to essay edge cases like authorization failures, malformed responses, or partial datum scenarios that are hard to reproduce use real APIs.
- Simulate network delay and failures:Requestly can inclose artificial hold or error responses to validate Playwright behavior under slow net, timeouts, or server failure, helping uncover race conditions and flakey delay.
- Reuse the same interception rules across environments:The like Requestly formula act in local runs, CI pipelines, and share team setups. This avoids duplicate of mock logic and trim inconsistencies between developer machines and automated builds.
- Improve debugging of flaky network-dependent tests:Centralized visibleness into intercepted requests and responses helps identify whether failure originate from frontend logic or unstable APIs, trim debugging time.
- Scale interception beyond simple test cases:As Playwright test coverage expands, maintaining interception logic inside tests becomes hard to contend. Requestly provides a scalable, maintainable layer for HTTP control without bloating test code.
For team using Playwright extensively for network-dependent flow,Requestlyacts as a dedicated HTTP interception bed that complement Playwright ’ s native capabilities while keeping test suites light and stable.
Conclusion
Network interception in Playwright transforms UI trial into precise, API-aware scenario where every asking and response is controlled. By employ route, continue, fulfill, and abort thoughtfully-with scoped patterns, clear validation, and skimpy handlers-fast, reliable, and expressive test suites can be built that rest stable as application and backends change.
On This Page
- What interception means in Playwright
- Why intercept HTTP in tests?
- How Playwright handles interception internally
- Playwright APIs for interception
- Intercepting and change HTTP asking
- Mocking API responses with route interception
- Blocking and aborting web requests in Playwright
- URL patterns and conditional interception
- Handling multiple and concurrent intercept
- Validating request and answer data
- Intercepting in Single Page Applications
- Common error with interception
- Performance and stability circumstance
- Debugging fail or missed intercept
- Best practice for HTTP interception using Playwright
- Limitations of Playwright & # 8217; s interception
- How Requestly Helps with HTTP Interception in Playwright
# Ask-and-Contributeabout this topic with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free