Guides
Connect Playwright
Point Playwright at a session's cdp_url and keep the code you already have.
At the end your Playwright script drives a hosted session instead of a local browser. You need an API key and playwright-core for TypeScript, or playwright and requests for Python. No local browser is needed.
Create a session and connect
Create the session over HTTP, then pass its cdp_url to connectOverCDP. The URL is a browser-level Chrome DevTools Protocol endpoint and carries its own token, so the connect call needs no headers.
import { chromium } from "playwright-core";
const base = process.env.SPHYNX_URL;
const headers = {
Authorization: `Bearer ${process.env.SPHYNX_API_KEY}`,
"Content-Type": "application/json",
};
const created = await fetch(`${base}/v1/sessions`, {
method: "POST",
headers,
body: JSON.stringify({ os: "mac" }),
});
const session = await created.json();
const browser = await chromium.connectOverCDP(session.cdp_url);
const context = browser.contexts()[0];
const page = context.pages()[0] ?? (await context.newPage());
await page.goto("https://example.com");
console.log(await page.title());
await browser.close(); // disconnects only; the session keeps running
await fetch(`${base}/v1/sessions/${session.id}`, { method: "DELETE", headers });import os
import requests
from playwright.sync_api import sync_playwright
base = os.environ["SPHYNX_URL"]
headers = {"Authorization": f"Bearer {os.environ['SPHYNX_API_KEY']}"}
session = requests.post(
f"{base}/v1/sessions", headers=headers, json={"os": "mac"}, timeout=60
).json()
with sync_playwright() as p:
browser = p.chromium.connect_over_cdp(session["cdp_url"])
context = browser.contexts[0]
page = context.pages[0] if context.pages else context.new_page()
page.goto("https://example.com")
print(page.title())
browser.close() # disconnects only; the session keeps running
requests.delete(f"{base}/v1/sessions/{session['id']}", headers=headers, timeout=30)The script prints the page title:
Example DomainKeep the fingerprint intact
The session already has a consistent identity. These rules keep it that way.
- Use the existing context,
browser.contexts()[0]. A new context loses the session's identity and storage, so do not callbrowser.newContext(). - Open more pages with
context.newPage()on that context. - Do not set a viewport, user agent, locale or timezone from the client. The session already has consistent values.
- Do not close the session's last page; open the new page first. A session with no page has no tabs, and drive calls answer
tab_not_founduntilPOST /v1/sessions/{id}/tabsopens one.
Disconnect and reconnect
browser.close() on a CDP connection only disconnects. The session keeps running, with its pages and cookies, until you delete it or it times out. Traffic on the connection resets the idle clock, so a script that is working keeps its session alive.
The token in cdp_url is valid for token_expires_in_seconds, 1800 when issued, and can be reused until then. After that, ask for a new URL with POST/v1/sessions/{id}/tokens and connect again.
const minted = await fetch(`${base}/v1/sessions/${session.id}/tokens`, {
method: "POST",
headers,
});
const { cdp_url } = await minted.json();
const browser = await chromium.connectOverCDP(cdp_url);
const page = browser.contexts()[0].pages()[0]; // the page you leftminted = requests.post(
f"{base}/v1/sessions/{session['id']}/tokens", headers=headers, timeout=30
).json()
browser = p.chromium.connect_over_cdp(minted["cdp_url"])
page = browser.contexts[0].pages[0] # the page you left{
"cdp_url": "wss://api.example/v1/sessions/sess_9f2c.../cdp?token=...",
"live_view_url": "https://api.example/v1/sessions/sess_9f2c.../view?token=...",
"token_expires_in_seconds": 1800
}Limits on the connection
- At most 10 connections to one session at a time. One more fails the handshake with 429
connection_limit. - Text frames only, without WebSocket compression. A binary frame or a message over 16 MiB ends the connection.
- Three CDP commands are refused, because they would let traffic leave the session around its proxy:
Target.createBrowserContextwithproxyServerorproxyBypassList,Target.exposeDevToolsProtocolandTarget.setRemoteLocations. Each is answered with a CDP error.
Use the HTTP calls on the same session
While Playwright is attached you can still call the HTTP endpoints on the same session, for example to read the current page as Markdown.
curl -s -X POST "$SPHYNX_URL/v1/sessions/$SESSION/extract" \
-H "Authorization: Bearer $SPHYNX_API_KEY" \
-H "Content-Type: application/json" \
-d '{"formats": ["markdown"]}'What can go wrong
| HTTP | Code | When |
|---|---|---|
| 403 | invalid_token | The token in cdp_url is bad or expired. The WebSocket handshake fails. Mint a new URL |
| 410 | session_closed | The session has ended, so there is nothing to connect to |
| 429 | connection_limit | The session already has 10 CDP connections. The WebSocket handshake fails. Disconnect one first |
| 429 | concurrency_limit | On create: too many live sessions for this key. Retry-After is set |
| 502 | session_launch_failed | On create: the browser failed to start |
| 503 | capacity_unavailable | On create: no browser capacity. Retry-After is set |
If a connection drops in the middle of a script, read the session with GET /v1/sessions/{id}: close_reason says whether it reached timeout, sat idle for idle_timeout or the browser exited.
A session's cookies and storage end with it. A later session with the same sphynx_id is the same device, with none of them.
Next
- Connect: the CDP endpoint and its token.
- Connect Puppeteer: the same session from Puppeteer.
- Live view: watch the session while the script runs.
- Concepts: when a session ends and how the idle clock works.