Skip to content
Blog

Playwright and Puppeteer Proxy Authentication (HTTP and SOCKS5)

Authenticated proxies in Playwright (Python, Node) and Puppeteer: launch vs context proxies, page.authenticate, sticky sessions per context, SOCKS5 limits.

Exitway team··6 min read

The short version:

  • Playwright: pass {"server": "http://gw.exitway.net:7777", "username": ..., "password": ...} as proxy, either at launch or per browser context.
  • Puppeteer: start Chromium with --proxy-server=http://gw.exitway.net:7777 and call page.authenticate() on every page.
  • Scheme: use the http:// scheme even for HTTPS sites, and give each identity its own browser context with its own sticky session.
  • SOCKS5: don’t try it with credentials. Chromium can’t authenticate to a SOCKS5 proxy, and the fix is simply to use the HTTP protocol on the same port.

The rest of this guide is the detail behind those rules, including one that costs people hours: Chromium hides the proxy’s error codes.

The three values

Field Value
Server http://gw.exitway.net:7777 (residential) or :8888 (datacenter)
Username USERNAME, plus options: -country-us, -session-abc123, -lifetime-30
Password Your proxy password from the dashboard, not your account password

Every Exitway port accepts HTTP, HTTPS (via CONNECT) and SOCKS5, detected automatically, so the same server and credentials work in every tool. The examples read EXITWAY_USER and EXITWAY_PASS from the environment.

Playwright (Python): proxy at launch

import os

from playwright.sync_api import sync_playwright

PROXY = {
    "server": "http://gw.exitway.net:7777",
    "username": f"{os.environ['EXITWAY_USER']}-country-us",
    "password": os.environ["EXITWAY_PASS"],
}

with sync_playwright() as p:
    browser = p.chromium.launch(proxy=PROXY)
    page = browser.new_page()
    page.goto("https://ipinfo.io/json", timeout=45_000)
    print(page.inner_text("body"))
    browser.close()

A launch-level proxy applies to every context in that browser. That’s fine for a one-off script with a single identity. Switch to context-level proxies as soon as you run more than one identity, or want to change country without restarting the browser. Without a session parameter, each new connection the browser opens can exit from a different IP, so one page load may use several IPs. For browsing, you almost always want a sticky session.

Chromium hides proxy errors

We ran this against an account with no residential bandwidth left. The gateway answered the CONNECT with 402 Payment Required, and Playwright raised:

playwright._impl._errors.Error: Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://ipinfo.io/json

Chromium collapses every refused tunnel into the same generic error. Here is what we observed for each failure mode:

Situation page.goto on an https:// URL Playwright context.request
Out of bandwidth (402) ERR_TUNNEL_CONNECTION_FAILED status 402, header x-exitway-error: insufficient_balance
Wrong password (407) Playwright: navigation timeout. Puppeteer: a 407 error page status 407, auth_required
Bad parameter (400) ERR_TUNNEL_CONNECTION_FAILED status 400, invalid_parameters

The fix is a preflight request through Playwright’s request API. It uses the context’s proxy settings but its own HTTP client, so you get the gateway’s real status and the X-Exitway-Error header. A wrong password that would otherwise look like a 45-second timeout becomes an immediate 407.

One sticky session per browser context

A browser context is an isolated profile with its own cookies, storage and cache. Give each one its own proxy username and you get an identity with a stable IP:

import os
import uuid

from playwright.sync_api import sync_playwright

USER, PASS = os.environ["EXITWAY_USER"], os.environ["EXITWAY_PASS"]


def sticky_proxy(country, minutes=30):
    session = uuid.uuid4().hex[:12]  # letters and digits only
    return {
        "server": "http://gw.exitway.net:7777",
        "username": f"{USER}-country-{country}-session-{session}-lifetime-{minutes}",
        "password": PASS,
    }


def check_proxy(context):
    """Chromium hides the proxy's status code; Playwright's request API does not."""
    r = context.request.get("https://ipinfo.io/json", timeout=30_000)
    if r.headers.get("x-exitway-error"):
        raise RuntimeError(f"proxy refused: {r.status} {r.text().strip()}")
    return r.json()


with sync_playwright() as p:
    browser = p.chromium.launch()
    for country in ("us", "de", "jp"):
        context = browser.new_context(proxy=sticky_proxy(country))
        try:
            ip = check_proxy(context)["ip"]
            page = context.new_page()
            page.goto("https://ipinfo.io/json")
            print(country, ip, page.inner_text("body")[:80])
        except RuntimeError as exc:
            print(country, exc)
        finally:
            context.close()
    browser.close()

On an empty balance this prints us proxy refused: 402 Exitway: no bandwidth left on this pool, please top up instead of a stack trace. Because the session is sticky, the IP the preflight reports is the IP the page will use, barring a failover. The check costs a few KB of bandwidth per context.

Some notes on sessions:

  • Session ids accept letters and digits, up to 32 characters. Lifetimes run from 1 to 1440 minutes.
  • Ids are scoped to your account, so another customer using the same id never gets your IP.
  • One browser with many contexts is much cheaper in memory than many browsers, and on Linux, Playwright’s Chromium handles a different proxy per context without any launch-level proxy.

