Skip to content

How to use a proxy with Playwright

Playwright has a built-in proxy option with server, username and password, so authenticated proxies need no extensions or extra packages. This guide shows how to set a proxy for a whole browser or for each context, keep a sticky IP per context, target countries and cities, and handle proxy errors.

Updated 9 November 2026

Prerequisites

  • Playwright for Node.js (npm i playwright, then npx playwright install chromium) or Python (pip install playwright, then playwright install chromium). Examples were checked against Playwright 1.6x.
  • A proxy login from the dashboard under Logins, written here as USER and PASS.

Typical uses are end-to-end testing from other regions, checking localized pages and ads, and collecting public data that only renders with JavaScript.

Basic proxy for the whole browser

Pass proxy to launch(). The server is the gateway without credentials; the username and password go in their own fields. Every page in that browser uses the proxy.

import { chromium } from "playwright";

const browser = await chromium.launch({
  proxy: {
    server: "http://gw.hyperproxy.io:8888",
    username: "USER-cc-us",
    password: "PASS",
  },
});
const page = await browser.newPage();
await page.goto("https://api.ipify.org");
console.log(await page.textContent("body"));
await browser.close();

Authentication

Don't put USER:PASS@ inside server; browsers ignore credentials in the proxy URL. Use the username and password fields, and Playwright answers the proxy's 407 challenge for you. The username is also where targeting options and session ids go.

Per-context proxies and sticky sessions

A browser page opens many connections at once: the document, scripts, images, API calls. The gateway rotates per connection, so without a session one page load could leave from several IPs. For browsers, use a sticky session per context: all of that context's connections then share one exit for 5 minutes by default, or up to 120 with ttl.

Setting proxy on newContext() gives each context its own login, session and country while sharing one browser process. Generate session ids with letters and digits only.

import { randomUUID } from "node:crypto";
import { chromium } from "playwright";

const browser = await chromium.launch();

// one sticky IP per context; each context is an isolated session
async function newContext(country) {
  const session = randomUUID().replaceAll("-", "").slice(0, 12);
  return browser.newContext({
    proxy: {
      server: "http://gw.hyperproxy.io:8888",
      username: `USER-cc-${country}-session-${session}-ttl-30`,
      password: "PASS",
    },
  });
}

for (const country of ["us", "de", "jp"]) {
  const context = await newContext(country);
  const page = await context.newPage();
  await page.goto("https://api.ipify.org");
  console.log(country, await page.textContent("body"));
  await context.close();
}
await browser.close();

To rotate, close the context and open a new one with a new session id.

Country and city targeting

UsernameExit
USER-cc-gbUnited Kingdom
USER-cc-us-city-new_yorkNew York
USER-cc-us-region-californiaCalifornia
USER-cc-us-os-androidAn Android device in the US
USER-cont-euAnywhere in Europe
USER-cc-us-city-houston-strict-falseHouston, falling back to the rest of the US

Exit location changes the IP, not the browser. Set a matching locale and timezoneId on the context if your test depends on them.

SOCKS5

Playwright accepts socks5:// servers, but its username and password fields are documented for HTTP proxies only, and Chromium doesn't support authenticated SOCKS5. Use the HTTP endpoint shown above for browsers. It tunnels HTTPS with CONNECT, so pages are still encrypted end to end. For SOCKS5 from scripts, see the curl or Python requests guides.

Concurrency

Contexts are cheap compared with browsers. Launch one browser and run a fixed number of contexts at a time, each with its own session. Close contexts when you're done with them, both to free memory and to end the proxy connections.

javascript
import { randomUUID } from "node:crypto";
import { chromium } from "playwright";

const urls = Array.from({ length: 20 }, (_, i) => `https://example.com/page/${i}`);
const browser = await chromium.launch();

