← Blog

BLOG

Run In Browser: What It Means and How to Do It Remotely

Learn what it means to run in browser, why local Chrome breaks at scale, and how to run real Chromium remotely over CDP with Playwright.

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

To run in browser means executing code or an agent's actions inside a real browser engine — Chromium, Firefox, or WebKit — rather than against a simulated DOM or a raw HTTP client. The phrase covers two very different setups: running a browser on your own machine, and running one on a remote host you connect to over the network. This guide explains both, then shows how to run in browser remotely with Playwright and the Chrome DevTools Protocol (CDP), including the production criteria that decide whether the approach holds up under load.

If you already know you want a hosted runtime, start with Remote Browser for AI agents. If you want the mechanics, keep reading.

What "run in browser" actually means

A browser is a rendering engine plus a JavaScript runtime plus a network stack plus a security model. When you "run in browser," your code executes inside that environment, which gives you three things a plain HTTP client cannot provide:

  • Rendered state. You see the DOM after JavaScript has run, not the HTML the server first returned.
  • Real interaction semantics. Clicks, focus, scrolling, and form submission behave the way a human's would, including event handlers and layout-dependent behavior.
  • Session context. Cookies, localStorage, service workers, and authentication state persist the way they do for a real user.

That is why browser automation exists at all. Tools like Playwright and Puppeteer drive a browser process through a protocol — CDP for Chromium-based browsers — and your script sends commands like "navigate," "click," and "evaluate" over that channel.

The important distinction for this article is *where that browser process lives*.

Local vs. remote: the same protocol, different operational reality

When you run npx playwright install and launch a browser locally, Playwright spawns a Chromium process on your machine and talks to it over a local pipe or WebSocket. When you run in browser remotely, that same Chromium process lives on a server, and Playwright connects to it over a WebSocket endpoint exposed by the host.

The API surface is nearly identical. The operational differences are not.

DimensionLocal browserRemote hosted browser
Where Chromium runsYour laptop, CI runner, or containerProvider's infrastructure
ConnectionLocal pipe or localhost WebSocketRemote CDP WebSocket endpoint
ScalingLimited by local CPU/RAM; one process per sessionSessions provisioned per request
Session isolationManual (separate user data dirs)Handled by the runtime
PersistenceYou manage profile directoriesPersistent profiles via API
DebuggingDevTools on your machineLive viewer in a browser tab
MaintenanceYou patch Chrome, drivers, OSProvider maintains the runtime
Cost modelYour computeMetered per browser-hour (see /pricing)

Neither column is universally better. A local browser is the right call for a one-off script, a debugging session, or a test suite that needs to run offline. A remote browser is the right call when you need concurrency, isolation, persistence, or a runtime that does not depend on the machine your code happens to be running on.

The failure mode people hit is starting local and never migrating. A script that works on one laptop quietly becomes a fleet of CI jobs that fight over ports, leak profile directories, and fail intermittently when the runner runs out of memory. That is the point at which "run in browser" stops being a code question and becomes an infrastructure question.

How remote execution works over CDP

CDP is a JSON-based protocol that exposes browser internals: targets (pages, workers), the DOM, the network stack, the runtime, and input events. A remote browser host exposes a WebSocket endpoint that speaks CDP. Your automation library connects to it and drives the browser exactly as it would a local one.

The connection flow is short:

  1. Your code requests a session from the runtime's API.
  2. The runtime provisions a Chromium instance and returns a CDP WebSocket URL.
  3. Playwright (or Puppeteer, or Selenium via a bridge) connects to that URL.
  4. Your script drives the page; the runtime meters the session.
  5. You close the session, and the runtime tears down the instance.

Playwright's connectOverCDP is the standard entry point for Chromium-based remote browsers. The official Playwright CDP documentation is worth reading once, because it clarifies that connectOverCDP is Chromium-only — Firefox and WebKit are not supported over CDP, which matters if your workload depends on cross-engine testing.

A minimal TypeScript example

The following connects to a hosted Chromium session over CDP, opens a page, and extracts rendered content. Replace the endpoint with the one your runtime returns.

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

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

