Skip to main content
Once you’ve created a session, use the CDP URL to connect your automation framework.

Connect to a Session

import { chromium } from "playwright";
import BrowsercashSDK from "@browsercash/sdk";

const client = new BrowsercashSDK({
  apiKey: process.env.BROWSER_API_KEY,
});

const session = await client.browser.session.create();
const browser = await chromium.connectOverCDP(session.cdpUrl);

// Get existing context or create new one
const context = browser.contexts()[0] || (await browser.newContext());
const page = context.pages()[0] || (await context.newPage());

// Automate
await page.goto("https://example.com");
console.log(await page.title());

// Cleanup
await browser.close();
await client.browser.session.stop({ sessionId: session.sessionId });

Best Practices

  • Handle reconnections — If your connection drops, the browser keeps running. Reconnect using the same CDP URL.
  • Set timeouts — Sessions terminate after 1 hour. For long tasks, monitor and create new sessions as needed.
  • Close gracefully — Always stop sessions when done to avoid billing for idle time.
  • Use contexts — Browser Cash sessions may have an existing context. Always check browser.contexts() before creating a new one.

Error Handling

try {
  const browser = await chromium.connectOverCDP(session.cdpUrl);
  // ... automation
} catch (error) {
  if (error.message.includes("connection refused")) {
    // Session may have expired — create a new one
    const newSession = await client.browser.session.create();
    // Retry with new session
  }
} finally {
  await client.browser.session.stop({ sessionId: session.sessionId });
}

Next Steps