Skip to content

Guides · Connect and debug

Playwright proxy setup and authentication

Set the proxy on the browser context, keep gateway credentials separate from website login details, and verify the route with a real page navigation. This guide uses Chromium and an authenticated HTTP proxy for a repeatable QA workflow.

Short answers

Where do I configure a proxy in Playwright?

Pass a proxy object when launching the browser or creating a browser context. Its server is the gateway address; authenticated HTTP proxies also use separate username and password fields.

Does httpCredentials authenticate the proxy?

No. httpCredentials is for HTTP authentication at the website. Configure gateway authentication inside the proxy object. Keep both separate from an application’s login form and saved browser state.

Can each page use a different proxy?

Proxy configuration belongs to the browser or context. Create separate contexts for different proxy settings, and put each page in the intended context. A new tab inside an existing context shares that context’s configuration.

Should I use HTTP or SOCKS5 with authentication?

Use the authenticated HTTP gateway in this recipe. Playwright documents proxy username and password fields for HTTP authentication; SOCKS support does not imply the same authenticated SOCKS behaviour in every browser engine.

Start with a known connection

Use this workflow for browser QA, regional presentation checks or another task you have permission to run. First verify a small request with the curl check. That separates a browser setup problem from a wrong password or an unavailable country. For a manual check in your own Chrome rather than a script, set the proxy with an extension.

  1. Open the connection builder and choose HTTP, your pool and an available country.
  2. Use a named sticky session for a multi-step journey. Copy the complete generated username rather than its account prefix.
  3. Make PROXY_USER and PROXY_PASSWORD available to the process through your runtime’s secret configuration. Do not put them in a committed test file.
  4. Keep the first run small and unfiltered. Prove that a page can load before adding request interception, parallel workers or a long test suite.
Install the library and its Chromium buildsh
npm install playwright
npx playwright install chromium

Use a Node.js version supported by the installed Playwright release. The library installation guide covers browser installation and operating-system dependencies; a container needs those browser dependencies inside the container too.

Run an authenticated page navigation

Save this as proxy-check.mjs. The optional PROXY_SERVER value contains only the scheme, host and port. Credentials remain separate, so a special character in the password is not interpreted as URL punctuation.

proxy-check.mjsjavascript
import { chromium } from 'playwright';

function required(name) {
  const value = process.env[name];
  if (!value) throw new Error('Missing ' + name);
  return value;
}

async function main() {
  const proxy = {
    server: process.env.PROXY_SERVER ?? 'http://gw.portproof.org:7000',
    username: required('PROXY_USER'),
    password: required('PROXY_PASSWORD'),
  };
  const browser = await chromium.launch({ headless: true });
  try {
    const context = await browser.newContext({ proxy });
    try {
      const page = await context.newPage();
      const response = await page.goto('https://api.portproof.org/v1/echo-ip', {
        waitUntil: 'domcontentloaded',
        timeout: 30_000,
      });
      if (!response || !response.ok()) {
        throw new Error('Echo did not return a successful HTTP status');
      }
      const payload = JSON.parse(await page.locator('body').innerText());
      if (typeof payload.ip !== 'string') {
        throw new Error('Echo did not return an IP address');
      }
      console.log('HTTP', response.status(), 'exit', payload.ip);
    } finally {
      await context.close();
    }
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error('Browser check failed:', error.name);
  process.exitCode = 1;
});

Run node proxy-check.mjs. The output is the status and your own observed exit address. This request travels through a page in the configured context, which is the path the browser workflow needs. A separate Node fetch call would test a different client unless you configured that client as well.

The configuration follows Playwright’s HTTP proxy guide and browser context options. The script closes the context before the browser, including when the request fails, so a failed check does not leave a browser running.

Choose browser-wide or per-context settings

Set proxy in chromium.launch when every context in that browser should use the same gateway configuration. Set it in browser.newContext when a job needs an explicit configuration per context. Prefer one clear scope in the first implementation instead of relying on interactions between both.