async function createSession(): Promise<SessionInfo> {
  // Your runtime's session-creation endpoint. The exact shape depends on
  // the provider; check /documentation for the current contract.
  const res = await fetch(`${process.env.BROWSER_API_URL}/sessions`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.BROWSER_API_KEY}`,
    },
    body: JSON.stringify({ profileId: "checkout-agent" }),
  });

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

  const data = await res.json();
  return { cdpUrl: data.cdpUrl, sessionId: data.id };
}

async function run(): Promise<void> {
  const session = await createSession();
  let browser: Browser | undefined;

  try {
    browser = await chromium.connectOverCDP(session.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" });
    await page.waitForLoadState("networkidle");

    const heading = await page.locator("h1").innerText();
    console.log({ sessionId: session.sessionId, heading });
  } finally {
    // Closing the connection releases the client; the runtime ends the
    // session on its own schedule or when you call its stop endpoint.
    await browser?.close();
  }
}

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

Two details matter in production. First, browser.close() on a CDP connection closes the *connection*, not necessarily the remote browser — check your provider's semantics and call its explicit stop endpoint if you need deterministic teardown. Second, networkidle is a heuristic, not a guarantee; for pages with long-polling or analytics beacons, wait on a specific selector or a custom predicate instead.

Production criteria for running in browser remotely

Once you move past a demo, the questions change. Here is what to evaluate.

Session isolation

Every agent or job should get its own browser context at minimum, and ideally its own process. Shared contexts leak cookies, localStorage, and cached credentials between tasks — a correctness bug that is hard to reproduce and easy to miss in testing. Ask whether the runtime isolates at the process level and whether profiles are scoped per session.

Persistent profiles

Some workflows need to stay logged in across sessions: a support agent that keeps a customer portal open, or a scraper that maintains a warm session. Persistent profiles let you reuse authentication state without re-running a login flow every time. The trade-off is that a persistent profile is a shared secret — treat profile IDs as credentials and rotate them when a workflow changes hands.

Connection stability

Remote CDP connections drop. Networks flap, sessions time out, and long-running agents hit idle limits. Your client code needs reconnect logic or a supervisor that detects a dead connection and provisions a fresh session. Do not assume a single WebSocket will live for the duration of a multi-hour task.

Observability

When something fails on a remote browser, you cannot open DevTools on your laptop. You need a live viewer to watch the session in real time, plus logs, network captures, and screenshots on failure. If the runtime does not expose these, debugging becomes guesswork. See remote control browser for how live session control works in practice.

Proxy and browser settings

Many workloads need a specific egress IP or region. Hosted runtimes typically expose configurable proxy and browser settings per session. Be precise about what you need: a residential proxy in a specific country is a different requirement from a datacenter IP with a fixed region. Prefer runtimes that let you set these per session rather than globally.

Cost model

Remote browsers are usually metered per browser-hour. That means idle sessions cost money. Close sessions aggressively, set timeouts, and measure actual usage before you commit to a concurrency plan. Current rates are on /pricing; do not plan capacity against numbers you have not verified.

When to run in browser locally, and when not to

Local execution still wins in a few cases:

  • Development and debugging. Iterating on selectors and flows is faster against a local browser with DevTools attached.
  • Offline or air-gapped environments. If the target is an internal app with no external network, a local browser may be the only option.
  • Single-run scripts. If you run something once a week, the overhead of a remote runtime is not worth it.

Remote execution wins when:

  • You need concurrency. Ten parallel agents on one laptop will thrash. A hosted runtime provisions sessions independently.
  • You need isolation guarantees. Separate processes per session, not shared contexts.
  • You need persistence. Profiles that survive across workers and deploys.
  • You need to decouple from the caller. A serverless function or a short-lived CI job cannot host a long-running browser; a remote session can outlive the caller.
  • You need a consistent environment. Pinning a Chromium version and OS across all runs removes a class of "works on my machine" failures.

A useful heuristic: if your automation is part of a product or an agent that runs continuously, run in browser remotely. If it is a tool you invoke by hand, local is fine.

Common mistakes when moving to remote

A few patterns show up repeatedly in migrations:

  • Assuming `connectOverCDP` gives you a fresh browser. It connects to whatever the endpoint exposes. If the runtime reuses instances, you may inherit state. Confirm the isolation model.
  • Forgetting to close sessions. Orphaned sessions accrue cost and can hit concurrency limits. Wrap session lifecycle in try/finally and add a server-side timeout as a backstop.
  • Hardcoding the CDP URL. Endpoints are per-session and short-lived. Fetch them at runtime.
  • Ignoring navigation timeouts. Remote networks have different latency characteristics than localhost. Set explicit timeouts and handle them.
  • Treating the live viewer as optional. It is your only window into a remote session. Build debugging around it from day one.

If you are coming from a local Playwright setup, the remote browser online guide walks through the migration path in more detail, and the remote web browser overview covers the broader runtime model.

A practical checklist before you commit

Before you standardize on any remote runtime, verify:

  • [ ] Sessions are isolated at the process level, not just the context level.
  • [ ] Persistent profiles are supported and scoped correctly.
  • [ ] The CDP endpoint is reachable from your deployment environment (check egress rules).
  • [ ] A live viewer exists and works for your team.
  • [ ] Proxy and browser settings are configurable per session.
  • [ ] Session teardown is deterministic and documented.
  • [ ] Pricing is metered in a way you can forecast; see /pricing.
  • [ ] The runtime's Chromium version is pinned and upgradeable on your schedule.

If most of those boxes are checked, you have a runtime you can build on. If several are missing, you will end up rebuilding them yourself — which is usually the thing you were trying to avoid by going remote in the first place.

Summary

"Run in browser" describes executing code inside a real browser engine. Doing it locally is simple and fine for development. Doing it remotely is the same protocol with different operational constraints: isolation, persistence, observability, and cost become first-class concerns. CDP is the transport, connectOverCDP is the Playwright entry point, and the runtime you choose determines whether those concerns are handled for you or become your problem. Start with the documentation to see the session contract, and evaluate against the checklist above rather than against a demo.