Supercharge QA with AI for Faster & Smarter Software Testing

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
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.
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.
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:
npm init playwright@latestOnce the above steps are done, you can use these methods: global proxy configuration and context-specific 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();
})();
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: Run Playwright tests across 50+ browser environments. Try LambdaTest Now!
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 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;
}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 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 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 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 minutesRequest-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];
};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');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.
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:
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.jsHere'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:
Test Execution:
Run the following command to execute the test:
npx playwright test
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:
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:
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:
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 testVisit the LambdaTest Web Automation dashboard to view the Playwright test results:
Playwright proxy environment extends beyond rotation and context settings. Let’s take a look at advanced proxy techniques in Playwright.
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 involves routing test traffic through IP addresses located in specific geographic regions. This technique is commonly used to:
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");
});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.
When setting up proxies in Playwright, it’s important to follow certain best practices for reliability and security.
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.
Did you find this page helpful?
More Related Hubs
Start your journey with LambdaTest
Get 100 minutes of automation test minutes FREE!!