How to Connect Playwright to a Remote Browser API (Step by Step)

Connect Playwright to a remote browser over WebSocket in Node.js or Python — API keys, connect() examples, a stealth Firefox option and troubleshooting.

Spectrae team · · 6 min read

Running Playwright on your laptop is easy. Running it in production — in the cloud, across parallel sessions, for weeks — is a completely different problem.

Most developers hit the same wall. They get a scraper working locally, push it to a server, and watch it fail. Memory spikes. Chrome crashes. The container OOMs. Suddenly you're debugging Linux dependencies instead of writing the code that actually matters.

There's a better way. Remote browser APIs let you connect your Playwright scripts to a cloud-hosted browser over a WebSocket. You write the same code you always have. The browser runs somewhere else.

This guide walks through exactly how to do that with Spectrae, a Browser-as-a-Service platform that gives you Chromium and a Camoufox-powered stealth Firefox over a simple WebSocket API. The same steps work with any service that exposes a Playwright server endpoint.


Why running Playwright locally breaks at scale

Playwright is a great tool. But browsers are memory-hungry. A single Chrome instance can use hundreds of megabytes of RAM once real pages load. Run 10 in parallel and you can exhaust the memory on a small cloud instance.

The problems compound fast:

  • Crashes — Browsers crash under memory pressure, and the OOM killer may take your application process with them
  • Dependency hell — Running Chrome on Linux requires a pile of system libraries (libgbm, libnss, shared fonts) that are easy to miss in Docker
  • No isolation — One runaway page can slow or kill all your other sessions
  • Maintenance — Keeping browser versions in sync with Playwright versions is its own ongoing job

You can patch each of these. But you end up spending more time on infrastructure than on scraping.


What is a remote browser API

A remote browser API is a server that runs a browser and exposes it over a WebSocket connection. Your Playwright code connects to that WebSocket instead of launching a local browser process.

Playwright has native support for this. The chromium.connect() method (and firefox.connect()) accepts a WebSocket URL. Once connected, you get a Browser object back that works like the one from chromium.launch(). Your existing page code works unchanged.

The remote server handles the browser lifecycle. You handle the logic.


Step 1: Get your API key

Sign up to get an API key. New accounts start with $1 of free credit. After that, Spectrae bills per second of session time: $0.003/min for the standard browser and $0.05/min for the stealth browser.

Once you have your key, keep it in an environment variable. Never hardcode it in your scripts.

export SPECTRAE_API_KEY=your_api_key_here

Step 2: Install Playwright

If you don't have Playwright installed yet, add it to your project.

npm install playwright

That's it. You don't need to run npx playwright install to download browser binaries. Spectrae runs the browsers for you. No Chromium downloads, no system dependencies to manage.

Pin the version: connect() needs a client version compatible with the server. Spectrae's browsers currently run Playwright 1.58, so start there:

npm install [email protected]

Step 3: Connect via WebSocket

Instead of calling chromium.launch(), you call chromium.connect() with a WebSocket URL.

import { chromium } from 'playwright';

const browser = await chromium.connect(
  `wss://browser.spectrae.dev/standard/playwright?key=${process.env.SPECTRAE_API_KEY}`
);

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

// Use it exactly like a local browser
const page = await browser.newPage();
await page.goto('https://example.com');
console.log('Page title:', await page.title());

await browser.close();

The connection string format is:

wss://browser.spectrae.dev/standard/playwright?key=YOUR_API_KEY

If you'd rather keep the key out of the URL (and out of logs), send it as a header instead:

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

Playwright's connect() method uses the Playwright protocol — the same one that browserType.launchServer() exposes. That means page.goto(), page.click(), page.evaluate(), request routing and screenshots all work as they do locally.


Step 4: Run your first scrape

Here's a more complete example that scrapes a page and handles cleanup properly.

import { chromium } from 'playwright';

