All posts

Playwright connectOverCDP hosted browser: Setup

Playwright connectOverCDP hosted browser setup: pass a wss:// URL to chromium.connectOverCDP() and set timeout past 30 seconds. Get code for JS and Python.

  • playwright
  • connectovercdp
  • hosted browser
  • cdp
  • puppeteer
On this page

With a Playwright connectOverCDP hosted browser, you pass a wss://api.wayfern.com/ws?token=LINK_TOKEN URL to chromium.connectOverCDP() and Playwright drives a hosted browser. Set timeout above its 30-second Playwright default, because a cold start takes about 45 to 50 seconds.

This setup is for developers whose Playwright flow already runs against local Chrome with remote debugging on, at http://localhost:9222, and now has to run from a hosted browser with a chosen exit. A Playwright connectOverCDP hosted browser swaps that localhost endpoint for a wss URL carrying a token.

Wayfern’s anti-detect browser sessions page lists what the alternative costs you: running your own browsers means a pool, upgrades, driver versions and proxy wiring. This guide shows how to connect a Playwright connectOverCDP hosted browser, size the timeout, pick an exit, close cleanly and choose a transport.

Key Takeaways

  • An unknown country or region is refused with close code 4007, not rerouted to another exit.
  • Browser time costs 8 credits per open-page hour, metered per second, with a 60-second minimum per page (pricing).
  • connectOverCDP() is Chromium-only and lower fidelity than browserType.connect(), per Playwright’s BrowserType docs.

How do you use Playwright connectOverCDP with a hosted browser?

You use Playwright connectOverCDP with a hosted browser by passing the hosted wss:// URL as the first argument of chromium.connectOverCDP(). Playwright’s BrowserType reference describes endpointURL as “A CDP websocket endpoint or http url to connect to.”

Illustration for How do you use Playwright connectOverCDP with a hosted browser?

The endpointURL entry in the options object is deprecated, so pass the URL positionally. The options object still takes headers, slowMo and timeout.

  1. Export your link token. Set WF_TOKEN in your environment. The URL is wss://api.wayfern.com/ws?token=LINK_TOKEN, and you can add country=US or session=run42 to it.
  2. Raise the connect timeout. A remote start can outlast the 30-second default, so a healthy connection can fail. The examples use 90 seconds.
  3. Connect with Playwright (JS).
import { chromium } from "playwright";

const url = `wss://api.wayfern.com/ws?token=${process.env.WF_TOKEN}&country=US`;
const browser = await chromium.connectOverCDP(url, { timeout: 90_000 });
const page = await browser.contexts()[0].newPage();
await page.goto("https://example.com/login");
  1. Connect with Playwright (Python). The method is connect_over_cdp, and the timeout is in milliseconds.
import os
from playwright.sync_api import sync_playwright

url = f"wss://api.wayfern.com/ws?token={os.environ['WF_TOKEN']}&country=US"
with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(url, timeout=90_000)
    page = browser.contexts[0].new_page()
    page.goto("https://example.com/login")
  1. Connect with Puppeteer. The same URL goes into the browserWSEndpoint option of puppeteer.connect(), as Puppeteer’s ConnectOptions reference defines it.
import puppeteer from "puppeteer";

const browser = await puppeteer.connect({
  browserWSEndpoint: `wss://api.wayfern.com/ws?token=${process.env.WF_TOKEN}&country=US`,
});
const page = await browser.newPage();
await page.goto("https://example.com/login");

Success looks like a page that navigates after the wait. If the call times out at 30 seconds, the default timeout is still in place. A wrong or revoked token closes the socket instead of starting a session.

In a Playwright connectOverCDP hosted browser setup, the wss URL plays the role of the browser-level endpoint a local Chrome would give you. It arrives already resolved, with the token and exit parameters in the query string. The Wayfern quickstart covers token setup.

What does a hosted anti-detect browser change over CDP?

