Power Your Software Testing with AI and Cloud

Supercharge QA with AI for Faster & Smarter Software Testing

Next-Gen App & Browser Testing Cloud

How to Use Playwright Proxy: A Complete Tutorial

Learn how to configure and use Playwright proxy for automation testing, including global, context-specific setups, and proxy rotation strategies.

Published on: November 9, 2025

  • Share:

When performing automation testing with frameworks like Playwright, a proxy acts as a network layer between test scripts and the target web application. The Playwright proxy controls how requests and responses are routed. It allows you to simulate different geographic locations, manage rate limits, and inspect or modify network traffic during test execution.

Overview

A Playwright proxy is a network intermediary configured in tests to route browser traffic, control network conditions, simulate regions, and manage requests during automation efficiently.

How to Set Up a Proxy in Playwright?

Playwright allows global or context-specific proxy setups to simulate regions, control network flow, and test under different network conditions.

  • Global Proxy Configuration: Apply a single proxy to all browser contexts and pages within a browser instance by passing the proxy option in browser.launch(). This is ideal for consistent network conditions across tests.
  • Context-Specific Proxy Configuration: Assign different proxies to individual browser contexts. Context-level proxies override the global setup, allowing isolated testing with multiple network conditions.

What Are Proxy Rotation Strategies in Playwright?

Rotating proxies in Playwright ensures test scripts bypass IP restrictions, avoid detection, and simulate different network locations for more realistic automation testing environments.

  • Round-Robin Rotation: Cycle sequentially through a list of proxies, assigning each new test to the next proxy, ensuring even distribution across parallel or repeated automation runs.
  • Random Selection: Select a proxy randomly for each request, simulating unpredictable user origins and testing how your application behaves under diverse network conditions effectively.
  • Session-Based Rotation: Assign a specific proxy to each session, maintaining session continuity across steps, while still rotating proxies between different sessions for distributed traffic.
  • Health-Based Rotation: Monitor proxy responsiveness, automatically removing failing or unresponsive proxies, ensuring automation tests continue without interruption and maintaining reliable coverage across the entire proxy pool.
  • Time-Based Rotation: Change proxies after a fixed interval, regardless of request count, to reduce detection risk and simulate different user sessions across multiple automated tests efficiently.
  • Request-Count-Based Rotation: Rotate proxies after a set number of requests or actions, preventing temporary bans, rate-limits, or other access issues during extensive automated test executions.
  • Geo-Location-Based Rotation: Assign proxies based on geographic regions to simulate location-specific behavior, test content delivery, verify compliance, and observe application performance across multiple regions effectively.
  • Third-Party Proxy Rotators: Use external proxy rotation services to automatically handle proxy switching, centralizing management while reducing implementation complexity in your Playwright automation test scripts.

How to Configure Proxy in Playwright?

You can set up a proxy in Playwright using browser launch or a config file. Use global proxy for all contexts or context-specific proxies for isolated tests, simulating regions and controlling network flow.

Before configuring Playwright proxy, ensure the following are in place:

  • Install Node.js and npm.
  • Install Playwright by running:
  • npm init playwright@latest

  • Set up a Playwright test project with at least one sample test file to verify that your environment is working correctly.

Once the above steps are done, you can use these methods: global proxy configuration and context-specific proxy configuration.

Global Proxy Configuration

Global proxy configuration in Playwright is ideal when you want all browser contexts and pages within a single browser instance to use the same proxy.

To set it up, configure the proxy by passing the proxy option with a server parameter in the browser.launch() method.

const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch({
    proxy: {
      server: "38.54.71.67:80",
    },
  });

  const page = await browser.newPage();
  await page.goto("https://httpbin.org/ip");
  const content = await page.content();
  await browser.close();
})();

LambdaTest Playwright Proxy GitHub Repository

Context-Specific Proxy Configuration

Context-level proxy only applies the proxy configuration to a specific browser context rather than the entire instance. Context-level proxy configurations override the global proxy setup. Any context without a proxy configuration falls back to the global setup by default.

Here's an example that sets up two different proxies for two contexts.

const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch();

  const url = "https://httpbin.io/ip";

  // set up two different contexts with different proxies
  try {
    const context1 = await browser.newContext({
      proxy: { server: "http://116.101.76.130:2058" },
    });

    const page1 = await context1.newPage();
    await page1.goto(url, { timeout: 10000 });
    content1 = await page1.content();
    console.log("content1:", content1);
    await context1.close();
  } catch (err) {
    console.error("Context1 error:", err.message);
  }

  try {
    const context2 = await browser.newContext({
      proxy: { server: "20.252.53.196:3128" },
    }); // no proxy
    const page2 = await context2.newPage();
    await page2.goto(url);
    content2 = await page2.content();
    console.log("content2:", content2);
    await context2.close();
  } catch (err) {
    console.error("Context2 error:", err.message);
  }

  await browser.close();
})();