A browser context separates cookies and other browser state. A gateway sticky session is a different mechanism, selected in the proxy username. Give independent QA journeys their own context and, when needed, their own session name. Keep one context for the related steps of a single journey.

Closing and opening a context does not itself promise a new exit address. Likewise, a sticky session does not promise that a device’s IP will stay unchanged. If a journey depends on continuity, record which context and session name belong to it and handle an interrupted journey explicitly. See rotation and sticky sessions.

Configure Playwright Test at its own entry point

The preceding example uses the standalone library. A suite driven by @playwright/test usually puts the setting in use.proxy in its existing configuration. Add this configuration to that project rather than assuming the standalone script changes the test runner.

Proxy settings in playwright.config.tstypescript
import { defineConfig } from '@playwright/test';

const username = process.env.PROXY_USER;
const password = process.env.PROXY_PASSWORD;
if (!username || !password) throw new Error('Proxy credentials are required');

export default defineConfig({
  use: {
    proxy: {
      server: process.env.PROXY_SERVER ?? 'http://gw.portproof.org:7000',
      username,
      password,
    },
  },
});

If your suite already has projects, devices, retries or a base URL, preserve them and add the proxy field at the appropriate scope. Keep worker counts low while validating the route. A configuration problem repeated across many workers consumes traffic without adding useful evidence.

Check the page your test actually needs

An echo response proves that this browser reached that endpoint. Next, navigate to one authorised application page and assert a meaningful piece of content. A successful navigation can still return an error page, an unexpected market or a sign-in screen.

Playwright’s navigation reference explains that ordinary HTTP error statuses do not make page.goto throw. Check the response and the application state. Prefer a bounded navigation followed by a specific locator or assertion over waiting indefinitely for every network request to stop.

For regional QA, keep the country setting, locale, time zone, account state and test data in the case description. A country-targeted route is only one signal a website can use. The wrong-country guide covers why an address lookup and the page’s selected market may differ.

Troubleshoot without weakening the check

Playwright proxy troubleshooting
SymptomNext check
407 or a proxy authentication errorConfirm username and password are inside proxy, not httpCredentials. Compare them with a fresh builder result.
An unsupported proxy authentication messageUse the HTTP gateway and its HTTP port for this recipe. Do not assume browser SOCKS authentication behaves like curl.
ERR_TUNNEL_CONNECTION_FAILEDRecheck scheme, port, balance and country availability with the same connection in curl.
Navigation timeoutTry the small echo page first. Then distinguish connection failure from an application whose expected state never appears.
Certificate validation failureCheck the destination certificate and machine trust configuration. Keep HTTPS validation enabled.
Works locally but not in CICheck browser installation, operating-system dependencies and availability of the credential variables in the worker.
Page loads but the test sees old account dataUse the intended browser context and review any restored storage state. A proxy does not clear cookies.

Use 407 troubleshooting for gateway credentials and CONNECT failures for tunnel problems. The generic error printed by this sample keeps shared logs small; inspect detailed exceptions locally after checking that URLs, headers and artefacts will not expose credentials.

Saved browser state can contain cookies that grant access to an account. Keep authentication files and traces out of public repositories and shared build artefacts. Playwright’s authentication guide explains the storage-state precautions.

Measure a representative browser journey

A browser loads more than the top-level document. Images, fonts, scripts, redirects and retries can make a journey much larger than an HTTP API call. Establish a passing baseline, then use the browser bandwidth guide to remove only assets the test does not depend on.

Keep visual checks representative: a screenshot with missing fonts and images is a different test. For data already available through an authorised endpoint, the Python Requests guide or Node fetch guide may fit better. See current per-GB pricing and the connection fields in the setup documentation.

What is not allowed

Run browser journeys only where you have permission and follow the destination’s terms, access controls and rate limits. Appropriate uses include your own QA, ad verification and lawful regional research. See the acceptable-use policy.

Playwright proxy setup and authentication · Portproof