A hosted anti-detect browser is a Chromium build that applies a browser identity (fingerprint) inside the build while you drive it over CDP. Your Playwright or Puppeteer code runs normally, and nothing is injected into your pages.

The browser runs headed on a virtual display (Xvfb) in linux-x64 containers. Your code sends the same page.goto() and locator.click() calls it would send to local Chrome.

What changes is how state has to be handled. The same page puts it this way: “A cookie issued to one IP and replayed from another is an easy signal for a site to read.”

If a login cookie is issued on one exit and your next step arrives from a different one, the site sees two locations for one session. The identity, cookie jar, storage and exit IP have to stay consistent for the whole flow.

The cookie jar and storage stay live while the socket is open. Keep one socket for the whole flow, and set country and session once on the URL.

How do you set country, session, proxy and viewport on the /ws URL?

You set the exit, sticky session, proxy and window size as query parameters on the /ws URL, and the hosted browser applies them when the socket opens. The full parameter list is in the Wayfern API reference.

  1. Choose the exit. With no location parameters you get the default datacenter exit, and its egress is free. Residential bandwidth is metered, so check Wayfern’s pricing before a long run.
  2. Pin a sticky session. Add session=run42 to hold one residential IP for the whole flow. Use the same id for every step so the cookie and the IP stay together.
  3. Pick the proxy mode. proxy=own|residential|none chooses the route per connection. Save your own proxy on the link (http, https or socks5, with proxyMode set to own).
  4. Protect proxy credentials. The password is encrypted at rest, so credentials never go in the URL, and own-proxy traffic isn’t metered as residential bandwidth.
  5. Size the window. Set width and height in whole CSS pixels, from 500 to 3600 wide and 400 to 1900 high.

One URL can carry the exit, the session and the window size:

import { chromium } from "playwright";

const url =
  "wss://api.wayfern.com/ws?token=LINK_TOKEN" +
  "&country=US&region=CA&session=run42&width=1366&height=768";
const browser = await chromium.connectOverCDP(url);

This pins a California residential exit for the whole run and opens a 1366 by 768 window.

Expect a refusal on a bad location. Wayfern checks every code against a live catalog before handing over the browser. An unknown location closes the socket with code 4007 and doesn’t fall back to another exit, so fix the code and reconnect.

Mint a link token and run that URL from your own script to confirm the exit and window size.

How do contexts, browser.close() and billing work on a remote CDP session?

On a remote CDP session, browser.contexts()[0] is the default context the hosted browser already holds, browser.close() ends your connection, and the meter keeps running for as long as a page stays open.

  1. Reuse the default context for a logged-in flow. Take browser.contexts()[0] when you want the session’s identity, cookies and storage. A context made with newContext() on each step starts without the cookie jar you built earlier.
  2. Call newContext() only for isolation, when two tasks must not share cookies or storage but can share one socket.
  3. Close in a finally block. Close pages, then the browser, even when a step throws.
  4. Confirm the instance is gone. Your browser.close() ends only your own connection, so check that no other worker still holds a socket on the same token.
import { chromium } from "playwright";

// Size the timeout above the cold start.
const browser = await chromium.connectOverCDP(
  "wss://api.wayfern.com/ws?token=LINK_TOKEN",
  { timeout: 120_000 },
);
try {
  const page = await browser.contexts()[0].newPage();
  await page.goto("https://example.com/login");
  // ...your steps...
  await page.close();
} finally {
  await browser.close();
}

Playwright’s Browser reference says browser.close() on a connected browser “clears all created contexts belonging to this browser and disconnects from the browser server.” It detaches you rather than killing a process you own.

Skipping step 3 has a direct cost. Wayfern’s pricing page lists browser time at 8 credits per open-page hour, metered per second with a 60-second minimum per page. A leaked socket or an open page keeps accruing until the connection closes.

A zero balance is a hard stop: calls are refused and open sessions are closed. Auto top-up stays off until you turn it on.