The above code sets a different proxy per context. Each page inherits its context's proxy configuration. We've wrapped each context in a separate try/catch block to isolate failures and ensure that errors in one context don't impact the execution of the other. This allows you to track and handle issues independently at the context level.

Note

Note: Run Playwright tests across 50+ browser environments. Try LambdaTest Now!

Playwright Proxy Rotation Strategies

Proxy rotation in Playwright involves using different IPs per request. During automation testing, proxies can be rotated to bypass IP-based rate limits, avoid detection mechanisms, and simulate diverse user environments across regions or networks.

There are various strategies to rotate the Playwright proxy:

Round-Robin Rotation

Round-robin rotation cycles through your proxy list in order, assigning each new automated test the next proxy in the sequence. This approach evenly distributes the test traffic and is simple to implement. It is a good choice for parallel or repeated test runs where a uniform network distribution is desired.

let proxyIndex = 0;
function getNextProxy(proxies) {
  const proxy = proxies[proxyIndex % proxies.length];
  proxyIndex++;
  return proxy;
}

Random Selection

This method involves picking a proxy at random for each request. This method is useful for simulating unpredictable user origins and for testing how your web application responds to access from a variety of networks.

function getRandomProxy(proxies) {
  return proxies[Math.floor(Math.random() * proxies.length)];
}

Session-Based Rotation

Session-based rotation or sticky session assigns a proxy to each browsing session and sticks with it for the duration of that session. This is particularly useful when you need to maintain session continuity (cookies or authentication state) across multiple steps, while still distributing your tests across different proxies.

The following example assigns a consistent proxy to each session and ensures that a Playwright proxy stays the same for a session it's assigned to.

const sessionProxies = new Map();
const getSessionProxy=(sessionId, proxies) =>{
  if (!sessionProxies.has(sessionId)) {
    const proxy = proxies[Math.floor(Math.random() * proxies.length)];
    sessionProxies.set(sessionId, proxy);
  }
  return sessionProxies.get(sessionId);
}

Health-Based Rotation

Health-based proxy rotation monitors proxy health and switches proxies when one fails or becomes unresponsive. It ensures your test suite isn’t blocked by a single bad proxy, improving reliability and coverage by automatically removing bad proxies from your pool.

Here's a simple example that tags bad and good proxies based on specific criteria.

let healthyProxies;
(async () => {
  healthyProxies = await isHealthyProxies(proxy_list);
})();

const getHealthyProxy = () => {
  return healthyProxies[Math.floor(Math.random() * healthyProxies.length)];
};

const markProxyBad = (badProxy) => {
  healthyProxies = healthyProxies.filter((p) => p !== badProxy);
};

To improve proxy health check logic, you can use an asynchronous method from Axios to ensure proxies are available before use.

For example, the following code pings a test URL through each proxy in parallel using asynchronous requests, and returns only the healthy ones. This approach not only ensures that only available proxies are used, but also makes the process much faster and more scalable than checking proxies one by one.

const axios = require('axios');
const { URL } = require('url');

const checkProxy = async (proxyUrl) => {
    try {
        const parsed = new URL(proxyUrl);
        await axios.get('https://httpbin.org/ip', {
            proxy: {
                host: parsed.hostname,
                port: parseInt(parsed.port, 10),
                protocol: parsed.protocol.replace(':', ''),
            },
            timeout: 5000,
        });
        return { proxy: proxyUrl, healthy: true };
    } catch (err) {
        return { proxy: proxyUrl, healthy: false };
    }
};

const checkProxies = async (proxyList) => {
    const results = await Promise.all(proxyList.map(checkProxy));
    return results.filter((r) => r.healthy);
};

Time-Based Rotation

Time-based rotation changes the Playwright proxy after a set interval, regardless of the number of test cases executed. The following example rotates the proxy after 5 minutes.

let currentProxy = proxies[0];
setInterval(() => {
  currentProxy = proxies[Math.floor(Math.random() * proxies.length)];
}, 300000); // Rotate every 5 minutes

Request-Count-Based Rotation

Request-count-based rotation switches to a new proxy after a specified number of test actions or browser sessions. This strategy is helpful when running load tests to avoid triggering rate limits or temporary bans. For instance, the following function returns the request count for each proxy.

