← Blog

BLOG

Playwright Connect to Remote Browser: A Practical Guide

Learn how to connect Playwright to a remote browser for AI agents and automation. Explore CDP, session persistence, and production trade-offs.

August 25, 20269 min readRemote Browser

# Playwright Connect to Remote Browser: A Practical Guide

Connecting Playwright to a remote browser is the difference between running a script on your laptop and running a reliable automation workload in production. When you use playwright.connect() or playwright.connectOverCDP(), you stop managing Chromium locally and start driving a browser that lives elsewhere—on a server, in a container, or behind an API. This guide explains how to connect Playwright to a remote browser, what the trade-offs are, and how to choose between a self-hosted setup and a browser-as-a-service runtime.

Why Connect Playwright to a Remote Browser?

The primary reason to connect Playwright to a remote browser is infrastructure separation. Your test script or AI agent logic runs in one place (a worker, a serverless function, a local machine), while the browser runs in another. This separation matters for several reasons:

  • Resource isolation: Browsers are memory-hungry. Running them inside a serverless function or a small container often causes OOM kills. A remote browser moves that burden elsewhere.
  • Session persistence: A local browser dies when your process dies. A remote browser can stay alive across multiple workers, retries, or agent steps.
  • Network egress: If your automation needs to access sites that block datacenter IPs, a remote browser with configurable proxy settings can route traffic through a different egress point.
  • Live debugging: You can watch a remote browser session in real time, even if the code that drives it runs on another machine.

For AI agents, the case is even stronger. An agent that browses the web needs a browser that survives between LLM calls, tool invocations, and retries. Connecting Playwright to a remote browser gives you that persistence without forcing you to build a browser-management service yourself.

How Playwright Connects to a Remote Browser

Playwright supports two primary ways to connect to a browser that isn't running locally:

  1. `playwright.connect()` — Connects to a browser server that speaks the Playwright protocol. This is the native way to attach to a browser started with browserType.launchServer() or a compatible service.
  2. `playwright.connectOverCDP()` — Connects to a browser via the Chrome DevTools Protocol (CDP) endpoint. This works with any Chromium-based browser that exposes a CDP port, including hosted browser APIs.

Here's a minimal TypeScript example using connectOverCDP:

import { chromium } from 'playwright';

async function main() {
  // Connect to a remote browser via CDP
  const browser = await chromium.connectOverCDP('wss://remote-browser.example.com/cdp');
  
  // The default context is the browser's existing session
  const context = browser.contexts()[0] || await browser.newContext();
  const page = await context.newPage();
  
  await page.goto('https://example.com');
  console.log(await page.title());
  
  // Keep the browser alive; don't close it if you want persistence
  await browser.close();
}

main().catch(console.error);

The key detail here is that connectOverCDP attaches to an existing browser session. If the remote browser is configured to keep sessions alive, your Playwright script can disconnect and reconnect later without losing cookies, local storage, or in-page state.

CDP vs. Playwright Protocol: What's the Difference?

When you connect Playwright to a remote browser, you have two protocol options. Understanding the difference helps you choose the right integration path.

FeaturePlaywright Protocol (connect)CDP (connectOverCDP)
CompatibilityPlaywright-native; works with launchServer()Works with any Chromium-based browser exposing CDP
Browser supportChromium, Firefox, WebKitChromium only
Session persistenceManaged by Playwright serverManaged by the browser process itself
Tooling supportPlaywright Inspector, trace viewerChrome DevTools, Puppeteer, Selenium (via CDP)
Use casePlaywright-only test farmsMixed tooling, AI agents, existing browser infrastructure

For most AI agent workloads, CDP is the better choice because it gives you a standard interface that other tools (Puppeteer, Selenium, raw WebSocket clients) can also use. If you're building a test harness exclusively with Playwright, the native protocol is simpler and more feature-complete.

Keeping Browser Sessions Alive Across Cloud Workers

One of the most common questions we hear is: *how do I keep browser sessions alive across multiple cloud workers?* The answer depends on where the browser runs.

If you're using a hosted browser API like Remote Browser, the session lives on our infrastructure. Your workers connect, do work, disconnect, and reconnect later. The session state—cookies, local storage, service workers—persists because the browser process never dies.

If you're self-hosting, you need to run a browser server that outlives individual workers. Options include:

  • A dedicated VM running chromium.launchServer() with a stable WebSocket endpoint.
  • A container orchestration platform (Kubernetes, Nomad) that keeps browser pods alive.
  • A sidecar pattern where each worker has a browser companion process, but this doesn't solve cross-worker persistence.

The trade-off is operational complexity. Self-hosting gives you full control but requires you to handle scaling, crash recovery, and security. A hosted runtime removes that burden but introduces a dependency on an external service.

Browser-as-a-Service vs. Self-Hosted Playwright Infrastructure

Choosing between a browser-as-a-service (BaaS) and self-hosted Playwright infrastructure is a cost and control decision. Here's a comparison to help you evaluate:

