How to Connect Playwright to a Remote Browser with CDP
TL;DR
Playwright connects to an existing Chromium browser with chromium.connectOverCDP(); launch() starts a different browser.
A managed session must be ready before you request short-lived CDP credentials and attach the client.
The lifecycle API key and the CDP access token authenticate different connections and cannot be substituted for each other.
A successful WebSocket handshake proves connectivity; a page assertion proves that your task reached the expected result.
Reusing an existing signed-in tab requires explicit page selection inside the same running session.
Disconnecting Playwright does not confirm that the managed browser has stopped; stop the session separately and verify ended.
What Does Playwright Connect over CDP Actually Do?
Playwright connect over CDP attaches your Node.js program to an already running Chromium browser through the Chrome DevTools Protocol. The script runs on your laptop or worker; the browser renders pages and makes website requests on the remote host. A hosted endpoint therefore removes the need to install a browser binary on that worker, while leaving selectors, assertions, and task decisions in your code.
Nstdata Cloud Browser provides managed cloud browsers for browser automation and AI agents. This tutorial uses a dashboard-created session so that you can observe the browser while proving the connection. The final task opens a public example page, checks its HTTP response, and verifies its heading. Nothing is submitted to an account or form.
The distinction matters when extending an existing Playwright web scraping workflow: replace the browser connection deliberately, then check context selection and cleanup. Copying a remote endpoint into a local launch configuration does not create the same execution model.
Which Playwright Connection Method Should You Use?
Use connectOverCDP() for a Chromium CDP endpoint, connect() for a compatible Playwright server, and launch() when your application owns a local browser process. These methods speak to different server contracts. The Playwright BrowserType API identifies CDP as Chromium-only and lower fidelity than the native Playwright protocol.
Method
Remote surface
Appropriate starting point
chromium.launch()
A browser executable started by your code
Local development and a browser you operate yourself
chromium.connect()
A Playwright browser server endpoint
A controlled Playwright client/server deployment
chromium.connectOverCDP()
A Chromium CDP endpoint
An existing browser or compatible managed session
CDP compatibility does not promise identical behavior for every advanced Playwright feature. Test the operations your application actually needs against the managed browser. Basic navigation passing does not establish that tracing, extension workflows, downloads, or every context option behave like a locally launched browser.
What Do You Need Before Connecting?
You need Node.js 22.12 or later, playwright-core, an accessible Nstdata workspace, a ready session, and the correct business API key. Obtain a personal key under Settings → Account, or a team member key under Members. Confirm workspace balance and the current concurrency allowance before launching a browser.
Field
Where it comes from
Where it belongs
NSTDATA_API_KEY
Your account or team key
Lifecycle HTTP header x-api-key, without Bearer
NSTDATA_TEAM_ID
A joined team, when using a personal key
Optional x-team-id on every lifecycle request
NSTDATA_SESSION_ID
The session you launched
Session lookup and credential endpoint paths
cdpUrl
Automation-credentials response
connectOverCDP() endpoint argument
headerName, accessToken
The same credential response
CDP connection headers
expiresAt
The same credential response
Expiration check before attachment
A team member key is bound to its team; adding another team ID does not switch it. Keep workspace context consistent throughout the workflow. Do not use a dashboard login JWT as the business API key.
The client below was exercised through a real CDP connection to a fresh, isolated local Chromium. The Nstdata credential branch requires your API key and was not executed against a paid account. Local execution verifies the client operations; it does not establish managed-account authentication or billing behavior.
How Do You Connect Playwright to Nstdata Cloud Browser?
Connect by creating a visible session, retrieving credentials for that same session, and passing those credentials to Playwright. The current Browser Automation guide documents the lifecycle and credential separation used below.
Step 1: Launch a browser session
Open Cloud Browser → Playground, select the intended workspace, and configure Session Name, Proxy Country, Resource Class, and Session Duration. Click Launch Browser. Wait until the tools area shows Running and the preview is available.
[Screenshot: Playground showing a running session and the CDP tools area, with all access URLs and tokens hidden.]
Choose proxy and environment settings before launch. The proxy country selects an exit location; it does not promise a fixed IP. The session duration is an automatic lifetime limit, distinct from the navigation timeout in your script.
Step 2: Install the client dependency
Create a project directory and install the version used for this example. playwright-core supplies the client without downloading a browser for the worker.
mkdir remote-playwright-demo
cd remote-playwright-demo
npm init -ynpminstall --save-exact playwright-core@1.65.1
Step 3: Save the connection helper
Save the following module as cloud-api.mjs. It looks up the original session, requires state === 'ready', requests credentials, and validates the returned session identity and expiration. The loopback-only branch is for an isolated developer test browser; production follows the Nstdata credential branch.
Credential prerequisite: Nstdata API requests in this module require your key, session ID, and optional team context. Supply them locally; never paste their real values into source control or a shared log.
const root ='https://api.nstdata.io/api/v1/cloud-browser';exportasyncfunctionapi(method, path, body){const key = process.env.NSTDATA_API_KEY;if(!key)thrownewError('Set NSTDATA_API_KEY');const headers ={'x-api-key': key };if(process.env.NSTDATA_TEAM_ID) headers['x-team-id']= process.env.NSTDATA_TEAM_ID;if(body) headers['content-type']='application/json';let response;try{ response =awaitfetch(root + path,{ method, headers,redirect:'error',body: body ?JSON.stringify(body):undefined,signal:AbortSignal.timeout(20_000),});}catch{throwObject.assign(newError('API transport failed; reconcile the original operation'),{retryable:true});}const retryable = response.status===429|| response.status>=500;let result;try{ result =await response.json();}catch{throwObject.assign(newError('Invalid API JSON'),{ retryable });}if(!response.ok|| result.err===true|| result.success===false){throwObject.assign(newError(`Cloud Browser API HTTP ${response.status}`),{ retryable });}if(!result.data)thrownewError('Missing API data');return result.data;}exportasyncfunctionconnection(id){if(!id)thrownewError('Set NSTDATA_SESSION_ID');const path =`/sessions/${encodeURIComponent(id)}`;const session =awaitapi('GET', path);if(session.state!=='ready')thrownewError(`Session is ${session.state}, not ready`);const c =awaitapi('POST', path +'/automation-credentials');if(c.sessionId!== id ||!c.headerName||!c.accessToken||!(Date.parse(c.expiresAt)>Date.now())||newURL(c.cdpUrl).protocol!=='wss:'){thrownewError('Invalid or expired CDP credentials');}return{endpoint: c.cdpUrl,headers:{[c.headerName]: c.headerName.toLowerCase()==='authorization'?`Bearer ${c.accessToken}`: c.accessToken},};}exportasyncfunctionendpoint(){// An isolated local CDP endpoint can test the client without managed credentials.if(process.env.LOCAL_CDP_URL){const url =newURL(process.env.LOCAL_CDP_URL);if(!['127.0.0.1','localhost','[::1]'].includes(url.hostname)){thrownewError('LOCAL_CDP_URL must use loopback');}return{endpoint: url.href,headers:{}};}returnconnection(process.env.NSTDATA_SESSION_ID);}
Step 4: Save the page verification task
Save this script as connect-playwright.mjs. The script creates a page inside the default context and closes only that page before releasing the client. Read the connected-browser cleanup semantics before adapting cleanup to a shared session.
Credential prerequisite: the managed execution path requires the environment settings from Step 3. The page logic and real CDP handshake were verified locally.
import{ chromium }from'playwright-core';import{ endpoint }from'./cloud-api.mjs';asyncfunctionmain(){const config =awaitendpoint();let browser;let page;try{ browser =await chromium.connectOverCDP(config.endpoint,{headers: config.headers,timeout:30_000,});const context = browser.contexts()[0];if(!context)thrownewError('Default context is unavailable'); page =await context.newPage();const response =await page.goto(process.env.TARGET_URL||'https://example.com/',{waitUntil:'domcontentloaded',timeout:30_000,});if(!response?.ok())thrownewError('Navigation did not return a successful response');const heading =await page.getByRole('heading',{name:'Example Domain',exact:true}).innerText();console.log(JSON.stringify({connected: browser.isConnected(), heading,taskPassed:true}));}finally{try{if(page)await page.close();}finally{if(browser)await browser.close();}}}main().catch(()=>{console.error("Browser task failed; inspect private diagnostics and the original session."); process.exitCode=1;});
Step 5: Run the connection test
Create a private .env file containing NSTDATA_API_KEY and NSTDATA_SESSION_ID, with your real values after =. Add NSTDATA_TEAM_ID only if applicable. Exclude this file from version control, then run the command below. Leave LOCAL_CDP_URL unset for the managed session.
node --env-file=.env connect-playwright.mjs
For the default target, success is a JSON object containing connected: true, heading: "Example Domain", and taskPassed: true. The role-based locator checks the page result rather than treating a connected socket as task completion. If you change TARGET_URL, change the assertion to match the intended authorized page.
Step 6: Stop the managed session
Return to the original session and click Stop Browser. Wait for the session to finish. In an API-owned job, call DELETE /api/v1/cloud-browser/sessions/{sessionId} and poll the same session until its state is ended. Closing the preview tab or releasing Playwright is not this stop operation.
How Does Cloud Browser Fit a Production Playwright Workflow?
Nstdata Cloud Browser fits a Playwright workflow when your team wants managed browser execution with visible session controls. Your application retains ownership of the task, output schema, and acceptance criteria. The service supplies the remote browser session and its connection surface. The same running browser can be viewed manually and driven through CDP. That makes a failed task inspectable without assuming the script chose the correct page or account.
Managed execution: attach a client from a worker that does not carry its own Chromium installation; retain application-level timeouts and assertions.
Session-level proxy configuration: use the selected built-in proxy configuration without adding a separate proxy gateway to this client script; measure proxy traffic alongside browser runtime.
Live inspection: observe the active page and available diagnostics when a selector fails; inspection does not automatically repair application logic.
Why Does a CDP Connection Fail or Open the Wrong Page?
A CDP connection fails when its endpoint, credentials, session state, or network path is invalid; the wrong page usually indicates incorrect context or tab selection.
Symptom
Likely cause
Next action
Lifecycle HTTP authentication fails
Wrong key or team context
Check x-api-key and consistent x-team-id
CDP authorization fails
Expired token or incorrect header
Query the same ready session and request fresh credentials
Browser connects but the application is signed out
A new page/context or another session was used
Select the existing authorized tab explicitly
Heading assertion times out
Wrong page, redirect, or changed content
Inspect the selected page and expected marker
Session is ended
Lifetime expired or browser was stopped
Start a deliberately new task; do not reuse old credentials
Avoid repeatedly restarting the entire job to troubleshoot authentication. A fresh session ID can hide the original failure and create additional runtime usage. Keep request/session identifiers in operational logs, while redacting access tokens and complete CDP URLs.
What Should You Verify Before Shipping the Integration?
Verify the managed connection, the actual page task, and confirmed session shutdown as separate checks. Run a narrow production canary with the intended workspace and target, record its session ID and accepted output, and confirm ended afterward. Expand only after your required interactions work with the remote browser. This gives the team a repeatable acceptance test instead of a connection-only demo.
Q: Can Playwright connect over CDP to Firefox or WebKit?
No. Playwright's CDP connection is for Chromium-based browsers. Use the appropriate supported browser workflow when your test requires Firefox or WebKit.
Q: Do I install Chromium on the worker?
No browser binary is required for this remote connection example. Install playwright-core on the worker and connect to the browser running in the managed session.
Q: Does the quick-start script reuse my signed-in tab?
No. This script creates a new page. For a manual sign-in handoff, select the existing page by its expected origin, path, and account marker inside the same running session.
Q: Can I use the business API key as the CDP token?
No. Use the business key for lifecycle requests, then obtain the short-lived accessToken and headerName from the automation-credentials response.
Q: Does disconnecting reset the session duration?
No. Reconnecting a client does not extend the managed session lifetime. Query the original state before requesting new credentials.
Q: Is a successful heading check enough for production?
The heading check is sufficient for this connection demonstration. Production tasks need their own acceptance criteria, failure handling, and confirmed cleanup, using only websites and accounts you are authorized to automate.
Let an operator sign in through Live View before a script verifies the same application tab. Define ownership, account assertions, approval boundaries, and cleanup without embedding a password in the automation.
Ivy Lin
Nov. 17th 2026
Launch cloud browsers on demand
Handle fingerprints and CAPTCHAs
Automate workflows and power AI agents
From web scraping and testing to AI-driven automation, run it all in the cloud.