A Puppeteer remote browser connection uses puppeteer.connect() and the remote browser's WebSocket endpoint.
puppeteer-core is appropriate when your worker connects to a browser that another service already runs.
Nstdata lifecycle HTTP calls use a business API key; CDP connections use separately issued, short-lived credentials.
Use browserWSEndpoint for the returned CDP WebSocket URL, and pass authentication through the returned header name.
Set defaultViewport: null when you want to preserve the remote browser's existing viewport rather than applying Puppeteer's default override.
browser.disconnect() leaves the remote browser running; stop the Nstdata session separately after the task.
What Is a Puppeteer Remote Browser Connection?
A Puppeteer remote browser connection lets a Node.js client control an already running browser instead of launching a local executable. Puppeteer sends automation commands over a protocol connection; the browser performs navigation, JavaScript execution, and rendering on its own host. This is useful when workers should remain small or an operator needs to see the same session that the script controls.
Nstdata Cloud Browser provides managed cloud browsers for browser automation and AI agents with a CDP connection surface. In this walkthrough, the dashboard owns session creation and stopping, while a small Puppeteer client owns one temporary page. Separating those responsibilities makes the first integration easier to inspect.
The example validates a public page without logging into an account or submitting data. For a broader framework introduction, the existing Node.js Puppeteer and Playwright guide covers local page automation. This article focuses on the extra contract introduced by a remote browser: endpoint identity, credential lifetime, page ownership, and shutdown.
Use puppeteer-core when your application supplies an existing browser endpoint and does not need Puppeteer's managed browser download. The Puppeteer installation guide distinguishes the full package from the core library. Choosing the core package does not create a browser; a compatible remote browser must already be available.
Decision
Use in this tutorial
Browser creation
Nstdata Playground
Client package
puppeteer-core
Connection method
puppeteer.connect()
Endpoint option
browserWSEndpoint
Page ownership
Create and close one demonstration page
Managed cleanup
Stop the original session in the dashboard
Do not confuse running Puppeteer on your Node.js worker with packaging its API inside a client webpage. This example is a server-side script. Business API keys stay in the worker environment and never enter a website's JavaScript bundle.
What Credentials and Settings Do You Need?
You need a ready Cloud Browser session, Node.js 22.12 or later, and a business API key for the workspace that owns the session. Obtain a personal key from Settings → Account, or use a team member key from Members. Check the current workspace balance and concurrency allowance before launch.
The session ID identifies the running browser. NSTDATA_API_KEY becomes the x-api-key lifecycle header without a Bearer prefix. A personal key can optionally select a joined team through NSTDATA_TEAM_ID, sent as x-team-id; a team member key uses its bound team. Keep this context the same for lookup and credential issuance.
The credential endpoint returns cdpUrl, headerName, accessToken, and expiresAt for the same session. Those values authenticate the WebSocket connection. They are not a reusable substitute for the business API key, and an old token does not revive an ended browser.
This tutorial's Puppeteer handshake, navigation, assertion, and disconnect were executed against an isolated local Chromium. The managed-account credential branch requires your key and was not run against a paid Nstdata workspace. Treat your first managed execution as an integration canary, with session shutdown included in acceptance.
How Do You Connect Puppeteer to a Cloud Browser?
Connect Puppeteer by launching a session, installing the core client, retrieving session-specific credentials, and supplying them to puppeteer.connect(). The Puppeteer connection API is the client reference for this operation.
Step 1: Create a visible remote session
Open Cloud Browser → Playground and select the intended personal or team workspace. Set Session Name, Proxy Country, Resource Class, and Session Duration, then click Launch Browser. Wait for Running and a usable preview.
[Screenshot: A running Cloud Browser session with the workspace and session name visible; hide access links, tokens, and private page content.]
Configure proxy country before the session starts. The client inherits the session's configured network path, so this example does not pass a second proxy URL into Puppeteer. Proxy country, language, and timezone are distinct settings; selecting a country does not guarantee a fixed address or an authenticated website session.
Step 2: Install Puppeteer-core
Initialize a project and install the exact client version used for the example. Keep the generated lockfile so another worker can reproduce the dependency choice.
mkdir cloud-puppeteer-demo
cd cloud-puppeteer-demo
npm init -ynpminstall --save-exact puppeteer-core@25.17.0
Step 3: Save the credential helper
Save the following code as cloud-api.mjs. It queries the session before requesting automation credentials and constructs the CDP header from the returned field. When that field is Authorization, the value receives the Bearer prefix; other returned header names receive the raw access token.
Credential prerequisite: the Nstdata branch requires your business API key and ready session. The helper's loopback option exists only for a separate local test browser and must remain unset for the managed workflow.
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 browser task
Save this script as connect-puppeteer.mjs. It opens one page, checks the navigation response, and verifies the expected heading before closing the page and disconnecting. The timeout values bound this demonstration; they are not service quotas.
Credential prerequisite: managed execution requires the key and session environment settings described above. The client branch was executed through a real local CDP connection.
defaultViewport: null preserves the existing viewport instead of imposing a Puppeteer default. It does not change the session's screen fingerprint, proxy country, or Live View zoom. If your task needs a particular viewport, set it intentionally and verify the rendered layout after attachment.
Step 5: Run the page assertion
Create a private .env file with NSTDATA_API_KEY and NSTDATA_SESSION_ID, plus NSTDATA_TEAM_ID only when needed. Exclude it from version control. Run the following command from the directory containing both modules.
node --env-file=.env connect-puppeteer.mjs
For the default target, the script prints a JSON object with heading: "Example Domain" and taskPassed: true. An endpoint connection alone would not produce that assertion. If you customize the target, update the selector and expected value together; an unrelated page with an h1 is not sufficient evidence.
Step 6: Stop the session you created
Click Stop Browser in the original session and wait for completion. The Puppeteer disconnect method releases the client connection while leaving the browser running. Managed browser shutdown remains a separate action.
For an API-owned job, stop with DELETE /api/v1/cloud-browser/sessions/{sessionId} and poll until state is ended. A worker crash can skip ordinary cleanup, so retain the session ID outside transient process memory. Use the current Browser Automation lifecycle when implementing that owner service.
How Can Nstdata Support a Puppeteer Workflow Beyond the Demo?
Nstdata Cloud Browser supplies the hosted browser while Puppeteer retains control of navigation and page interaction. A developer can attach a script from an existing job runner without deploying Chromium on every worker. An operator can inspect the same running browser when a task needs attention. Session configuration provides a controlled launch point for resources and proxy location. The application still decides which page is valid, which output is acceptable, and when the session should stop.
Managed browser runtime: move browser execution out of the worker deployment, then test your specific Puppeteer operations against that runtime.
Built-in proxy configuration: choose the session's supported proxy country without maintaining a separate proxy gateway in the example client; monitor the resulting traffic cost.
Live View and diagnostics: observe rendering and inspect available Console or Network information when a page wait fails.
Explicit lifecycle: use session states to distinguish connection problems from an expired or stopped browser.
Review Cloud Browser usage pricing before scaling. Runtime, proxy traffic, and optional CAPTCHA usage are separate cost components; a remote connection is not a fixed-cost substitute for unlimited browser work. The Cloud Browser product introduction describes the product boundary, and the Playwright hands-on tutorial provides a complementary approach to browser task design.
How Do You Reuse an Existing Tab Without Losing State?
Reuse an existing tab by identifying it inside the same session rather than creating a new browser or choosing the first entry in browser.pages(). List the available pages, match an expected origin and pathname, and require exactly one candidate. Then verify an application-specific account or workspace marker before reading data or clicking controls.
The demonstration intentionally uses newPage() because it has no signed-in state to preserve. A human handoff has a different contract: do not navigate the selected tab back to a login URL, create an incognito context, or assume a new session contains the old session's cookies. An application can also invalidate its login independently of the browser's lifetime.
Why Does the Browser Connect but the Task Fail?
The browser can connect successfully while the selected page is redirected, incomplete, signed out, or different from the expected application. Diagnose the task layer after checking the connection layer.
Symptom
Cause to investigate
Fix
Credential request fails
API key or team mismatch
Keep business authentication and workspace context consistent
WebSocket rejects authentication
Expired or misapplied CDP token
Request fresh credentials for the same ready session
Heading is missing
Navigation or rendering did not reach the expected state
Check response, page URL privately, and a specific readiness marker
An existing login is absent
New tab/context or wrong browser session
Select the original session and intended page
Browser remains in history as running
Client disconnected without stop
Stop through the lifecycle owner and confirm ended
Do not add arbitrary sleeps before checking these conditions. Wait for the particular element or response that proves readiness. A long timeout merely delays a failure when the script is watching the wrong tab.
What Is a Sensible First Production Test?
A sensible first production test performs one authorized, read-only task and records its result independently of connection success. Use a short session duration, an explicit task timeout, and an owner responsible for stopping the browser. Keep the accepted output and session ID, redact credentials, and verify shutdown before increasing concurrency. This turns the remote connection into an operational workflow you can account for.
Q: Does Puppeteer-core download a browser for this example?
No. The example connects to an existing remote browser. Install the core client and supply the endpoint returned for the managed session.
Q: Should I put the CDP URL in browserURL?
Use browserWSEndpoint for the returned CDP WebSocket URL in this tutorial. Do not interchange a WebSocket endpoint with a dashboard page or Live View URL.
Q: Does disconnecting stop browser usage?
No. browser.disconnect() leaves the browser running. Stop the Nstdata session separately and confirm its ended state.
Q: Can I share one browser among unrelated customer jobs?
A shared browser can expose state and allow competing actions. Assign session ownership and isolate unrelated jobs rather than relying on tab order to separate customers.
Q: Does built-in proxy configuration guarantee website access?
No. Proxy configuration supplies a network path. Website permissions, login requirements, rendering behavior, and task acceptance still need independent checks.
Q: What should I do after a connection drops?
Query the original session first. If it remains ready, request fresh credentials and rediscover the intended page; if it ended, begin a new authorized task and restore only state your application is permitted to reuse.
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.