← Blog

BLOG

Browser CDP: Connect Playwright to Remote Chromium

Browser CDP connects Playwright, Puppeteer, or Selenium to a running Chromium session. Learn endpoints, setup, security, and production trade-offs.

10 min readRemote Browser
Ivory computer towers connected across terracotta platforms in a quiet desert landscape
The infrastructure behind your browserREMOTE BROWSER / ILLUSTRATION

Browser CDP is the connection layer between your automation code and an already-running Chromium browser. Instead of launching Chrome inside the same process or machine as your test or AI agent, you attach to a browser through the Chrome DevTools Protocol (CDP).

That model is useful when the browser runs in a hosted environment. Remote Browser provides hosted Chromium sessions with CDP access, so your application can keep its agent logic, task orchestration, and business systems separate from the browser runtime.

A typical flow is:

  1. Create or obtain a hosted Chromium session.
  2. Read the session's authenticated CDP endpoint.
  3. Connect with Playwright, Puppeteer, Selenium, or another CDP-compatible client.
  4. Use the browser normally.
  5. Disconnect or stop the session according to your lifecycle policy.

This guide explains how the connection works, how to connect with TypeScript and Playwright, and which production details matter beyond the first successful page load.

What browser CDP means

The Chrome DevTools Protocol is a set of domains and commands for controlling Chromium. Those domains cover capabilities such as:

  • Page navigation and lifecycle events
  • DOM inspection and JavaScript execution
  • Network requests and responses
  • Cookies, storage, and browser permissions
  • Screenshots, PDF generation, and emulation
  • Console messages, tracing, and debugging
  • Target and tab management

A browser CDP endpoint is the network address through which a client communicates with a running Chromium instance. Depending on the runtime, the endpoint may be represented as a WebSocket URL or an HTTP URL that exposes browser connection information. Your automation library handles the protocol details after you provide the endpoint.

CDP is not an automation framework by itself. It is a browser control protocol. Playwright and Puppeteer provide higher-level APIs for locators, assertions, navigation, waiting, and test structure. Selenium can also work with Chromium-related debugging capabilities, but its primary abstraction is WebDriver rather than CDP.

This distinction matters because a CDP connection does not create a browser. It attaches to one that already exists. The browser's process, profile, proxy configuration, operating system, and session lifecycle are controlled by the environment that launched it.

Remote Browser is designed for that separation. The hosted runtime manages Chromium sessions, while your code connects to the session and drives it. See the Remote Browser documentation for the current connection and session instructions.

How a CDP connection works

A browser CDP connection has four important parts.

1. A running Chromium session

There must be a browser process available before the client connects. With a local workflow, this might be Chrome started with a remote debugging port. With a hosted workflow, the provider starts and isolates the browser session for you.

The session determines the browser version, available settings, profile state, network path, and resource allocation. If the session has a persistent profile, cookies and local storage can remain available across connections according to the profile's lifecycle.

2. An endpoint and credentials

The endpoint is sensitive. Anyone who can use a valid CDP endpoint may be able to navigate pages, read session data, execute JavaScript, and interact with authenticated accounts. Treat it like a high-privilege credential.

Do not:

  • Commit the endpoint to source control.
  • Print it in application logs.
  • Put it in a client-side bundle.
  • Share it through unencrypted chat or tickets.
  • Reuse it across unrelated tenants or jobs.

Pass the endpoint through a secret manager or protected environment variable. Follow the provider's current authentication and expiration rules rather than assuming that every endpoint behaves like a permanent local debugging port.

3. A compatible client

Playwright's connectOverCDP() is the direct browser CDP path for Chromium. Puppeteer provides a similar connection method. The client creates a local representation of the remote browser, contexts, pages, and targets, while commands execute in the hosted Chromium process.

The client and browser do not need to run on the same machine. They only need network reachability, compatible protocol support, and an endpoint that the client can access.

4. A lifecycle decision