CriterionBrowser-as-a-ServiceSelf-Hosted
Setup timeMinutes (API key + connect)Days to weeks (infra + config)
ScalingAutomaticManual (or via K8s)
Session persistenceBuilt-inYou build it
Network egressConfigurable proxiesYou manage IP pools
Cost modelPer browser-hourFixed infra + engineering time
DebuggingLive viewer, session replayYou build tooling
SecurityVendor-managedYou own the blast radius

For teams running fewer than 100 browser-hours per month, BaaS is almost always cheaper when you factor in engineering time. At higher volumes, self-hosting can be more cost-effective, but only if you have the operational expertise to run it reliably.

Our recommendation: start with a hosted runtime to validate your workload, then move to self-hosting only if you hit scale or compliance requirements that justify the engineering cost.

Giving Your AI Agent Browser Access in Production

AI agents that browse the web need more than a browser connection. They need a runtime that handles the messy parts of web automation:

  • Session continuity: An agent might make 10 LLM calls while working on one task. The browser must stay alive between those calls.
  • Isolation: If you're running multiple agents, each should have its own browser profile to avoid cross-contamination.
  • Stealth and proxy settings: Some sites block datacenter IPs. Configurable browser settings let you route traffic through residential or other proxies.
  • Live debugging: When an agent fails, you need to see what the browser saw. A live viewer or session recording is essential.

This is where a dedicated remote browser runtime differs from a raw CDP endpoint. A raw endpoint gives you a browser. A runtime gives you sessions, profiles, proxies, and debugging tools on top of that browser.

If you're building an AI agent that needs browser access, read our guide on remote browsers for AI agents for a deeper dive into session management and profile isolation.

Practical Steps to Connect Playwright to Remote Browser

Here's a step-by-step approach to connecting Playwright to a remote browser, whether you're using a hosted service or your own infrastructure.

Step 1: Get a CDP Endpoint

For a hosted service, you'll typically get a WebSocket URL or an HTTP endpoint that returns one. For self-hosted, you'll start Chromium with --remote-debugging-port=9222 and connect to http://localhost:9222.

Step 2: Choose Your Connection Method

Use connectOverCDP if you need compatibility with other tools or if the browser is already running. Use connect if you're starting a Playwright-managed browser server.

Step 3: Handle Session Persistence

Don't close the browser after each task. Instead, keep the connection open or reconnect to the same session. In Playwright, this means:

  • Don't call browser.close() unless you're done with the session.
  • Store the session ID or WebSocket URL so you can reconnect.
  • Use persistent contexts (launchPersistentContext) if you need a specific profile.

Step 4: Configure Network and Proxy Settings

If your automation needs to appear from a specific location or avoid IP blocks, configure proxy settings at the browser or context level. In Playwright, this is done via browser.newContext({ proxy: { server: '...' } }).

Step 5: Monitor and Debug

Use a live viewer or session recording to watch what the browser is doing. This is invaluable for debugging AI agent failures, where the agent's reasoning might be correct but the browser state is wrong.

Common Pitfalls When Connecting Playwright to a Remote Browser

Even with a solid setup, you'll hit issues. Here are the most common ones and how to avoid them:

  • WebSocket timeouts: Remote browser connections can drop if there's no activity. Configure keep-alive pings or reconnect logic in your Playwright script.
  • Context leakage: If you reuse a browser across tasks, make sure you create a fresh context for each task to avoid state leakage.
  • CDP version mismatch: Chromium updates frequently. If your remote browser is older than your Playwright version, you may hit protocol errors. Pin your Playwright version to match the browser.
  • Firewall and egress rules: Some corporate networks block WebSocket connections. Ensure your network allows outbound WebSocket traffic to your browser endpoint.

When Not to Use a Remote Browser

Remote browsers aren't always the right answer. Consider alternatives if:

  • Your workload is short-lived and stateless: A single page scrape that doesn't need persistence might be faster with a local browser.
  • You need extreme low latency: Every network hop adds latency. If your automation is latency-sensitive, local execution wins.
  • You have strict data residency requirements: If browser data cannot leave your infrastructure, you'll need to self-host.

For everything else—AI agents, long-running tests, cross-worker persistence—a remote browser is the pragmatic choice.

Conclusion: Playwright Connect to Remote Browser Is a Production Decision

Connecting Playwright to a remote browser is straightforward technically, but the real decision is architectural. You're choosing where your browser runs, how it persists, and who manages it. For AI agents and production automation, a hosted runtime with CDP support, session persistence, and debugging tools is the fastest path to reliability.

If you're ready to move from local Playwright scripts to a production browser runtime, explore Remote Browser's documentation to see how to connect, or check our pricing to understand the cost model. For a broader look at how remote browsers fit into AI agent architectures, see our post on remote web browsers and the practical runtime guide for remote control browsers.

For more on the CDP protocol itself, the official Chrome DevTools Protocol documentation is the authoritative reference.