let requestCount = 0;
let proxyIndex = 0;
const getProxyByRequestCount = (proxies, maxRequestsPerProxy) => {
  if (requestCount % maxRequestsPerProxy === 0) {
    proxyIndex = (proxyIndex + 1) % proxies.length;
  }
  requestCount++;
  return proxies[proxyIndex];
};

Geo-Location-Based Proxy Rotation

This method involves rotating proxies based on their geographical origin (e.g., country, city, or region). It's particularly useful for geolocation testing, allowing teams to observe how a web application behaves for users in different locations. It also helps verify regional content delivery, local compliance, and feature availability specific to certain geographies.

Here's an example that manually obtains regional proxies from a master pool:

const geoProxies = {
  US: ['http://us-proxy1:3128', 'http://us-proxy2:3128'],
  UK: ['http://uk-proxy1:3128'],
  JP: ['http://jp-proxy1:3128', 'http://jp-proxy2:3128']
};

const getGeoProxy=(region) => {
  const proxies = geoProxies[region];
  if (!proxies || proxies.length === 0) throw new Error('No proxies for region');
  return proxies[Math.floor(Math.random() * proxies.length)];
}

// Usage:
const proxyForJapan = getGeoProxy('JP');
const proxyForUS = getGeoProxy('US');

Third-Party Proxy Rotators

External proxy rotators and some dedicated proxy services handle the rotation logic to centralize proxy management. This means you can point your test automation script to a single Playwright proxy endpoint, and the service will handle IP rotation under the hood.

How to Test Behind a Proxy With Playwright?

Let's see a simple scenario by running an automation test in a specific region, like the US. To do this, ensure you have a valid Playwright proxy that originates from the target region.

Before we begin, create the following files in your tests directory:

  • local_regional.spec.js
  • remote_regional.spec.js
  • setup.js

The code structure should look like this:

playwright_proxy
├─ examples
├─ .env
├─ package-lock.json
├─ package.json
├─ setup.js
└─ tests
   ├─ local_regional.spec.js
   └─ remote_regional.spec.js

Here's the local_regional.spec.js file for testing with a proxy in Playwright in a local environment:

const { chromium, expect, test } = require("@playwright/test");

test("should use a proxy", async () => {
  const browser = await chromium.launch({
    proxy: {
      server: "http://us_proxy_server:port",
    },
  });

  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto("https://httpbin.org/ip");
  const content = await page.textContent("body");
  console.log(content);
  expect(content).toContain("origin");

  await browser.close();
});

Code Walkthrough:

  • Import the Libraries: Import the packages required to initiate the Playwright test. These include chromium, expect, and test.
  • Set the Proxy: Launch a Chromium browser instance locally and set the proxy server with this instance. This allows the browser instance to use the proxy server in requests.
  • Open the Test Site: Create a new browser context and page. Then, navigate to the website under test.
  • Assert and Log the Content: Log the website's content to confirm that the proxy was successfully deployed. A result showing the proxy URL confirms that Playwright used the specified proxy for the request.

Test Execution:

Run the following command to execute the test:

npx playwright test
test execution for each-browser

How to Run Playwright Test Behind a Proxy With LambdaTest?

We'll now execute the simple regional test using the provided geo-location feature provided by LambdaTest.

LambdaTest is a cloud testing platform that allows you to run automated tests at scale on a Playwright automation cloud across 50+ browsers and OS combinations.

You can also check this guide on Playwright testing with LambdaTest.

Step 1: To get started with LambdaTest, follow the steps below:

  • Set LambdaTest Credentials: Configure your Username and Access Key as environment variables. You can find them under Account Settings → Password & Security in your LambdaTest dashboard.
  • Generate Capabilities: Use the LambdaTest Automation Capabilities Generator to generate capabilities for your test environment, including OS, browser type, and browser version.
  • Connect via WebSocket Endpoint: Use the LambdaTest Playwright wsEndpoint: wss://cdp.lambdatest.com/playwright?capabilities.

Here is the setup.js file that configures and runs Playwright tests on LambdaTest.

const capabilities = {
  browserName: "Chrome",
  browserVersion: "latest",
  "LT:Options": {
    platform: "Windows 11",
    build: "Playwright Proxy",
    name: "Playwright Proxy Test",
    user: process.env.LT_USERNAME,
    accessKey: process.env.LT_ACCESS_KEY,
    network: true,
    video: true,
    console: true,
    tunnel: false,
    geoLocation: "US",
    playwrightClientVersion: playwrightClientVersion,
  },
};