Connecting and disconnecting are separate from starting and stopping a session. Your application should decide whether a job:

  • Reuses a persistent browser profile.
  • Connects to a short-lived isolated session.
  • Leaves the browser available for another worker.
  • Stops the browser after the task completes.
  • Hands the session to an operator through a live viewer.

Remote Browser includes session isolation, persistent profiles, a live viewer, configurable browser settings, and usage controls. These features address runtime operations around CDP; they do not change the underlying protocol.

Browser CDP compared with other connection models

The right connection method depends on who owns the browser process and how much browser state you need to preserve.

Connection modelBrowser ownerBest fitMain trade-off
chromium.launch()Your application or test runnerLocal development and isolated test runsYou manage the browser executable, startup, resources, and environment
connectOverCDP()A local or hosted Chromium runtimeAttaching Playwright to an existing browser sessionChromium-focused and dependent on the remote session's lifecycle
Puppeteer browser connectionA local or hosted Chromium runtimeNode.js automation already built around PuppeteerAPI and behavior follow Puppeteer's model
Selenium WebDriverA WebDriver service and browser driverExisting Selenium grids and WebDriver-based suitesRequires WebDriver infrastructure and uses a different control abstraction
Manual DevTools Protocol clientYour application and browser runtimeLow-level debugging or protocol-specific toolingMore control, but you must implement more waiting and error handling

For a hosted browser, connectOverCDP() is usually the shortest path when your application already uses Playwright. It avoids downloading a local browser and lets the remote runtime own browser startup, profiles, network configuration, and isolation.

The trade-off is that a CDP attachment is not identical to a Playwright-launched browser. Some Playwright features depend on Playwright's own browser server and transport. If your workflow requires a feature that is not exposed or behaves differently through CDP, verify it against the exact browser and Playwright versions used in your deployment. The official Playwright CDP documentation is the appropriate reference for current support details.

Connect Playwright to a hosted browser

The following TypeScript example assumes that your application has already created a Remote Browser session and received its CDP endpoint. The endpoint is supplied through an environment variable rather than embedded in the source.

import { chromium, type Browser, type BrowserContext } from "playwright";

async function run() {
  const cdpUrl = process.env.REMOTE_BROWSER_CDP_URL;

  if (!cdpUrl) {
    throw new Error("REMOTE_BROWSER_CDP_URL is required");
  }

  let browser: Browser | undefined;

  try {
    browser = await chromium.connectOverCDP(cdpUrl);

    const contexts = browser.contexts();
    const context: BrowserContext =
      contexts[0] ?? (await browser.newContext());

    const page = context.pages()[0] ?? (await context.newPage());

    await page.goto("https://example.com", {
      waitUntil: "domcontentloaded",
      timeout: 30_000,
    });

    console.log({
      title: await page.title(),
      url: page.url(),
    });
  } finally {
    // Disconnect the client without assuming ownership of the remote session.
    browser?.disconnect();
  }
}

run().catch((error) => {
  console.error("Remote browser task failed:", error);
  process.exitCode = 1;
});

There are two details worth preserving in production code.

First, inspect existing contexts and pages before creating new ones. A hosted session may already contain the profile, cookies, or page that your workflow expects. Creating a new context can bypass that state.

Second, distinguish disconnecting from stopping. browser.disconnect() ends the Playwright connection while leaving session ownership to the runtime. If the task should terminate the hosted browser, use the session-management operation documented by your provider rather than relying on a client disconnect.

You can adapt the same pattern to an internal browser service or a local Chrome debugging endpoint. The main difference is how the endpoint is created, authenticated, and retired.

Production criteria for browser CDP

A successful connection proves only that the endpoint is reachable. Production reliability depends on the surrounding system.

Protect the endpoint

CDP provides broad control over the browser. Restrict access at the network and application layers, use encrypted transport where supported, and keep endpoint values out of logs and error payloads.

For multi-tenant systems, create a separate session or profile boundary for each workload that handles sensitive accounts. Do not let arbitrary user input select a CDP endpoint. Validate that the endpoint belongs to the session and tenant that requested the job.