Session replays are optional (Record sessions is off by default) and cost no credits.

Why does a Playwright connectOverCDP hosted browser connection fail?

A connectOverCDP() call against a hosted browser can fail in several ways, and each one has a different signature. A timeout and a closed socket point to different fixes.

SymptomLikely causeFix
Timeout error after 30 seconds, no socket messageDefault timeout is shorter than the cold startPass timeout: 90000
Socket closes with code 4007Unknown country or region, refused instead of reroutedCheck the code against the location catalog in /docs/api
Handshake refused with a token you used yesterdayLink token expired or was revokedMint a new token on the project’s browser links
Extra connections refused while others runLink token cap (1 to 100, default 10) or plan concurrencyRaise the cap or see /docs/limits
Sessions closed mid-runCredit balance hit zero, which closes open sessionsAdd credits or turn on auto top-up
Credits drain after the script endsOrphaned socket or open pageClose pages and the browser in finally

4007 is the only documented close code among these failures. Don’t retry it, because the location won’t become valid on the second attempt.

The connection code retries timeouts with backoff and runs the whole flow on one socket:

import { chromium } from "playwright";
const url = `wss://api.wayfern.com/ws?token=${process.env.LINK_TOKEN}`;

async function connect(tries = 3) {
  for (let i = 0; i < tries; i++) {
    try {
      return await chromium.connectOverCDP(url, { timeout: 90000 });
    } catch (err) {
      if (i === tries - 1) throw err;
      await new Promise((r) => setTimeout(r, 2000 * 2 ** i));
    }
  }
}

const browser = await connect();
try {
  const page = await browser.contexts()[0].newPage();
  // run every step of the flow on this one socket
  await page.close();
} finally {
  await browser.close();
}

One socket per flow avoids paying the cold start per step and keeps you under the connection cap. The finally block closes the last connection, which stops the meter.

Playwright connectOverCDP vs connect: which one for a hosted browser?

For a hosted browser you reach through a CDP WebSocket, connectOverCDP() is the Playwright call to use, because connect() needs a Playwright server you run yourself.

CriterionHosted browser over CDPconnect()Own Chrome, remote debuggingWeb Data API scrape
What you runNothing, you pass a wss:// URLA Playwright server from launchServerChrome started with --remote-debugging-portNothing, one POST
State kept between stepsYes, while the socket is openYesYesNo
Playwright version matchNoYesNoNo
Protocol fidelityLower than connect()Playwright protocolLower than connect()Not applicable

Playwright’s BrowserType reference states the limit directly: “This connection is significantly lower fidelity than the Playwright protocol connection via browserType.connect().”

It also says that connecting over the Chrome DevTools Protocol “is only supported for Chromium-based browsers.” If something advanced misbehaves over CDP, connect() is the documented fallback.

connect() attaches to a browser started with BrowserType.launchServer in Node.js, and the docs say the connecting Playwright instance “needs to match the version of Playwright that launches the browser.” A rented browser that exposes only a CDP WebSocket can’t meet that, so lower fidelity is the price of a hosted Chromium.

A scrape endpoint is the other option. Wayfern’s anti-detect browser sessions page puts it this way: “A request/response endpoint returns one page and keeps nothing.” That suits a single fetch and fails a login that spans several steps.

Choose by the job:

  1. Multi-step logged-in flows with a chosen exit, where cookies, storage and exit IP must stay together: use a hosted browser over CDP.
  2. One page in, one result out, with nothing to persist: call the Web Data API (pages versus sessions, compared).
  3. Debugging and local development on a machine you own: start Chrome with remote debugging and attach over CDP.
  4. Infrastructure you operate, with matching Playwright versions on both ends and full protocol fidelity: use connect().

What does a hosted anti-detect browser not do?

