← Blog

BLOG

Learn Use of Remote Browsers: A Practical Setup Guide

Learn use of hosted Chromium for AI agents: CDP wiring, Playwright setup, session lifecycle, and the production criteria that matter.

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

If you want to learn use of a remote browser, the fastest path is to understand one thing: a remote browser is just Chromium running on someone else's machine, exposed over the Chrome DevTools Protocol (CDP). Your agent code connects to a WebSocket endpoint instead of launching a local binary. Everything else — Playwright, Puppeteer, Selenium, or a higher-level agent framework — sits on top of that connection.

This guide walks through the mechanics, the code, and the production decisions you need to make. It assumes you already know how to write a Playwright script and want to move it off your laptop.

What "learn use" actually means in practice

Learning to use a remote browser is not a single skill. It breaks into four concrete capabilities:

  1. Provisioning — creating a browser session through an API and getting back a connection URL.
  2. Connecting — attaching Playwright, Puppeteer, or a raw CDP client to that URL.
  3. Driving — running navigation, extraction, and interaction logic against the remote page.
  4. Managing lifecycle — keeping sessions alive, persisting profiles, and tearing down cleanly so you don't pay for idle browsers.

Most tutorials stop at step 2. Production problems live in steps 3 and 4. If you only learn to connect, you will ship something that works in a demo and breaks under concurrency, retries, or long-running tasks.

The core mental model: the browser is a service, not a dependency. You don't npm install it into your container. You request it, use it, and release it.

How a remote browser session works

When you request a session from a hosted runtime like Remote Browser, the provider allocates an isolated Chromium instance and returns a CDP WebSocket endpoint. That endpoint is the same protocol Chrome exposes when you run chrome --remote-debugging-port=9222 locally. The difference is that the browser lives in a data center, has its own network egress, and can be watched through a live viewer.

The flow looks like this:

  • Your code calls a session-creation endpoint with configuration (viewport, proxy, profile, timeout).
  • The provider spins up Chromium and returns { sessionId, cdpUrl }.
  • Your Playwright/Puppeteer client connects to cdpUrl.
  • You run your automation.
  • You call a stop endpoint, or the session times out.

Because the transport is standard CDP, the same script that works against a local Chrome works against a remote one with a one-line change. That is the entire value proposition, and it is worth internalizing before you touch any framework-specific API.

Connecting Playwright to a hosted Chromium session

The canonical method is chromium.connectOverCDP(). It accepts a WebSocket URL and returns a Browser object. From there, you get contexts and pages exactly as you would locally.

import { chromium, Browser, Page } from "playwright";

interface SessionResponse {
  sessionId: string;
  cdpUrl: string;
}

async function createSession(): Promise<SessionResponse> {
  const res = await fetch("https://api.remote-browser.dev/v1/sessions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.REMOTE_BROWSER_API_KEY}`,
    },
    body: JSON.stringify({
      viewport: { width: 1280, height: 800 },
      timeoutSeconds: 600,
      // Optional: attach a persistent profile so logins survive restarts.
      profileId: process.env.PROFILE_ID,
    }),
  });

  if (!res.ok) {
    throw new Error(`Session creation failed: ${res.status} ${await res.text()}`);
  }
  return (await res.json()) as SessionResponse;
}

async function runTask(): Promise<void> {
  const { sessionId, cdpUrl } = await createSession();
  let browser: Browser | undefined;

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

    // A remote session usually starts with one default context.
    const context = browser.contexts()[0] ?? (await browser.newContext());
    const page: Page = context.pages()[0] ?? (await context.newPage());

    await page.goto("https://example.com", { waitUntil: "domcontentloaded" });
    const title = await page.title();
    console.log("Remote page title:", title);

    // Do your extraction or interaction here.
    await page.getByRole("link", { name: /more information/i }).click();
    await page.waitForLoadState("networkidle");
  } finally {
    // Disconnect the client. The session itself is stopped via the API.
    await browser?.close();
    await fetch(`https://api.remote-browser.dev/v1/sessions/${sessionId}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${process.env.REMOTE_BROWSER_API_KEY}` },
    });
  }
}

runTask().catch((err) => {
  console.error(err);
  process.exit(1);
});

Three details matter here and are easy to get wrong:

  • `browser.close()` does not necessarily stop the remote session. In many hosted runtimes, closing the CDP client only disconnects. You must call the provider's stop endpoint to release the browser. Check your provider's semantics; Remote Browser meters by session time, so an orphaned session keeps accruing usage.
  • Contexts may already exist. A hosted session often pre-creates a default context. Calling newContext() unconditionally can leave you driving a page nobody is watching. Reuse contexts()[0] when present.
  • Timeouts are your responsibility. Set a session timeout at creation and a navigation timeout in Playwright. A hung goto on a slow third-party site will otherwise burn your session budget.

For the official protocol reference, see the Chrome DevTools Protocol documentation and Playwright's `connectOverCDP` docs.

Puppeteer and Selenium: same endpoint, different client