Make session state explicit

Decide which state is intentional:

  • Cookies and authenticated sessions
  • Local storage and indexed databases
  • Open tabs and navigation history
  • Proxy or network settings
  • Browser permissions
  • Downloaded files
  • Temporary data created by a task

Persistent profiles are useful for repeated workflows, but they also create coupling between jobs. A stale login, unexpected tab, or previous task's local storage can affect later results. Use isolated sessions for unrelated users and define when profiles are refreshed or invalidated.

The article on remote browsers for AI agents covers why session state, browser lifecycle, and agent execution should be treated as separate runtime concerns.

Set timeouts and handle disconnects

A CDP client can lose its connection because of network interruptions, browser termination, idle cleanup, or an infrastructure event. Use explicit navigation and action timeouts instead of waiting indefinitely.

When a disconnect occurs:

  1. Record the session identifier and task identifier, but not the secret endpoint.
  2. Determine whether the browser session is still alive.
  3. Reconnect only if the operation is safe to repeat.
  4. Avoid repeating non-idempotent actions such as purchases, submissions, or account changes without checking the resulting state.
  5. Mark the task for controlled retry or human review.

A retry should not automatically replay the last click. First inspect whether the click succeeded before the connection failed.

Control concurrency and browser state

Each session can contain multiple tabs and pages, but uncontrolled tab creation increases memory use and makes agent decisions harder to reason about. Establish limits for pages, navigation depth, downloads, and task duration.

Use usage controls to prevent abandoned sessions from consuming resources. Stop sessions that are no longer needed, and make cleanup run in a finally block or an equivalent job-finalization hook. Consult current pricing and usage details when designing capacity assumptions; do not assume a fixed limit or unrestricted concurrency.

Add an operator path

AI agents and automated jobs can fail in ways that are difficult to diagnose from logs alone. A live viewer gives an operator a way to inspect the current page, authentication state, unexpected redirects, or consent dialogs.

A useful operational record should include:

  • Session and task identifiers
  • Browser and client versions
  • Start and end timestamps
  • Current URL, excluding sensitive query values
  • Navigation and action timing
  • Failure category and retry count
  • Whether the session was disconnected or stopped

Do not capture screenshots, page content, or recordings by default if they may contain personal, financial, or authentication data. Set retention and access rules before enabling diagnostic capture.

Common browser CDP failure modes

“Connection refused” or timeout

The browser may not be running, the endpoint may have expired, or the network path may block the connection. Verify session state and endpoint freshness first. Do not “fix” this by exposing a debugging port publicly.

“No pages” or unexpected context

The session may have started without an initial page, or your code may be connecting to a different context than expected. Inspect browser.contexts() and context.pages() before acting. For persistent sessions, confirm that your code is using the context created by the runtime.

This can indicate a page readiness issue, a changed DOM, a blocked resource, or a client/browser compatibility difference. Use locators and explicit conditions rather than fixed sleeps. Check the live session when the page depends on a login, challenge, or consent flow.

The task succeeds locally but not remotely

Compare browser version, viewport, locale, timezone, proxy configuration, permissions, and profile state. A hosted browser is a real runtime with its own environment, not merely a remote copy of your local process. Configure only the settings the workflow requires and test against the deployment environment.

When to use browser CDP

Use browser CDP when you need to attach existing automation code to a browser that is managed elsewhere. It is especially appropriate for hosted Chromium, persistent browser sessions, remote debugging, AI agent workers, and applications that should not package Chrome into every execution environment.

Use a direct local launch when you need the simplest isolated test process and want your runner to own browser startup. Use WebDriver when your organization already operates a Selenium grid or depends on WebDriver-specific tooling.

For remote workflows, CDP gives your application a practical boundary: the application controls tasks and policy, while the browser runtime controls Chromium, profiles, networking, and session operations. That separation is the foundation for running browser automation without coupling every worker to a local Chrome installation. For a broader introduction to the runtime model, see remote browser online and remote control browser.