async function worker() {
  for (let url = urls.shift(); url; url = urls.shift()) {
    const session = randomUUID().replaceAll("-", "").slice(0, 12);
    const context = await browser.newContext({
      proxy: { server: "http://gw.hyperproxy.io:8888", username: `USER-cc-us-session-${session}`, password: "PASS" },
    });
    try {
      const page = await context.newPage();
      const res = await page.goto(url, { timeout: 60_000 });
      console.log(url, res?.status());
    } finally {
      await context.close();
    }
  }
}

await Promise.all(Array.from({ length: 4 }, worker)); // 4 pages at a time
await browser.close();

To save bandwidth, block resources you don't need with page.route(), for example images and fonts. All traffic through the proxy counts toward usage.

Error handling and retries

When the gateway rejects a CONNECT, Chromium doesn't show its status code. page.goto() rejects with a net:: error instead, such as ERR_TUNNEL_CONNECTION_FAILED or, for bad credentials, ERR_INVALID_AUTH_CREDENTIALS. To see the actual status, send the same username through curl: curl -v -x http://USER-cc-us:PASS@gw.hyperproxy.io:8888 https://api.ipify.org. Then map it with Errors:

  • 407: wrong credentials, a misspelled or repeated option, or no balance. Fix it; don't retry.
  • 404: no exit matches the targeting. Widen it or add strict-false.
  • 403: the target is not allowed.
  • 502 / 504: retry. Within a session the retry uses the same exit; if that exit went offline, the session moves to a new IP.
javascript
async function gotoWithRetry(page, url, attempts = 3) {
  for (let i = 1; ; i++) {
    try {
      return await page.goto(url, { timeout: 60_000 });
    } catch (err) {
      const msg = String(err);
      // auth or targeting problems: retrying won't help
      if (msg.includes("ERR_INVALID_AUTH_CREDENTIALS") || i >= attempts) throw err;
      await new Promise((r) => setTimeout(r, 1000 * 2 ** i));
    }
  }
}

Verify the exit IP

Open https://api.ipify.org in the proxied page and read the body, as in the examples above. Two pages in the same context should show the same IP; contexts with different session ids should show different ones.

Troubleshooting

  • The browser asks for proxy credentials or fails at once: credentials are in server instead of username/password.
  • One page shows several IPs: add a session to the username.
  • Timeouts on heavy pages: raise the navigation timeout, use waitUntil: "domcontentloaded", and block unneeded resources.
  • 404 for a city: names are lowercase English with _ for spaces, for example new_york.

FAQ

Can each Playwright context use a different proxy?

Yes. Pass proxy to browser.newContext() (or new_context() in Python). Each context can have its own country and session.

Does the proxy apply to WebSockets?

Yes. The browser sends all of the context's HTTP, HTTPS and WebSocket traffic through the proxy.

Should I use Playwright or Puppeteer?

Both work. Playwright's proxy option handles authentication directly and supports several browsers; see the Puppeteer guide for the Chromium-only alternative, or Crawlee for a crawler built on top of Playwright.

Where are more examples?

See Examples for Playwright, Puppeteer and HTTP clients side by side.

Try it on your own workload

Sign up with GitHub or Google, create a proxy login and send your first request in a minute.

More proxy integration guides

  • Python requests — Rotating and sticky residential proxies with Python requests, including SOCKS5 and retries.
  • Python httpx — Sync and async httpx through a residential proxy with the proxy= argument and SOCKS5.
  • Python aiohttp — High-concurrency aiohttp requests through rotating or sticky residential IPs.
  • Scrapy — Route Scrapy spiders through residential proxies with request.meta and a middleware.
  • Puppeteer — Launch Puppeteer behind an authenticated residential proxy with page.authenticate.
  • Crawlee — Map Crawlee sessions to sticky residential IPs and target countries per request.
  • Node.js axios — Send axios requests through HTTP and SOCKS5 residential proxies with proxy agents.
  • Node.js fetch & undici — Use Node's built-in fetch with undici ProxyAgent or NODE_USE_ENV_PROXY.
  • Go net/http — Configure Go's http.Transport for HTTP and SOCKS5 residential proxies.
  • curl & SOCKS5 — Use curl with HTTP and SOCKS5 proxies, and test targeting from the command line.