Playwright WebSocket API: connect() vs connectOverCDP() for Remote Browsers

How Playwright's remote browser connections work — connect() vs connectOverCDP(), auth headers, contexts, reconnection and a full error-handling example.

Spectrae team · · 8 min read

Most developers use Playwright to launch a local browser. That works fine on your laptop. But the moment you need to run automation in the cloud — or hand off the browser layer entirely — you need to understand what's happening under the hood.

Playwright has a built-in remote control capability that most teams never touch. It's been there for years, and once you understand how it works, running browsers somewhere other than your app server becomes easy.


How Playwright's WebSocket protocol actually works

There are two layers to keep apart.

Your Playwright client (the playwright package in your code) talks to a Playwright driver using Playwright's own protocol. The driver then talks to the browser using that browser's native automation protocol: the Chrome DevTools Protocol (CDP) for Chromium, and Playwright's patched protocols for Firefox and WebKit. When you call chromium.launch(), all of this happens on your machine, over local pipes.

When you call page.click(), the client sends a Playwright protocol message to the driver, and the driver turns it into the browser-level commands needed to click.

The key insight: the client and the driver don't have to be on the same machine. Playwright can run the driver and browser as a server and let clients connect over a WebSocket — as long as the Playwright versions are compatible.

What BrowserServer does

Playwright ships with a BrowserServer class that exposes a browser over a WebSocket endpoint. You can start one like this:

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

const server = await chromium.launchServer({
  port: 3000,
  headless: true,
});

console.log(server.wsEndpoint());
// ws://localhost:3000/uniquetoken...

That WebSocket URL is what remote clients use to connect. The server handles the browser-specific protocol. Your client code just talks Playwright. (npx playwright run-server does the same thing from the command line.)


chromium.connect() vs chromium.connectOverCDP() — when to use each

This is where most people get confused. There are two connection methods and they're not interchangeable.

Method Protocol Use case
chromium.connect(wsEndpoint) Playwright protocol Connecting to a Playwright BrowserServer
chromium.connectOverCDP(endpoint) Raw CDP Connecting to a Chrome instance (or a CDP endpoint) directly

Use chromium.connect() (or firefox.connect()) when you're connecting to a Playwright server. This is the right method for Spectrae's /standard/playwright and /stealth/playwright endpoints. The server speaks Playwright's protocol natively, so you get full API support — contexts, pages, locators, the works.

const browser = await chromium.connect('wss://browser.spectrae.dev/standard/playwright', {
  headers: { Authorization: `Bearer ${process.env.SPECTRAE_API_KEY}` },
});