Playwright (Node)

The same pattern in JavaScript. It also sets the locale and time zone to match the exit country, because a German IP with an en-US browser is an easy inconsistency for a site to spot.

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

const { EXITWAY_USER, EXITWAY_PASS } = process.env;

function stickyProxy(country, minutes = 30) {
  const session = randomUUID().replaceAll("-", "").slice(0, 12);
  return {
    server: "http://gw.exitway.net:7777",
    username: `${EXITWAY_USER}-country-${country}-session-${session}-lifetime-${minutes}`,
    password: EXITWAY_PASS,
  };
}

const browser = await chromium.launch();
const context = await browser.newContext({
  proxy: stickyProxy("gb"),
  locale: "en-GB",
  timezoneId: "Europe/London",
});

const check = await context.request.get("https://ipinfo.io/json");
if (check.headers()["x-exitway-error"]) {
  console.error(`Proxy refused: ${check.status()} ${(await check.text()).trim()}`);
} else {
  const page = await context.newPage();
  await page.goto("https://ipinfo.io/json");
  console.log(await page.textContent("body"));
}
await browser.close();

Puppeteer: --proxy-server and page.authenticate

Puppeteer passes the proxy to Chromium as a flag, then answers the proxy’s 407 challenge with credentials:

import puppeteer from "puppeteer";

const { EXITWAY_USER, EXITWAY_PASS } = process.env;

const browser = await puppeteer.launch({
  args: ["--proxy-server=http://gw.exitway.net:7777"],
});
const page = await browser.newPage();
await page.authenticate({ username: `${EXITWAY_USER}-country-us`, password: EXITWAY_PASS });

try {
  const res = await page.goto("https://ipinfo.io/json", { timeout: 45_000 });
  console.log(res.status(), await res.text());
} catch (err) {
  // A refused CONNECT (402, 400, ...) surfaces as a generic network error
  console.error(err.message); // net::ERR_TUNNEL_CONNECTION_FAILED at https://ipinfo.io/json
} finally {
  await browser.close();
}

If you run as root inside Docker, add --no-sandbox to args. Puppeteer has no request API for a preflight check, so run one request through any HTTP client first to classify errors (see the Python guide).

For several identities in one browser, Puppeteer’s browser contexts take their own proxyServer. Credentials are still set per page, not per context:

import puppeteer from "puppeteer";
import { randomUUID } from "node:crypto";

const { EXITWAY_USER, EXITWAY_PASS } = process.env;
const browser = await puppeteer.launch();

async function openIdentity(country) {
  const session = randomUUID().replaceAll("-", "").slice(0, 12);
  const context = await browser.createBrowserContext({ proxyServer: "http://gw.exitway.net:7777" });
  const credentials = {
    username: `${EXITWAY_USER}-country-${country}-session-${session}-lifetime-30`,
    password: EXITWAY_PASS,
  };
  const newPage = async () => {
    const page = await context.newPage();
    await page.authenticate(credentials); // per page, not per context
    return page;
  };
  return { context, newPage };
}

const fr = await openIdentity("fr");
const page = await fr.newPage();
try {
  await page.goto("https://ipinfo.io/json", { timeout: 45_000 });
  console.log(await page.evaluate(() => document.body.innerText));
} catch (err) {
  console.error(err.message);
}
await fr.context.close();
await browser.close();

Wrapping newPage this way means you can’t forget the authenticate call on a second tab.

SOCKS5: use the HTTP endpoint instead

Chromium supports SOCKS5 proxies but not SOCKS5 username/password authentication. Playwright refuses the configuration up front:

import os

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(proxy={
        "server": "socks5://gw.exitway.net:7777",
        "username": os.environ["EXITWAY_USER"],
        "password": os.environ["EXITWAY_PASS"],
    })
playwright._impl._errors.Error: BrowserType.launch: Browser does not support socks5 proxy authentication

Puppeteer doesn’t complain at launch. It fails on the first navigation with net::ERR_SOCKS_CONNECTION_FAILED, because Chromium never sends the credentials.

The honest workaround is to not use SOCKS5 for browsers at all. Change socks5:// to http:// and keep everything else: same host, port, username options and password. The gateway detects the protocol per connection, and HTTPS traffic is still end-to-end encrypted inside the CONNECT tunnel. Keep SOCKS5 for tools that handle its authentication properly, such as curl with socks5h://.

Keep the bandwidth bill in check

A browser downloads everything a page references, so a page that weighs 100 KB as HTML can cost several MB rendered. Blocking images, media and fonts with page.route is the biggest lever. The residential vs datacenter guide has the snippet and the cost math.

Going further

A clean residential IP doesn’t hide an automated browser. For Patchright, nodriver and SeleniumBase UC with authenticated proxies, see this guide. For what sites actually measure, read browser fingerprinting for scrapers. Automate only what you’re allowed to, and within our Acceptable Use Policy.

Exitway residential proxies start at $0.70/GB with no subscription, and every port takes HTTP and SOCKS5. Create an account or read the docs.

More guides