How to Reduce Browser Automation Traffic with Request Interception
TL;DR
Use Playwright request interception on an authorized app to block a verified optional resource.
Register the route before navigation and match the smallest stable scope, such as one exact asset URL.
Preserve scripts, API requests, essential styles and any asset the intended feature requires.
Compare the same application acceptance assertion before and after routing, then check actual provider usage separately.
Routing can affect caching, and service workers change which requests a route can observe.
Remove the route and listeners after the run, and stop the managed browser if your job owns it.
When does Playwright request interception reduce browser traffic?
Playwright request interception can reduce traffic when a browser aborts requests for assets that an authorized task does not need. Good candidates are decorative images or redundant resources in your own application. Start with one path and prove that the task still reaches its accepted result. Nstdata Cloud Browser.
A background image can be optional in a data-focused confirmation workflow and essential in a visual QA case. Large requests can also serve multiple purposes. Before blocking a category, check whether a resource supports accessibility, layout, application initialization, validation, or the artifact you intend to keep. Treat dependencies as product behavior and verify them on the page you operate.
The example uses a staging catalog that loads a single decorative SVG. The expected business signal is a Catalog ready heading. The baseline must deliver the SVG. The treatment must abort that exact image request. Both runs must still report the expected heading.
Which resources should you leave alone?
Leave resources alone when their role is uncertain or when they affect the business task. Use an exact route first. Broader filters require a larger regression sample and clear accountability for what changed.
Can the intended content still render and be read?
Application script or module
Preserve
Does it initialize the controls or data the job uses?
API call for result rows
Preserve
Can the accepted result exist without its response?
Stylesheet or font
Preserve for visual QA
Would blocking it change layout or text measurement?
Embedded video
Depends on the job
Is playback part of the acceptance condition?
Sign-in or security requests
Preserve
Does the app require them for authorized access or integrity?
If you must reduce image bytes broadly, investigate the role of each image group and the browser task first. An exact route gives you a small, well-defined experiment. Always continue requests outside that scope. Playwright supports URL matchers and different interception actions. Playwright network guide.
How do you compare a baseline and one route?
Run the same page assertion twice and compare the observed delivery for a single known asset. Use Node.js 22.12 or later and install playwright-core@1.65.1. For the local run install Chromium with npx playwright-core install chromium. For managed routing, deploy the approved test page where the remote browser can reach it.
Step 1. Start a reproducible target
Save fixture.mjs and run node fixture.mjs. The test page is at /catalog and the optional resource is /assets/decorative.svg. Use the exact path when adapting the test to an owned staging application. The fixture has no external dependencies.
Save the shared connection modules below. A local run uses an isolated Chromium. For a managed run, launch in Cloud Browser → Playground, then set NSTDATA_API_KEY, NSTDATA_SESSION_ID and any applicable NSTDATA_TEAM_ID. Use an approved staging endpoint. This path requires your own ready session and workspace credential. The routing and acceptance logic were exercised locally. See attaching Playwright with CDP.
const root ='https://api.nstdata.io/api/v1/cloud-browser';exportasyncfunctionapi(method, path, body){const key = process.env.NSTDATA_API_KEY;if(!key)thrownewError('Set NSTDATA_API_KEY');const headers ={'x-api-key': key };if(process.env.NSTDATA_TEAM_ID) headers['x-team-id']= process.env.NSTDATA_TEAM_ID;if(body) headers['content-type']='application/json';let response;try{ response =awaitfetch(root + path,{ method, headers,redirect:'error',body: body ?JSON.stringify(body):undefined,signal:AbortSignal.timeout(20_000),});}catch{throwObject.assign(newError('API transport failed; reconcile the original operation'),{retryable:true});}const retryable = response.status===429|| response.status>=500;let result;try{ result =await response.json();}catch{throwObject.assign(newError('Invalid API JSON'),{ retryable });}if(!response.ok|| result.err===true|| result.success===false){throwObject.assign(newError(`Cloud Browser API HTTP ${response.status}`),{ retryable });}if(!result.data)thrownewError('Missing API data');return result.data;}exportasyncfunctionconnection(id){if(!id)thrownewError('Set NSTDATA_SESSION_ID');const path =`/sessions/${encodeURIComponent(id)}`;const session =awaitapi('GET', path);if(session.state!=='ready')thrownewError(`Session is ${session.state}, not ready`);const c =awaitapi('POST', path +'/automation-credentials');if(c.sessionId!== id ||!c.headerName||!c.accessToken||!(Date.parse(c.expiresAt)>Date.now())||newURL(c.cdpUrl).protocol!=='wss:'){thrownewError('Invalid or expired CDP credentials');}return{endpoint: c.cdpUrl,headers:{[c.headerName]: c.headerName.toLowerCase()==='authorization'?`Bearer ${c.accessToken}`: c.accessToken},};}exportasyncfunctionendpoint(){// An isolated local CDP endpoint can test the client without managed credentials.if(process.env.LOCAL_CDP_URL){const url =newURL(process.env.LOCAL_CDP_URL);if(!['127.0.0.1','localhost','[::1]'].includes(url.hostname)){thrownewError('LOCAL_CDP_URL must use loopback');}return{endpoint: url.href,headers:{}};}returnconnection(process.env.NSTDATA_SESSION_ID);}
Save traffic.mjs and run TARGET_URL=http://127.0.0.1:4173/catalog node traffic.mjs. The baseline goes through without a route. The treatment applies one exact URL match before navigation. The route callback checks the resource type before aborting. The URL matcher handles a URL object from the route API and a string from request observations.
Expected fixture output includes baseline.delivered: 1, blocked: 1, delivered: 0 and accepted: true. A completed request is a browser event, not a provider charge record. This example checks delivery and content with a small fixture. Build a stronger test predicate for pages with a skeleton that can appear before the final rows.
Step 4. Remove the route and end the browser
The script unregisters the route by the same matcher and handler, removes its own event listeners, and closes the page. If the job owns the managed browser, stop it and wait for termination. Store the original state, the route rules used, and the business result in the job record. See Cloud Browser session management.
[Screenshot: Baseline and routed diagnostic run for a controlled catalog fixture, both showing the expected readiness marker.]
Why can request counts and measured proxy usage disagree?
Request counters describe browser events, while provider usage records reflect service-measured traffic. A request observed by Playwright might be aborted, cached, redirected or delivered. That makes counts useful for local diagnosis and incomplete as a cost calculation. Reconcile the run against provider usage under the same account and time window.
Route installation can disable HTTP cache. A baseline with browser caching and a routed run with disabled caching can produce an asymmetric comparison. For a stronger benchmark, compare separate fresh sessions with the same cache conditions, configuration and fixtures. If you need matched routing overhead, compare an allow-through route against a blocking route. Playwright Page.route reference.
Service workers can intercept traffic before your page handler sees it. For a controlled test self-contained in a new context, consider what a service-worker policy changes. Blocking a service worker alters app behavior and needs its own approval from the test owner and acceptance checks. A first request in a popup can also call for context-level routing. Limit that routing to a context you own. Playwright BrowserContext.route reference.
What can go wrong after a narrow route is added?
A route can fail because the URL matcher is too broad, the asset is needed, the route was attached too late, or the browser served the resource elsewhere. Observe the exact failed condition and add one diagnostic per hypothesis.
If no rule triggers, check the actual origin, path and whether the application uses a service worker. Inspect the network view for how the request was handled.
If the route triggers and the page stalls, inspect required responses and the first user-visible checkpoint. Roll back the rule while investigating.
If usage rises, compare cache behavior, redirect counts, and job retries. Confirm session shutdown before comparing resource use.
If the test affects unrelated tabs, scope the route to the page or to a dedicated context and remove it after the task.
Use accepted output as the guardrail. A test that saves transfer but drops results creates rework and can increase total usage. Review live console and network diagnosis to confirm the first failing request or assertion.
How do you tell whether a rule is safe to keep?
Keep a route only after a baseline and a representative routed run both satisfy the app's acceptance contract. In the fixture, a missing Catalog ready heading causes the worker to fail regardless of the count. In an app with pagination, verify the expected page title and record IDs on the first and last cases. If a page has responsive behavior, test both sizes where you know it serves different assets.
Record the source URL pattern, asset type, timing, output count and service usage observation. Give each rule a clear owner and rollback condition. Should a deployment reuse the same asset URL for a functional component, a test for that component must detect the missing dependency before the change reaches users.
How does Nstdata Cloud Browser support this experiment?
Nstdata Cloud Browser provides managed cloud browsers for browser automation and AI agents. Playwright can attach over CDP and apply a bounded route in the chosen managed page. The built-in proxy carries permitted target traffic under the selected settings. Session history provides separate usage observations when available. Your application owns the routing rule and its acceptance and rollback conditions. Browser Automation documentation.
Managed routing. Compare under a consistent supported proxy selection without adding a second gateway to your worker.
CDP execution. Apply the same page-specific rule after attachment and keep its lifetime tied to the test.
Live troubleshooting. Check the selected page's supported diagnostics and review service-measured usage after your run.
Roll out only after a representative sample keeps the same acceptance rate, demonstrates reproducible usage savings, and passes targeted tests for pages that load differently. Retain the exact route scope and owner for rollback. Check the effect of a failure and verify cleanup before increasing concurrency. For production debugging, retain sanitized network observations and a small accepted-output sample.