You are not locked into Playwright. Puppeteer connects with puppeteer.connect({ browserWSEndpoint }). Selenium 4 can attach over CDP as well, though the ergonomics are rougher. The important point is that the CDP URL is the contract. If you can connect a client to a WebSocket, you can drive the session.

This matters when you inherit a codebase. You don't need to rewrite your Puppeteer scripts to use a hosted runtime; you need to change how the browser is acquired.

Local Chrome vs hosted Chromium: what actually differs

DimensionLocal ChromeHosted Chromium (Remote Browser)
Provisioningnpm install, binary download, version pinningAPI call returns a CDP URL
ScalingLimited by host CPU/RAM; manual orchestrationRequest N sessions; provider handles placement
Network egressYour machine's IPProvider egress, configurable proxy settings
Session persistenceProfile directory on diskPersistent profiles managed by the runtime
DebuggingLocal DevToolsLive viewer plus CDP access
Failure isolationOne crash can take down the hostSessions are isolated per instance
Cost modelFixed infra + ops timeMetered per session; see /pricing
Version controlYou pin and patch ChromeProvider manages the Chromium build

The trade-off is not "cloud is better." It is that hosted runtimes move operational burden off your team at the cost of per-session metering and a network hop. For a single script run once a day, local Chrome is fine. For an agent fleet handling concurrent tasks with retries, hosted sessions remove a class of infrastructure work you would otherwise own.

Production criteria to evaluate before you commit

When you learn use of any remote browser product, evaluate it against these criteria rather than feature lists:

  • CDP fidelity. Can you use the full protocol, or is it a restricted subset? If the provider proxies only a handful of methods, your Playwright features will silently degrade.
  • Session lifecycle semantics. Does closing the client stop the session? What is the idle timeout? Can you extend a session mid-run?
  • Profile persistence. Can you save cookies and local storage across sessions so agents don't re-authenticate every run? See /documentation for how Remote Browser handles profiles.
  • Network controls. Are proxies configurable per session? Is egress region selectable? These affect both reliability and whether sites treat your traffic as suspicious.
  • Observability. Is there a live viewer? Can you capture console logs, network traces, and screenshots from the remote session?
  • Concurrency and quotas. What happens when you hit your limit — queue, error, or silent throttling? Know this before you build a retry loop.
  • Isolation. Are sessions truly isolated, or do they share a browser process? Shared processes leak state and crash together.

If you are evaluating this for an agent workload specifically, the companion piece on remote browsers for AI agents covers the runtime-layer concerns in more depth.

Common mistakes when learning to use remote browsers

These show up repeatedly in support threads and postmortems:

  1. Leaking sessions. The script throws, the finally block never runs, and the session sits idle until timeout. Always wrap session creation in try/finally and stop the session explicitly.
  2. Assuming a fresh browser. Persistent profiles mean the browser may already be logged in, have cookies, or be on a different page than you expect. Assert state before acting.
  3. Ignoring the network hop. A goto that takes 300ms locally may take 800ms remotely. Set timeouts accordingly and avoid tight polling loops.
  4. Hardcoding the CDP URL. Session URLs are ephemeral. Never cache them across runs.
  5. Skipping the viewer during development. Watching the session live is the fastest way to debug selector failures and unexpected redirects. Use it before you add logging.
  6. Treating the remote browser as a scraper. It is a full browser. If you only need HTML, an HTTP client is cheaper and faster. Use a remote browser when you need JavaScript execution, interaction, or session state.

When a remote browser is the right tool

Use a hosted browser when at least one of these is true:

  • Your agent needs to run many concurrent sessions and you don't want to manage a Chromium fleet.
  • Tasks require persistent login state across runs.
  • You need network egress from a specific region or through a proxy.
  • You want a live viewer for human-in-the-loop debugging.
  • Your CI or serverless environment can't run a headless browser reliably.

Skip it when you need a single short-lived scrape, when latency budgets are extremely tight, or when your workload is fully static HTML. The runtime is infrastructure, and infrastructure should earn its place.

If you are still comparing hosted options, the remote browser online overview and the remote web browser guide cover the category from different angles. For control-plane details — how to drive a session programmatically versus interactively — see remote control browser.

A minimal checklist to get started

If you want to learn use today, do this in order:

  1. Get an API key and read the session-creation docs at /documentation.
  2. Write the createSession + connectOverCDP snippet above and run it against a simple page.
  3. Open the live viewer and watch the session while your script runs.
  4. Add a persistent profile and confirm cookies survive a restart.
  5. Add try/finally teardown and verify sessions stop when your script exits.
  6. Run two sessions concurrently and confirm isolation.
  7. Check /pricing and estimate your per-task cost before scaling.

That sequence takes an afternoon and surfaces almost every integration issue you will hit in production. The protocol is standard, the code is short, and the hard part is lifecycle discipline — not the connection itself.

Bottom line

To learn use of a remote browser, learn CDP first. The endpoint is the contract; Playwright, Puppeteer, and agent frameworks are clients on top of it. Get provisioning, connection, and teardown right, evaluate the runtime against lifecycle and isolation criteria, and treat the browser as a metered service rather than a local dependency. Do that, and moving from a laptop script to a hosted fleet is a configuration change, not a rewrite.