#Intercepting requests with page.route
AddedEvery request a page makes (the HTML, scripts, images, fetch calls to your API) passes through Playwright on its way out, and page.route(pattern, handler) lets you stop the matching ones and decide what happens. The handler gets a route and must do exactly one of:
route.fulfill({...}): answer it yourself; the request never reaches the server.json,body,status,headersandcontentTypeshape the fake response.route.continue({...}): let it go to the server, optionally changed (url,method,headers,postData).route.fetch()thenroute.fulfill({ response, … }): send it to the server, get the real response, then change it before the page sees it.route.abort(): fail it, as if the network were down.route.fallback(): pass it on to the next matching handler (handlers registered later are tried first).
The mental model: a mailroom between the page and the internet. Every outgoing letter goes through it. For the addresses you've told it about, the mailroom can write the reply itself, edit the letter or the reply, or throw the letter away. Everything else goes out untouched.
Here are the main moves against the shop's product list, GET /practice/api/products.json:
import { test, expect, type Page } from "@playwright/test";
async function signIn(page: Page) {
await page.goto("/practice/");
await page.getByLabel("Username").fill("rohit");
await page.getByLabel("Password").fill("playwright");
await page.getByRole("button", { name: "Sign in" }).click();
}
test("fulfil: answer with fake data", async ({ page }) => {
await page.route("**/practice/api/products.json", (route) =>
route.fulfill({ json: [
{ id: "t-1", name: "Test Teapot", category: "Kitchen", price: 12, stock: 3 },
{ id: "t-2", name: "Test Toaster", category: "Kitchen", price: 30, stock: 0 },
] }),
);
await signIn(page);
await expect(page.getByRole("listitem")).toHaveText([/Test Teapot/, /Test Toaster/]);
await expect(page.getByTestId("product-t-2").getByRole("button", { name: "Add to cart" })).toBeDisabled();
});
test("modify: change the real response", async ({ page }) => {
await page.route("**/practice/api/products.json", async (route) => {
const response = await route.fetch();
const products = await response.json();
for (const p of products) p.price = Math.round(p.price * 0.5 * 100) / 100; // a half-price sale
await route.fulfill({ response, json: products });
});
await signIn(page);
await expect(page.getByTestId("product-ms-01")).toContainText("$14.75");
await expect(page.getByRole("listitem")).toHaveCount(8);
});
test("abort: the request fails", async ({ page }) => {
await page.route("**/practice/api/products.json", (route) => route.abort());
await signIn(page);
await expect(page.getByRole("alert")).toHaveText("Couldn’t load products. Try again later.");
});Running 3 tests using 1 worker
✓ 1 [chromium] › tests/route.spec.ts:10:1 › fulfil: answer with fake data (1.6s)
✓ 2 [chromium] › tests/route.spec.ts:23:1 › modify: change the real response (1.5s)
✓ 3 [chromium] › tests/route.spec.ts:36:1 › abort: the request fails (1.5s)
3 passed (5.3s)- Each test registers its route before signing in, because signing in lands on the shop page, which immediately requests the products. A route added after the request has gone out is too late.
- Fulfil: the handler answers with two made-up products; the request never reaches the server.
jsonserialises the value and setsContent-Type: application/json. The page renders exactly the fake list, and the sold-out toaster's button is disabled, a state you can now test with any data you like. - Modify:
route.fetch()sends the request to the real server and returns the real response. The handler halves every price and fulfils withresponse(keeping its status and headers) plus the changedjson. The mouse now shows $14.75 instead of $29.50, and all eight real products are still there. - Abort:
route.abort()fails the request like a dropped connection. The shop'sfetchrejects, itscatchruns, and it shows "Couldn’t load products. Try again later." in arole="alert"element, which is what the test checks. - Routes belong to the test's page (or context, with
context.route) and disappear when the test ends, so nothing leaks into other tests.
The first argument is a glob (or a RegExp, or a function of the URL). The glob must match the whole URL, not part of it, which is why patterns start with **/. The rules, from the docs:
| Pattern part | Matches |
|---|---|
* | any characters except / |
** | any characters including / |
{a,b} | either a or b |
? | only a literal ? (since 1.52; before, it meant "any one character") |
\ | escapes a special character |
Since 1.52, ? and [] have no special meaning in globs; use a RegExp if you need them. This test shows * stopping at /:
import { test, expect } from "@playwright/test";
test("which requests does **/api/*.json catch?", async ({ page }) => {
const caught: string[] = [];
await page.route("**/api/*.json", async (route) => {
caught.push(new URL(route.request().url()).pathname);
await route.continue();
});
await page.goto("/practice/");
await page.localStorage.setItem("shop-user", JSON.stringify({ username: "rohit", name: "Rohit" }));
await page.localStorage.setItem("shop-cart", JSON.stringify([{ id: "ms-01", name: "Wireless Mouse", price: 29.5, qty: 1 }]));
await page.goto("/practice/shop");
await expect(page.getByRole("listitem")).toHaveCount(8);
await page.goto("/practice/checkout");
await page.getByLabel("Promo code").fill("SAVE10");
await page.getByRole("button", { name: "Apply" }).click();
await expect(page.getByText("SAVE10 applied: 10% off.")).toBeVisible();
console.log(caught);
});Running 1 test using 1 worker
[ '/practice/api/products.json' ]
✓ 1 [chromium] › tests/globs.spec.ts:3:1 › which requests does **/api/*.json catch? (1.2s)
1 passed (1.9s)- The handler records each URL it catches, then lets it through unchanged with
route.continue(), so the page works normally. - The test seeds a signed-in user and a cart with
page.localStorage(Chapter 8) so it can go straight to the shop and the checkout, where it applies the code SAVE10. - The page made two API calls:
/practice/api/products.jsonand/practice/api/promos/SAVE10.json. Only the first was caught. In**/api/*.json, the*can't cross the/inpromos/SAVE10, so the promo request didn't match and went straight to the server. **/api/**/*.jsonor**/api/**would catch both. Getting a glob slightly wrong is the commonest reason a mock "does nothing": the request simply doesn't match, and the real server answers. When a mock seems ignored, log what the page requests (see "Watching what the page sends").