← Templates Playwright template

Playwright session control

Move an existing Playwright script from local browser launch to a BrowserCity managed session.

PlaywrightSessionsTesting

Use this when your code already speaks Playwright and you want BrowserCity to host the browser. The main change is creating a BrowserCity session, connecting to its returned endpoint, and reusing the prepared context/page.

Minimal executable examples

browsercity-playwright.ts
import { chromium } from 'playwright';const apiKey = process.env.BROWSERCITY_API_KEY;if (!apiKey) {  throw new Error('Set BROWSERCITY_API_KEY before running this script.');}const response = await fetch('https://api.browser.city/v1/sessions', {  method: 'POST',  headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },  body: JSON.stringify({ browser: 'chromium' }),});if (!response.ok) {  throw new Error(`Create session failed: ${response.status} ${await response.text()}`);}const { endpoint, token, id } = await response.json() as { endpoint: string; token: string; id: string };try {  const browser = await chromium.connect(endpoint, {    headers: { Authorization: `Bearer ${token}` },  });  const context = browser.contexts()[0];  const page = context?.pages()[0];  if (!page) {    throw new Error('BrowserCity session did not return a ready page.');  }  await page.goto('https://example.com');  console.log(await page.title());} finally {  await fetch(`https://api.browser.city/v1/sessions/${id}`, {    method: 'DELETE',    headers: { Authorization: `Bearer ${apiKey}` },  });}

Migration steps

  1. Create a BrowserCity session before your Playwright script starts.
  2. Connect to endpoint with the returned token bearer header.
  3. Reuse the prepared context/page that BrowserCity returns on connect.
  4. Delete the BrowserCity session during cleanup.

Cost and plan notes

For test suites, estimate the number of workers times average runtime. If you add managed residential/mobile egress or BYOP traffic, include that traffic in /pricing-calculator before increasing parallelism.

[ 06 / 06 ] — Get Started

Give your AI agents the web.

Start for free. No credit card required. Private sessions by default.