exports.test = require("@playwright/test").test.extend({
  page: async ({ page }, use, testInfo) => {
    // Check if LambdaTest config is set
    if (process.env.executeOn !== "local") {
      const browser = await chromium.connect({
        wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(
          JSON.stringify(capabilities)
        )}`,
      });

Code Walkthrough:

  • Define Browser Capabilities: Set up capabilities with browser name, version, OS, and LT:Options and user credentials. Importantly, the geoLocation capability ensures the test runs in the desired location (the US, in this case) automatically.
  • Extend Playwright's test fixture: The test.extend() overrides the default page fixture and conditionally runs the test on LambdaTest or locally based on process.env.executeOn.
  • Switch Between Local and Cloud execution: If executeOn isn't set to "local", the test connects to LambdaTest Playwright grid using WebSocket and the defined capabilities. Otherwise, it runs locally.
  • Send Test Status to LambdaTest: At the end of the remote test run, retrieve the result from testInfo and send a custom command (window.lambdatest_action) to update the test status (pass/fail and error message) on the LambdaTest Web Automation dashboard.

Step 2: Create the test script inside the remote_regional.spec.js file as shown below:

const { test } = require("../setup");
const { expect } = require("@playwright/test");

test("should use a proxy", async ({ page }) => {
  await page.goto("https://httpbin.org/ip");
  const content = await page.textContent("body");
  console.log(content);
  expect(content).toContain("origin");
});

Code Walkthrough:

  • Import the Required Libraries: In addition to the expect package, import the custom setup from the setup.js file. This points the test to the LambdaTest cloud grid configuration.
  • Open the Website: Launch the website under test and log its content to ensure that the proxy address has changed.

Note: Since Playwright uses a LambdaTest WSS endpoint, which is a pre-connected instance, you don't have direct control over proxy settings. However, you can achieve it by using the geoLocation capability or setting the dedicatedProxy capability to true. If you still want to bring your own proxy, you can set it up via the LambdaTest Tunnel and route your request through that Tunnel.

Test Execution:

Run the above test suites using the following command:

npx playwright test

Visit the LambdaTest Web Automation dashboard to view the Playwright test results:test execution for each-browser

Advanced Playwright Proxy Techniques

Playwright proxy environment extends beyond rotation and context settings. Let’s take a look at advanced proxy techniques in Playwright.

Handling Proxy Authentication

Proxy authentication requires providing authentication credentials to access a proxy server. Most paid proxy providers require credentials in the form of a username and a password, usually passed along with the proxy address.

To use authenticated proxies in Playwright, expand the server option with the credential flags, as shown below:

const { chromium, expect, test } = require("@playwright/test");

test("should use a proxy", async () => {
  const browser = await chromium.launch({
    proxy: {
      server: "http://proxy_address:port",
      username: "proxy_username",
      password: "proxy_password",
    },
  });

  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto("https://httpbin.org/ip");
  const content = await page.textContent("body");
  console.log(content);
  expect(content).toContain("origin");

  await browser.close();
});

Geo-Specific Proxy Configuration

Geo-specific proxy configuration involves routing test traffic through IP addresses located in specific geographic regions. This technique is commonly used to:

  • Simulate user behavior from a particular country or city.
  • Test region-specific content, pricing, or localization.
  • Bypass geo-restrictions or content blocks.
  • Improve accuracy in geo-targeted data delivery and validation.

The following example dynamically switches Playwright proxy location from an array of countries:

const { chromium, expect, test } = require("@playwright/test");

// Define region-based proxies
const regionProxies = {
  US: "http://142.111.48.253:7030",
  UK: "http://51.158.123.35:8811",
  DE: "http://195.201.123.45:3128",
};

async function runWithGeoProxy(region) {
  const proxyServer = regionProxies[region];

  const browser = await chromium.launch({
    proxy: {
      server: proxyServer,
    },
  });

  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto("https://httpbin.org/ip");
  const content = await page.textContent("body");

  console.log(`Proxy region: ${region}`);
  console.log(content);

  expect(content).toContain("origin");

  await browser.close();
}

// Run the test with a specific region
test("should use geo-specific proxy (US)", async () => {
  await runWithGeoProxy("US");
});

Integrating Proxies With Playwright MCP

If you use the Playwright MCP via Claude, Cursor, or any other AI platform, you can explicitly configure it with a proxy server.

Let's see how to achieve this with Claude. Go to Claude's installation location on your machine and open the desktop configuration file (claudedesktopconfig.json) with a code editor.

Include the --proxy-server flag in the args, as shown below:

{
    "mcpServers": {
        "playwright": {
            "command": "npx",
            "args": [
                "@playwright/mcp@latest",
                "--proxy-server=http://username:password@proxy_address:port"
            ]
        }
    }
}

Save the file after modifying it. Then, restart any existing Claude desktop instance. You've now set up a proxy for your Playwright MCP server. All new automation requests will go through this proxy henceforth.

Best Practices for Setting Up Proxies With Playwright

When setting up proxies in Playwright, it’s important to follow certain best practices for reliability and security.

  • Understand Your Use Case: Identify why your team needs a proxy, whether for geolocation testing, bypassing network restrictions, or simulating user behavior from different regions.
  • Choose the Right Proxy Type: Decide between HTTP, HTTPS, or SOCKS proxies based on your testing requirements and the level of anonymity or security needed.
  • Use Secure and Reliable Proxies: Opt for reputable proxy providers to ensure stability, speed, and privacy. Avoid free or untrusted proxies to minimize downtime and data leaks.
  • Handle Proxy Authentication Carefully: Store proxy credentials in environment variables or secret managers rather than hardcoding them. This protects sensitive data and supports safer collaboration.
  • Manage Proxy Rotation: For large-scale or scraping tests, implement proxy rotation to avoid IP bans and distribute requests evenly. Use sticky proxies to persist a single IP for a particular session.
  • Monitor Proxy Performance: Regularly check proxy speed and reliability. Integrate health checks in your test setup to flag slow or failing proxies early.
...

Conclusion

Using Playwright proxies helps you simulate real-world conditions, control network traffic, and validate application behavior across regions. You can configure proxies, apply rotation strategies, and test behind them locally or on cloud platforms like LambdaTest.

Advanced techniques such as geo-targeting and authentication handling enhance test reliability. Always secure credentials, use dedicated proxy pools, and capture network logs for debugging. A well-configured Playwright proxy environment ensures consistent, scalable, and accurate test execution across different environments.

Citations

Frequently Asked Questions (FAQs)

How does Playwright proxy differ from a system proxy?
A Playwright proxy applies only to browser sessions created by Playwright. It controls request routing within automated tests, while a system proxy affects all outgoing network traffic on the machine. This ensures isolated and controlled testing conditions.
Can different proxies be assigned to each Playwright test?
Yes. Separate browser contexts can be configured with individual proxy settings. This allows parallel testing across multiple IPs or regions, useful for geo-validation, load testing, and avoiding rate limits during high-volume automated runs.
How can a proxy be authenticated in Playwright?
Authentication credentials can be passed directly within the proxy configuration object using username and password fields. Playwright automatically handles the proxy handshake and ensures secure connection establishment during test execution.
Can Playwright rotate proxies automatically?
Playwright doesn’t rotate proxies by default. Proxy rotation can be implemented by dynamically updating the proxy configuration for each test or session, integrating a proxy pool API, or using external rotation services.
Does Playwright support SOCKS proxies?
Yes. Playwright supports both HTTP and SOCKS proxies. The proxy protocol can be specified in the configuration, allowing advanced routing for tests that require encrypted tunneling or non-standard network environments.
How is network traffic captured when using a Playwright proxy?
Requests and responses in Playwright can be intercepted using page.on('request') and page.on('response') events. Combined with a proxy, this enables detailed inspection and debugging of traffic between test scripts and the target server.
Can Playwright proxy settings work with LambdaTest?
Yes. When running tests on LambdaTest’s cloud grid, proxy details can be added to the capability configuration. This setup allows testing from specific regions and controlled network routing for consistent cross-environment validation.
How do proxies support geo-location testing in Playwright?
Proxies route traffic through servers in specific regions, simulating real users from those locations. This helps validate location-based content delivery, localized UI behavior, and compliance with region-specific configurations.
What is the best way to handle proxy failures in Playwright tests?
Network errors can be captured using Playwright’s event listeners, allowing retry logic or proxy rotation when connections fail. Logging proxy responses also helps identify unstable endpoints or authentication issues.
Can proxy usage be combined with VPN testing in Playwright?
Yes, but they should be isolated. A proxy manages browser-level routing, while a VPN handles system-level connections. Keeping them separate ensures predictable and reproducible test behavior across environments.

Did you find this page helpful?

Helpful

NotHelpful

More Related Hubs

ShadowLT Logo

Start your journey with LambdaTest

Get 100 minutes of automation test minutes FREE!!