async function scrape(url) {
  const browser = await chromium.connect(
    `wss://browser.spectrae.dev/standard/playwright?key=${process.env.SPECTRAE_API_KEY}`
  );

  try {
    const context = await browser.newContext({
      viewport: { width: 1280, height: 800 },
      locale: 'en-US',
    });

    const page = await context.newPage();
    await page.goto(url, { waitUntil: 'domcontentloaded' });

    const data = await page.evaluate(() => {
      return {
        title: document.title,
        headings: Array.from(document.querySelectorAll('h1, h2')).map(h => h.textContent.trim())
      };
    });

    return data;
  } finally {
    await browser.close(); // Always close — session billing stops when you do
  }
}

scrape('https://news.ycombinator.com').then(console.log);

A few things worth noting here. The try/finally block ensures the browser closes even if your scrape throws an error. This matters for billing — Spectrae tracks session time, so an unclosed browser keeps the meter running. The browser.newContext() call lets you set viewports, locale, and other options per context without opening a new connection. Avoid overriding the user agent with a hand-written string: a UA that doesn't match the real browser is itself a detection signal.


Python example

Playwright has first-class Python support. The remote connection pattern works exactly the same way.

import asyncio
import os
from playwright.async_api import async_playwright

async def scrape(url: str):
    api_key = os.environ["SPECTRAE_API_KEY"]
    ws_url = f"wss://browser.spectrae.dev/standard/playwright?key={api_key}"

    async with async_playwright() as p:
        browser = await p.chromium.connect(ws_url)

        try:
            page = await browser.new_page()
            await page.goto(url)

            title = await page.title()
            print(f"Title: {title}")

            return title
        finally:
            await browser.close()

asyncio.run(scrape("https://example.com"))

Install the Python library with pip install "playwright==1.58.*". No browser downloads needed — same as Node.js.


Camoufox: the Firefox option for tougher targets

Some sites detect Chromium-based automation and block it. For those cases, Spectrae offers a stealth browser powered by Camoufox — a custom Firefox build with anti-detection changes made in its C++ source.

Camoufox changes fingerprint surfaces inside the engine, before page JavaScript runs. Navigator properties, WebGL parameters, fonts, screen dimensions — generated to be internally consistent and realistic. That removes the common headless tells; it doesn't guarantee access to every site.

The connection string is the same pattern, just a different path. Because it's Firefox, use Playwright's firefox client:

import { firefox } from 'playwright';

const browser = await firefox.connect(
  `wss://browser.spectrae.dev/stealth/playwright?key=${process.env.SPECTRAE_API_KEY}`
);

const page = await browser.newPage();
await page.goto('https://example.com');

await browser.close();

Use the standard browser by default. Switch to the stealth browser when you hit bot detection walls — more in our Playwright stealth guide.


Troubleshooting common issues

Connection closes immediately

Check that your API key is correct. Spectrae closes the WebSocket with code 1008 and the reason invalid_api_key when it doesn't recognise the key — Playwright surfaces this as a connection error. Double-check for whitespace or truncation.

Error: browserType.connect: WebSocket error

This almost always means a network issue. Verify the URL starts with wss:// not ws://. If you're behind a corporate proxy, it may be blocking WebSocket upgrades.

Playwright version mismatch

connect() needs compatible client and server versions. If you get a version or protocol error, pin your client to the server's version (Playwright 1.58 at the time of writing; the docs list the current one).

Connection rejected with connection_limit_exceeded

You've hit your account's concurrent-session limit. Close sessions you're done with, cap your own concurrency to match, or add slots from the dashboard.

Sessions end when your balance runs out

New sessions are blocked at a $0 balance and active sessions are closed gracefully. Top up from the dashboard.

Memory or performance issues

You're running remotely — browser memory isn't on your machine any more. If pages feel slow, try setting waitUntil: 'domcontentloaded' instead of networkidle to avoid waiting on slow third-party resources.


Start building

Remote browser APIs remove the hardest part of running Playwright in production. You get a browser, you use it, you close it. No servers to maintain, no Chromium binaries to install, no OOM crashes to debug at 2am.

Spectrae gives you a standard Chromium browser and a Camoufox stealth browser over a WebSocket, billed per second. Get your API key with $1 of free credit and start your first session.