A hosted anti-detect browser leaves out most of what a desktop profile manager gives a person: named profiles, saved cookie jars and per-vector fingerprint control. Wayfern’s comparison with Multilogin lists the gaps: “no named profiles, no cookie import or export, no per-vector fingerprint switches”.

Three more limits follow from how the browser works:

  • No mobile emulation. Per Wayfern’s API reference, phone sizes aren’t offered because the browser presents a desktop device.
  • Chromium only. Firefox and WebKit engines aren’t available over CDP.
  • No state between runs. Cookies and storage live only while the socket is open, so keep what you need yourself.

Playwright’s own API carries state from one run to the next. BrowserContext.storageState() “Returns storage state for this browser context, contains current cookies” and local storage.

The storageState option of browser.newContext() “Populates context with given storage state.” Read the state before you close, and feed it back on the next run:

import fs from "node:fs/promises";
import { chromium } from "playwright";

const url =
  "wss://api.wayfern.com/ws?token=LINK_TOKEN&country=US&session=run42";
const browser = await chromium.connectOverCDP(url, { timeout: 90_000 });

const saved = await fs.readFile("state.json", "utf8").catch(() => null);
const context = await browser.newContext(
  saved ? { storageState: JSON.parse(saved) } : {},
);
const page = await context.newPage();
// ...your logged-in flow...

await fs.writeFile("state.json", JSON.stringify(await context.storageState()));
await browser.close();

Keep the exit unchanged between runs, with the same country and the same session id, so a restored jar doesn’t come back from a new IP. Treat state.json as a credential and store it accordingly.

If a person manages many long-lived profiles by hand, buy a desktop profile manager. Multilogin gives far more per-vector control than Wayfern does.

Frequently asked questions

How do I use Playwright connectOverCDP with a hosted browser?

Pass the hosted WebSocket URL, for example wss://api.wayfern.com/ws?token=LINK_TOKEN, to chromium.connectOverCDP(). Per the Wayfern docs, opening the socket starts the session, so no create-session call is needed. Set timeout above the Playwright 30-second default, then close the browser when you’re done.

Does browser.close() shut down a hosted browser?

In Playwright, browser.close() detaches your connection from a remote browser.

Can I use Python or Puppeteer instead of Node Playwright?

Python’s connect_over_cdp and Puppeteer’s puppeteer.connect with browserWSEndpoint both accept the same wss:// URL. Only the client library changes, and the query parameters stay the same.

Why does connectOverCDP time out on the first connection?

A remote start can take longer than the default connect timeout. Pass a larger timeout, such as 60000, on the first connection.

Can I use Firefox or a mobile device profile?

Neither is available. connectOverCDP() works only with Chromium-based browsers, and the hosted browser presents a desktop device, so phone sizes aren’t offered.

What should you do next with a Playwright connectOverCDP hosted browser?

The next step is one working connection, then one real flow, then a capacity check.

Today, connect with connectOverCDP() using a fresh link token and a connect timeout raised above the cold start, and load one page.

This week, pick an exit and a sticky session for one real flow. Wrap it in try/finally, and save and restore storageState in your own code, since there are no saved cookie jars to lean on.

This month, check your concurrency against /docs/limits. Then decide between a hosted CDP browser, the Web Data API and your own Chrome.

Wayfern has no free tier or free trial. The cheapest self-serve options are the Developer plan or a credit pack, both listed on pricing.

Start from the quickstart: get a link token, connect over CDP and scrape your first page.

Sources

Developer Docs - Browser, Web Data API & MCP | Wayfern · Anti-Detect Browser Sessions over CDP | Wayfern · Pricing - Credits for Browsers & the Web Data API | Wayfern · BrowserType | Playwright · ConnectOptions | Puppeteer · Wayfern API reference · Browser | Playwright · Wayfern API reference. Every other source is linked where the article cites it.

See us more often in Google

One click marks Wayfern as a preferred source in Google, so our posts can show up more often in your Top Stories, AI Mode and AI Overviews.