Use chromium.connectOverCDP() when you're connecting to a raw Chrome instance that was started with --remote-debugging-port, or to a service's CDP endpoint (Spectrae's are /standard/cdp and /stealth/cdp). It's common for attaching to an already-running browser and for AI agent tools that only speak CDP. Playwright notes that CDP connections are lower fidelity than its own protocol.

// Connecting to chrome started with --remote-debugging-port=9222
const browser = await chromium.connectOverCDP('http://localhost:9222');

The practical difference: connectOverCDP gives you access to whatever contexts and pages already exist in the browser. connect() starts fresh — you get an empty browser to work with.

One hard constraint with connect(): the client's Playwright version must be compatible with the server's. A mismatch fails at connect time with a version error. Always pin your Playwright version when working with remote browsers — Spectrae currently runs Playwright 1.58.


Passing authentication in the connection URL

When connecting to a remote browser service, you need to authenticate. Playwright's connect() method accepts a headers option — HTTP headers sent with the WebSocket handshake. Spectrae accepts the API key as a Bearer token:

const browser = await chromium.connect('wss://browser.spectrae.dev/standard/playwright', {
  headers: {
    Authorization: `Bearer ${process.env.SPECTRAE_API_KEY}`,
  },
  timeout: 30000, // 30s connection timeout
});

Spectrae (like many services) also accepts the key in the URL itself, which is handy for tools that only take a URL:

// Key in the URL — convenient, but avoid logging this URL
const browser = await chromium.connect(
  `wss://browser.spectrae.dev/standard/playwright?key=${apiKey}`
);

The headers approach is cleaner. It keeps credentials out of URLs that end up in logs. Either way, the server checks the key before any browser starts.


Session lifecycle: connect, context, page, close

Understanding the lifecycle saves you from resource leaks. Here's how the layers stack:

Browser (1 remote connection)
  └── BrowserContext (isolated session)
       └── Page (individual tab)

Each layer is independent. A browser can hold many contexts. A context can hold many pages. Closing a page doesn't close the context. Closing the context doesn't close the browser.

The full lifecycle looks like this:

// 1. Connect to remote browser
const browser = await chromium.connect('wss://browser.spectrae.dev/standard/playwright', {
  headers: { Authorization: `Bearer ${process.env.SPECTRAE_API_KEY}` },
});

// 2. Create an isolated context (like an incognito window)
const context = await browser.newContext({
  userAgent: 'Mozilla/5.0 ...',
  viewport: { width: 1280, height: 720 },
});

// 3. Open a page
const page = await context.newPage();

// 4. Do work
await page.goto('https://example.com');
const title = await page.title();

// 5. Clean up in reverse order
await page.close();
await context.close();
await browser.close(); // disconnects from remote

Always close in reverse order. Closing the browser first orphans any open contexts and pages — the remote server may not clean them up immediately.


Running multiple contexts on one browser connection

This is the biggest cost-efficiency win people miss.

Each call to chromium.connect() opens a new browser session. On Spectrae, that's a new isolated browser, billed per second, and it counts toward your concurrent-session limit. Multiple contexts on the same connection share that one session.

Contexts are isolated — separate cookies, localStorage, and auth state. They're perfect for running multiple scrapers in parallel without cross-contamination.

const browser = await chromium.connect('wss://browser.spectrae.dev/standard/playwright', {
  headers: { Authorization: `Bearer ${process.env.SPECTRAE_API_KEY}` },
});

// Spin up 5 isolated scrapers on one browser connection
const tasks = Array.from({ length: 5 }, async (_, i) => {
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto(`https://example.com/item/${i}`);
  const data = await page.textContent('.price');

  await page.close();
  await context.close();

  return data;
});

const results = await Promise.all(tasks);
await browser.close();

This runs 5 parallel scrapes on a single session: one billing meter and one concurrent slot. The savings add up at scale.

The practical limit per browser depends on memory and how heavy the pages are. Start with a handful of contexts per connection and measure before pushing higher. One caveat for stealth work: contexts on one connection share the same browser, so they share its fingerprint. Use separate connections when you need separate identities.


Error handling and reconnection logic

Remote connections fail. Networks hiccup. Servers restart. Your code needs to handle this.

When a remote browser disconnects unexpectedly, in-flight calls reject with errors such as "Target page, context or browser has been closed", and the Browser emits a disconnected event. You can catch these and reconnect.

async function connectWithRetry(wsEndpoint, options, retries = 3) {
  for (let attempt = 1; attempt <= retries; attempt++) {
    try {
      const browser = await chromium.connect(wsEndpoint, options);

      // Listen for disconnect events
      browser.on('disconnected', () => {
        console.log('Browser disconnected unexpectedly');
      });

      return browser;
    } catch (err) {
      if (attempt === retries) throw err;

      const delay = attempt * 1000; // 1s, 2s, 3s
      console.log(`Connection attempt ${attempt} failed. Retrying in ${delay}ms...`);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

For page-level operations, wrap them in a try/finally to make sure cleanup always runs:

async function scrapePage(browser, url) {
  let context;
  let page;

  try {
    context = await browser.newContext();
    page = await context.newPage();
    await page.goto(url, { timeout: 30000 });
    return await page.textContent('body');
  } catch (err) {
    console.error(`Failed to scrape ${url}:`, err.message);
    throw err;
  } finally {
    await page?.close().catch(() => {});
    await context?.close().catch(() => {});
  }
}

The .catch(() => {}) on close calls is intentional. If the browser already disconnected, those close calls will throw too. You don't want an error in cleanup masking the original error.


Full code example with error handling

Here's a production-ready example that puts it all together:

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

const WS_ENDPOINT = 'wss://browser.spectrae.dev/standard/playwright';
const API_KEY = process.env.SPECTRAE_API_KEY;

async function scrapeWithRemoteBrowser(urls) {
  let browser;

  try {
    browser = await chromium.connect(WS_ENDPOINT, {
      headers: { Authorization: `Bearer ${API_KEY}` },
      timeout: 30000,
    });

    console.log('Connected to remote browser');

    const results = await Promise.allSettled(
      urls.map(url => scrapeUrl(browser, url))
    );

    return results.map((result, i) => ({
      url: urls[i],
      status: result.status,
      data: result.value ?? null,
      error: result.reason?.message ?? null,
    }));

  } finally {
    await browser?.close().catch(err => {
      console.error('Error closing browser:', err.message);
    });
  }
}

async function scrapeUrl(browser, url) {
  let context;
  let page;

  try {
    context = await browser.newContext({
      viewport: { width: 1280, height: 720 },
    });
    page = await context.newPage();

    // Block images and fonts to speed things up
    await page.route('**/*.{png,jpg,jpeg,gif,webp,svg,woff,woff2,ttf}', route => {
      route.abort();
    });

    await page.goto(url, {
      waitUntil: 'domcontentloaded',
      timeout: 20000,
    });

    const title = await page.title();
    const text = await page.textContent('body');

    return { title, textLength: text.length };

  } finally {
    await page?.close().catch(() => {});
    await context?.close().catch(() => {});
  }
}

// Run it
const urls = [
  'https://example.com/page-1',
  'https://example.com/page-2',
  'https://example.com/page-3',
];

scrapeWithRemoteBrowser(urls)
  .then(results => console.log(JSON.stringify(results, null, 2)))
  .catch(console.error);

Performance tips

A few patterns that make a real difference at scale:

Reuse contexts where possible. Creating a new context has some overhead. If you're scraping the same logged-in session across multiple pages, keep the context open and open/close pages within it.

Close pages promptly. Open pages hold memory on the remote browser. Close them as soon as you've extracted what you need — don't let them sit idle while the next batch queues up.

Use waitUntil: 'domcontentloaded' over 'networkidle'. The networkidle wait holds until there's been no network activity for 500ms — which can take a long time, or never happen, on analytics-heavy pages. domcontentloaded fires as soon as the HTML is parsed, which is usually enough for scraping.

Block assets you don't need. Images, fonts, and stylesheets add significant load time and bandwidth. The route example above is a fast filter to drop them.

Set explicit timeouts. Don't rely on Playwright's 30-second defaults. Set a timeout on every goto() and waitForSelector() call. It makes failures fast and predictable.


Using remote browsers with Spectrae

Spectrae is built for this pattern. You connect your Playwright script to a WebSocket endpoint, and Spectrae handles the browser — starting an isolated Chromium or Camoufox (Firefox) session and cleaning it up when you disconnect.

Pricing is per second: $0.003/min for the standard browser and $0.05/min for the stealth browser, with $1 of free credit to start. There's no infrastructure to provision and no Linux dependencies to manage.

The connection is a single line change from local to remote:

// Before: local
const browser = await chromium.launch({ headless: true });

// After: remote on Spectrae
const browser = await chromium.connect('wss://browser.spectrae.dev/standard/playwright', {
  headers: { Authorization: `Bearer ${process.env.SPECTRAE_API_KEY}` },
});

Everything else stays the same. Your contexts, pages, locators, and assertions work as they do locally. See the docs for every endpoint, or get an API key.