# Integrating Puppeteer &amp; Playwright with XProxy

> For AI tools: this is the Markdown copy of https://xproxy.io/document/integrating-puppeteer-playwright-with-xproxy. Every XProxy guide has one at its URL + `.md`; the index of all guides is https://xproxy.io/llms.txt.

Send Puppeteer and Playwright browsers through XProxy with a login, and change the IP from code.

Send Puppeteer and Playwright browsers through an XProxy mobile proxy, with a login, and change the IP from your code.

In short

**Proxy in the launch options**

Give the browser the proxy address when you start it. Playwright also takes the username and password there.

**New IP from code**

Call one URL on your panel before you open the page. The modem gets a new IP in a few seconds.

**Easy to check**

Open an IP page and print it. It must match the **Public IP** of that proxy in your panel.

**You need:** Node.js (or Python for Playwright) with Puppeteer or Playwright installed, and an XProxy panel with a working modem.

## Get your proxy

In your XProxy panel open **Proxy Management** and click **Export Proxy**. Pick the **Plain HTTP** preset with `user:pass@host:port`, turn on **Scheme prefix** and click **Copy All**. Each line is one proxy, for example `http://USERNAME:PASSWORD@192.168.1.10:4001`. The port is the one shown for that modem in **Proxy Management**.

The address must work from the computer that runs your code: see [how to copy a proxy in the right format](https://xproxy.io/document/how-use-proxy-format-http-socks5).

In the code below, the address is `http://192.168.1.10:4001` and the login is `USERNAME` and `PASSWORD`.

## Open a page through XProxy

**Puppeteer (Node.js)**

```
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    args: ['--proxy-server=http://192.168.1.10:4001'], // from Export Proxy
  });
  const page = await browser.newPage();
  await page.authenticate({ username: 'USERNAME', password: 'PASSWORD' });
  await page.goto('https://api.ipify.org?format=json');
  console.log(await page.evaluate(() => document.body.innerText)); // {"ip":"..."}
  await browser.close();
})();
```

Chromium cannot take a username and password inside `--proxy-server`, so the code calls `page.authenticate()`. Use the **HTTP** address, not SOCKS5.

**Playwright (Node.js)**

```
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({
    proxy: {
      server: 'http://192.168.1.10:4001', // from Export Proxy
      username: 'USERNAME',
      password: 'PASSWORD',
    },
  });
  const page = await browser.newPage();
  await page.goto('https://api.ipify.org?format=json');
  console.log(await page.innerText('body')); // {"ip":"..."}
  await browser.close();
})();
```

Using the Whitelist IP login instead of a password? Leave out `username` and `password`.

**Playwright (Python)**

```
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(
        proxy={
            "server": "http://192.168.1.10:4001",  # from Export Proxy
            "username": "USERNAME",
            "password": "PASSWORD",
        }
    )
    page = browser.new_page()
    page.goto("https://api.ipify.org?format=json")
    print(page.inner_text("body"))  # {"ip":"..."}
    browser.close()
```

## Change the IP from code

Position **1** is the first modem, the one on port **4001** when the starting port is 4000. The code calls the rotation API, then asks the panel for the modem's status until it says `MODEM_READY`. All calls are in [How to change / rotate IP](https://xproxy.io/document/how-change-rotate-ip).

**Panel asks for a login?** If **Force API Auth** is on, these calls need your dashboard login: add `auth=("USER", "PASS")` to each `requests.get`.

**Node.js**

```
const PANEL = 'http://192.168.1.10'; // your XProxy panel address
const POSITION = 1; // the Pos number in Proxy Management
const PROXY_ADDR = '192.168.1.10:4001'; // host:port of the same modem

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Ask the modem for a new IP, then wait until it is back online.
async function rotateIp(timeoutMs = 60000) {
  const res = await fetch(`${PANEL}/api/v1/rotate_ip/position/${POSITION}`);
  const data = await res.json();
  if (!res.ok || !data.status) throw new Error(`Rotation refused: ${JSON.stringify(data)}`);
  await sleep(3000); // the modem reconnects in a few seconds
  const end = Date.now() + timeoutMs;
  while (Date.now() < end) {
    const s = await (await fetch(`${PANEL}/status?proxy=${PROXY_ADDR}`)).json();
    if (s.msg === 'MODEM_READY') return s.public_ip;
    await sleep(1000);
  }
  throw new Error('The modem did not come back in time');
}

rotateIp().then((ip) => console.log('New IP:', ip));
```

Needs Node.js 18 or newer (built-in `fetch`). Call `await rotateIp()` before `page.goto()` to start each run on a new IP.

**Python**

```
import time

import requests

PANEL = "http://192.168.1.10"      # your XProxy panel address
POSITION = 1                       # the Pos number in Proxy Management
PROXY_ADDR = "192.168.1.10:4001"   # host:port of the same modem

def rotate_ip(timeout=60):
    """Ask the modem for a new IP, then wait until it is back online."""
    r = requests.get(f"{PANEL}/api/v1/rotate_ip/position/{POSITION}", timeout=10)
    r.raise_for_status()
    if not r.json().get("status"):
        raise RuntimeError(f"Rotation refused: {r.text}")
    time.sleep(3)  # the modem reconnects in a few seconds
    deadline = time.time() + timeout
    while time.time() < deadline:
        s = requests.get(f"{PANEL}/status", params={"proxy": PROXY_ADDR}, timeout=10).json()
        if s.get("msg") == "MODEM_READY":
            return s.get("public_ip")
        time.sleep(1)
    raise TimeoutError("The modem did not come back in time")

print("New IP:", rotate_ip())
```

Needs `pip install requests`. Call `rotate_ip()` before `page.goto()` to start each run on a new IP.

## Check it works

1. Run a script above. It prints an IP address.
2. In **Proxy Management**, look at the **Public IP** of that proxy (marked 1). It is the same IP.
3. Run the rotate script, then the first script again. The IP is new.

![Proxy Management table with the Public IP of the first proxy marked (demo data)](https://media1.xproxy.io/docs/integrations/int-publicip-v1.webp)

The Public IP your script should print. Demo data.

## Something not working?

| You see | What to do |
| --- | --- |
| 407 Proxy Authentication Required, or an authentication error | The username or password is wrong or missing. Copy the proxy again after saving **Proxy Settings → Login**. If the password has special characters such as `@` or `:`, URL-encode them in the proxy URL. |
| Connection refused or timed out | The address is not reachable from your computer. A **LAN only** address works only on your own network: use **Public address** or **VPS relay** ([public access](https://xproxy.io/document/how-public-access-xproxy)). Also check the port in **Proxy Management**. |
| The printed IP is your own IP | The request did not go through the proxy. Check that the proxy is passed to the request, the browser or the crawler, and that it is not set only for `http` or only for `https`. |
| The rotation call fails or says `status` is false | Check the position number and the panel address. If **Force API Auth** is on, add your dashboard login to the call. |
| The IP is the same after rotating | Sometimes the carrier gives the modem the same IP. Rotate again. The status call can also answer `COLLISION_IP` when **IP unchanged detect** is on in Rotation Settings. |
| The browser cannot connect and your proxy address starts with `socks5://` | Chromium cannot send a SOCKS5 username and password. Use the **HTTP** address of the proxy. |

## What next?

Change the IP on a timer, or copy your proxies in another format.

[Rotate IP: all ways →](https://xproxy.io/document/how-change-rotate-ip) [Proxy formats →](https://xproxy.io/document/how-use-proxy-format-http-socks5)

---

Source: https://xproxy.io/document/integrating-puppeteer-playwright-with-xproxy
