This guide covers the setup for Playwright and Puppeteer, how to keep one session per logical task, and the first errors you are likely to meet when the endpoint, credentials, or DNS behaviour is wrong.
Configure the proxy before the browser starts
Both frameworks apply proxy settings at launch. Set the endpoint, username, and password through environment variables so the values never appear in source control or in a screenshot of your terminal. In Playwright, Chromium also accepts a proxy on the browser context, which is the feature that makes per-task isolation practical.
Targeting headers belong on the same context, not in the destination URL. A country or session header configured through the context applies to every request that context makes, which keeps routing consistent across redirects and subresources.
import { chromium } from "playwright";
const proxy = {
server: process.env.GRAVIIX_PROXY_SERVER,
username: process.env.GRAVIIX_PROXY_USER,
password: process.env.GRAVIIX_PROXY_PASS,
};
const browser = await chromium.launch();
const context = await browser.newContext({
proxy,
extraHTTPHeaders: { "X-Graviix-Country": "US" },
});
const page = await context.newPage();
await page.goto("https://httpbin.org/ip", {
waitUntil: "domcontentloaded",
});
console.log(await page.textContent("body"));
await context.close();
await browser.close();Puppeteer needs two separate steps
Puppeteer sets the proxy server through a launch argument, but the argument does not accept a username and password. Authentication is supplied separately on each page, which is a common source of confusion when a browser opens but every request arrives with a 407.
Keep the endpoint in the launch argument and credentials in the page call. If you need a session header, set it on the page before the first navigation so the initial request carries the routing instruction.
import puppeteer from "puppeteer";
const browser = await puppeteer.launch({
headless: true,
args: [`--proxy-server=${process.env.GRAVIIX_PROXY_SERVER}`],
});
const page = await browser.newPage();
await page.authenticate({
username: process.env.GRAVIIX_PROXY_USER,
password: process.env.GRAVIIX_PROXY_PASS,
});
await page.setExtraHTTPHeaders({
"X-Graviix-Country": "US",
});
await page.goto("https://httpbin.org/ip");One context per task, not one browser for everything
A browser context is an isolated cookie jar with its own cache and storage. Creating a context per task keeps a checkout flow from sharing cookies with a price check, and it lets two tasks use different sessions or locations at the same time. Close the context when the task ends instead of leaving it to accumulate memory.
In Playwright, a context can carry its own proxy on Chromium, so a single browser can serve several tasks with different targeting. Puppeteer keeps the proxy at the browser level, so parallel tasks that need different endpoints require separate browser instances. Choose the framework with that difference in mind if per-task routing is a requirement.
Do not reuse a context after its session has expired. Create a new context with a new session identifier, and record the identifier next to the task result so a later investigation can tell which peer was used.
Verify the exit IP before the real work
Open an IP echo page first and assert the reported country before navigating to the target. This catches a wrong endpoint, an expired credential, or a session header that was never applied. It also gives you the exit IP to store with the run, which is the single most useful field when a later result is disputed.
Fail fast. If the echo page reports the wrong location, do not start the collection; the dataset would be mislabelled and expensive to repair. A short pre-flight check costs a few kilobytes and prevents hours of rework.
- Assert success, country, and session identity before the first target request.
- Store the exit IP and timestamp with the task record.
- Run the check on the same context that will perform the work.
- Re-check after a browser or session restart, not only at the start of the job.
The first errors and what they mean
ERR_TUNNEL_CONNECTION_FAILED usually means the browser could not reach the proxy endpoint at all: wrong host, wrong port, or a firewall in between. It is not an authentication error, so changing the password will not help.
A page that loads a 407 message means the proxy rejected the credentials. Check that authentication was applied to this exact context, that special characters in the password are handled correctly, and that the credential is still active. In Puppeteer, forgetting the per-page authenticate call produces this symptom on an otherwise healthy browser.
Timeouts on the first navigation are often proxy latency rather than a broken route. Give the first load a longer budget than later requests and measure time to first byte before concluding that the endpoint is down. TLS errors are different: they usually point to an intercepting middlebox or a client that does not trust the proxy certificate chain.
Keep the browser environment repeatable
Containers need the same browser version, fonts, and shared libraries on every run, or the rendered page can differ from the one you tested. Pin the browser revision and the automation library together, and rebuild the image when either changes.
Watch memory and process count as contexts accumulate. A browser that has handled hundreds of contexts without a restart may slow down or crash, and the failure often looks like a proxy timeout. Restart on a schedule that fits your workload, and log the restart so it is not confused with a network incident.
Headless mode is appropriate for most data collection. Switch to a visible browser when you are debugging a page that behaves differently, and capture a screenshot on failure so the next person sees the page instead of a stack trace.
How the two frameworks treat proxies differently
Playwright separates the browser from its contexts. The browser is the process; each context is an isolated browsing profile. On Chromium, a context can carry its own proxy, credentials, targeting headers, and emulated device. That design maps cleanly onto a worker that handles many independent tasks inside one process.
Puppeteer sets the proxy when the browser launches, and the setting applies to every page in that browser. Parallel tasks that need different exit locations therefore need separate browser processes, which is heavier but simpler to reason about. There is no per-context proxy equivalent in the current API.
Choose based on the routing model, not on a benchmark of raw page loads. If tasks share a location, Puppeteer is perfectly adequate. If tasks need different locations, carriers, or credentials at the same time, Playwright contexts save a considerable amount of memory and startup time.
A useful test is to map the workflow to contexts on paper before writing code. One task that spans a login, a cart, and a confirmation is one context. Fifty independent price checks are fifty short-lived contexts, or one context per few checks if the site does not set state. Whichever model you choose, the mapping should be explicit rather than emerging from whatever the code happens to do.
- Playwright Chromium: per-context proxy, headers, storage, and device emulation.
- Puppeteer: browser-wide proxy; separate browsers for different endpoints.
- Firefox and WebKit in Playwright use launch-level proxy settings on current versions.
- Contexts are cheap to create compared with browsers, but they still need closing.
Logging and evidence for failed runs
When a headless run fails, the useful evidence is rarely the exception message. Capture the URL, the exit IP, the session identifier, the response status, a screenshot, and a short HTML snippet at the moment of failure. Those fields answer whether the page was a refusal, a consent wall, an empty shell, or a genuine timeout.
Enable request and response logging for a sample of runs rather than for every request. A full network log of a large job is enormous and often contains cookies or tokens. Sampling keeps the log small and still shows the sequence of requests that led to the failure.
Never write credentials into the log, including proxy URLs with embedded authentication. Redact the proxy configuration when printing it, and store secrets only in the environment or the platform secret store.
Keep the timezone explicit in timestamps. A failure at the boundary between two days is otherwise ambiguous when it is compared with a provider dashboard, and that ambiguity costs more time than the log itself. The IP lookup tool is handy for a quick exit-IP sanity check outside the browser, while the full record should come from the run itself.
Session identity across browser restarts
A browser restart destroys the context, so any session identifier that lived only in memory disappears. For tasks that need continuity, persist the session identifier and the task state before the restart, then create the new context with the stored identifier if the session is still alive.
If the session has expired, do not silently continue with a new peer. Mark the task as restarted in its record. A result that mixes two exit IPs without a note is indistinguishable from a data quality problem, and it is far harder to investigate after the fact.
Set a shutdown hook that releases sessions when the process exits cleanly. Crashes will still leave sessions to expire on their own, which is acceptable; what matters is that the happy path does not hold capacity longer than the task needs.
The headless browser overview covers the operational side of running many sessions, including timeouts and resource use. Pair that with the proxy setup above and a task can be reproduced from its stored configuration rather than from memory.
Key takeaways
- Set proxy settings at launch, and supply credentials separately in Puppeteer.
- Use one browser context per task so cookies, sessions, and targeting stay isolated.
- Verify the exit IP before the first target request and store it with the result.
Frequently asked questions
Can each tab use a different proxy?
In Playwright on Chromium, yes: each browser context can carry its own proxy and a tab belongs to a context. In Puppeteer the proxy is set for the whole browser, so different proxies mean separate browser instances.
Why does the browser ignore my proxy credentials?
Puppeteer does not accept credentials inside the --proxy-server argument; they must be supplied with page.authenticate. In Playwright, confirm the credentials are on the context that makes the request and that special characters are passed as-is rather than percent-encoded.
Do I need a visible browser for scraping?
Usually not. Headless mode is faster and easier to run in containers. Use a visible browser only to debug a page that behaves differently, and keep screenshots on failure for headless runs.
Need proxies for this workflow?
Graviix provides residential, mobile, datacenter, and static ISP proxies with country and city targeting, rotating or sticky sessions, and a documented HTTP API.










