Cloud Browser Session Management: Create, Reconnect, and Stop Safely
TL;DR
A cloud browser session lifecycle tracks the managed browser resource, independently of a website login or client connection.
Persist a UUID v4 requestId and the complete create body before sending a session creation request.
Retry an uncertain creation with the same ID and identical body; changed configuration requires a new ID.
ready means the browser is available for attachment, not that your business task has succeeded.
Refreshing Live View or reconnecting CDP does not reset the browser lifetime.
A stop request is complete only when the original session reaches ended; stopping is intermediate.
What Is a Browser Session Lifecycle?
A browser session lifecycle is the sequence of states that a managed browser passes through from creation to termination. It describes the resource your automation consumes. A website authentication session describes whether a particular site considers a user signed in, while a CDP client connection describes whether your program is currently attached. These three lifetimes can end independently.
Nstdata Cloud Browser provides managed cloud browsers for browser automation and AI agents. Managing that resource explicitly lets a team recover from worker failures, coordinate a human handoff, and account for runtime after the page task finishes. The Cloud Browser introduction provides product context; this guide focuses on the ownership and state transitions needed in an actual job runner.
For example, your script may lose its WebSocket while the browser remains ready and signed into an application. Conversely, the socket can remain connected while the website expires the login. A single success flag cannot represent both conditions accurately.
Your application should handle creating, unknown, ready, stopping, ended, and failed from the session response's state field. Do not look for an undocumented status field or infer resource state from a preview image.
State
Meaning for the controller
Appropriate next action
creating
Browser startup is in progress
Poll the same session within a deadline
unknown
Current resource state is uncertain
Reconcile the original operation; avoid duplicate creation
ready
Browser can accept a connection
Obtain credentials and validate the task's page state
stopping
Shutdown has been requested
Continue checking for ended
ended
This session has finished
Do not attempt to revive it with old credentials
failed
The resource has failed
Capture the failure context and resolve cleanup before a new attempt
The current Browser Automation API guide is the contract for these values. Keep a separate application task state such as awaiting-human, working, accepted, or rejected. Those are your own job states, not additional Cloud Browser API states.
What Endpoints and Parameters Do You Need?
You need options, creation, inspection, credential issuance, and deletion endpoints under https://api.nstdata.io/api/v1/cloud-browser. Retrieve current options before building the create body because resource classes, countries, and allowed durations depend on the current service configuration.
The create example also supplies targetUrl, recording: false, and captchaSolver: { enabled: false }. Review warnings and effectiveConfiguration from the creation response when customizing it. A configuration warning deserves investigation before the job is allowed to perform meaningful work.
Use x-api-key without Bearer for lifecycle HTTP calls. Obtain a personal key under Settings → Account or a bound team member key under Members. With a personal key, optional x-team-id selects a joined team; keep the same value on every request. CDP credentials are issued separately and should never be saved in the job record.
How Do You Create and Stop a Session Without Duplicating It?
Create and stop a session safely by persisting the intended request before creation, retaining the returned session ID, and treating shutdown as a confirmed state transition. This example deliberately separates commands so that an interrupted worker can resume its existing intent.
Step 1: Prepare the Node.js project
Use Node.js 22.12 or later and create a working directory. The lifecycle controller uses built-in Node APIs and does not install a browser client.
mkdir browser-lifecycle-demo
cd browser-lifecycle-demo
Create a private .env file containing NSTDATA_API_KEY and, only if required, NSTDATA_TEAM_ID. Exclude .env and the generated job record from version control. Run each job in its own directory or choose a distinct JOB_FILE path.
Step 2: Save the HTTP helper
Save this module as cloud-api.mjs. It validates the response envelope and avoids printing raw server messages that could contain sensitive data. Node's AbortSignal timeout bounds each request independently of the browser lifetime.
Credential prerequisite: these HTTP requests require a Nstdata business key. API behavior was checked against current documentation and synthetic state-transition tests; this article does not claim a live managed-account run.
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 3: Save the resumable controller
Save the following code as lifecycle.mjs. The controller creates the local record exclusively and refuses to overwrite an existing intent. Its retry loop reuses the stored body, including the same UUID generated with Node.js randomUUID.
Credential prerequisite: the API branch requires your workspace key. Recovery and repeated-create behavior were exercised with a clearly separated HTTP fixture, not presented as Nstdata service output.
import{ randomUUID }from'node:crypto';import{ readFile, writeFile }from'node:fs/promises';import{ setTimeout as delay }from'node:timers/promises';import{ api }from'./cloud-api.mjs';const file = process.env.JOB_FILE||'browser-job.json';constpathFor=id=>`/sessions/${encodeURIComponent(id)}`;constsave=job=>writeFile(file,JSON.stringify(job,null,2),{mode:0o600});asyncfunctionretry(operation){for(let attempt =0;; attempt++){try{returnawaitoperation();}catch(error){if(!error.retryable|| attempt ===2)throw error;awaitdelay(500*2** attempt +Math.random()*250);}}}asyncfunctionwait(id, expected){const deadline =Date.now()+90_000;while(Date.now()< deadline){const session =awaitretry(()=>api('GET',pathFor(id)));if(session.state=== expected)return session;if(['ended','failed'].includes(session.state)){thrownewError(`Session ${session.state}; expected ${expected}`);}awaitdelay(2_000);}thrownewError('State wait expired; inspect the original session');}const command = process.argv[2];if(command ==='create'){const options =awaitapi('GET','/sessions/options');const{ resourceClass, proxyCountry, ttlSeconds }= options.defaults;if(!options.resourceClasses.some(x=> x.value=== resourceClass)||!options.proxyCountries.some(x=> x.value=== proxyCountry)||!Number.isInteger(ttlSeconds)|| ttlSeconds < options.session.minSeconds|| ttlSeconds > options.session.maxSeconds)thrownewError('Inspect current options');const job ={body:{requestId:randomUUID(),name:'lifecycle-demo', resourceClass, proxyCountry, ttlSeconds,targetUrl:'https://example.com/',recording:false,captchaSolver:{enabled:false}}};awaitwriteFile(file,JSON.stringify(job,null,2),{flag:'wx',mode:0o600});console.log('Saved create intent. Run: node lifecycle.mjs resume');}elseif(['resume','inspect','stop'].includes(command)){const job =JSON.parse(awaitreadFile(file,'utf8'));if(!job.sessionId&& command ==='resume'){const created =awaitretry(()=>api('POST','/sessions', job.body));if(typeof created.sessionId!=='string'||!created.sessionId)thrownewError('Missing sessionId'); job.sessionId= created.sessionId; job.configurationWarningsPresent=Boolean(created.warnings?.length);awaitsave(job);}if(!job.sessionId)thrownewError('Resume the original create intent first');if(command ==='stop'){const current =awaitapi('GET',pathFor(job.sessionId));if(current.state!=='ended')awaitretry(()=>api('DELETE',pathFor(job.sessionId)));awaitwait(job.sessionId,'ended');}elseif(command ==='resume'){awaitwait(job.sessionId,'ready');}const current =awaitapi('GET',pathFor(job.sessionId));console.log(JSON.stringify({sessionId: job.sessionId,state: current.state,configurationWarningsPresent: job.configurationWarningsPresent}));}elsethrownewError('Use create, resume, inspect, or stop');
Step 4: Persist one creation intent
Run the create command. It fetches valid defaults and writes browser-job.json before any session creation request. The file is a local operational record, not a Cloud Browser API field.
node --env-file=.env lifecycle.mjs create
The command intentionally does not launch the browser. Inspect the recorded resource class, country, lifetime, and target URL before continuing. If configuration must change at this stage, start a deliberately new intent with a new job file and request ID; do not repurpose an ID already submitted to the service.
Step 5: Resume the stored intent
Run the resume command to submit the recorded request and wait for ready. If creation returns no usable result, investigate and resume the same record rather than deleting it and rerunning create.
node --env-file=.env lifecycle.mjs resume
Success prints the original sessionId and observed state. A configurationWarningsPresent value of true means you should inspect the creation configuration before attaching a task. The example's bounded retries are a demonstration policy, not a promise that every transient failure will recover.
Step 6: Inspect the original session
Use the inspection command when a worker or CDP client disconnects. The same session may still be running. If it is ready, a separate automation client can request new credentials and rediscover its page state.
node --env-file=.env lifecycle.mjs inspect
Do not restore actions from memory alone. Determine whether the previous step completed before repeating it, especially if it could submit a form or create a record. The production scraper error-handling guide explains why transport retries and business-operation retries need different policies.
Step 7: Stop and confirm termination
Run the stop command after your task or immediately after this lifecycle demonstration. It requests deletion when necessary, waits for ended, and prints the final observed state.
node --env-file=.env lifecycle.mjs stop
If shutdown cannot be confirmed, keep the job record and inspect the original session in Cloud Browser → Session History. A thrown error should not be converted into a successful cleanup metric.
[Screenshot: Session History showing the original session has ended, with access URLs and account details concealed.]
How Does Cloud Browser Help With Lifecycle Ownership?
Nstdata Cloud Browser gives a controller explicit session creation, inspection, attachment, and stop operations. The dashboard offers an operator a second way to inspect the resource when a worker fails. Short-lived automation credentials keep connection authorization separate from the business API key. Built-in proxy configuration belongs to the session rather than each client script. These capabilities help a team implement recovery, but they do not replace its job database or ownership rules.
Current configuration discovery: read supported option values instead of deploying hardcoded resource classes or lifetime limits.
Inspectable runtime: correlate a session ID with the active browser and history when a task is interrupted.
Controlled attachment: issue credentials for the intended ready session and reconnect without assuming a new session contains the old state.
Explicit termination: make confirmed shutdown part of the job's completion record.
Browser runtime, proxy traffic, and optional CAPTCHA activity should be evaluated separately using Cloud Browser pricing. Waiting for a human or debugging a stalled page can keep the browser active. A session duration limit bounds exposure, but proactive stop remains normal cleanup.
Production lifecycle failures usually arise from uncertain creation, competing owners, interrupted cleanup, or treating authentication state as browser state.
Symptom
Cause
Response
Creation times out
The response may have been lost after creation
Preserve the original body and request ID; reconcile that operation
HTTP 400
Invalid or outdated explicit configuration
Fetch options and correct the field; use a new intent when changing configuration
HTTP 401/403/470
Business authentication or workspace mismatch
Check the key and consistent team context
HTTP 409
Conflicting state or reused ID with changed parameters
Inspect the original operation and session
HTTP 429/503
Temporary capacity or rate pressure
Apply bounded backoff to the same operation
Stop remains unconfirmed
Shutdown is delayed or the controller lost contact
Reinspect the same session and escalate to an operator
The local JSON record is adequate for a single-worker demonstration. It is not a distributed lock, transactional database, or safe multi-worker scheduler. In production, store intent and session identity in a durable job record, give one controller the lease to mutate the browser, and run reconciliation for unfinished jobs after crashes.
Do not log API keys, automation tokens, full CDP URLs, or signed Live URLs. The OWASP logging guidance supports keeping secrets out of logs. Restrict job records and diagnostics to authorized operators; the browser automation tool guide is useful when comparing which responsibilities a framework or managed runtime actually owns.
What Should a Completed Browser Job Prove?
A completed browser job should prove that its intended output was accepted and its owned browser session ended. Store those results separately, along with the session ID and unresolved cleanup state when necessary. Reconnect only to a confirmed running resource, reconcile uncertain creation before creating again, and let an operator see unfinished work. That is the practical basis for remote browser session management.
No. ready means the browser can accept a connection. Your application must separately verify the page and task result.
Q: Can I reconnect after the session ends?
No. An ended session cannot be revived by requesting another CDP token. Create a new authorized task and restore only explicitly supported application state.
Q: Should a create retry generate a new request ID?
No. Retry the same uncertain creation with its original ID and identical body. Changed configuration or a deliberately new task requires a new ID.
Q: Is a website login the same as the browser session?
No. A website controls its authentication lifetime independently of the managed browser. Verify login state after reconnecting; do not infer it from ready.
Q: Does session duration replace cleanup?
No. Session duration is an automatic limit. Stop your owned session after the task and confirm ended to avoid unnecessary active runtime.
Q: Is the local job file enough for a distributed service?
No. A distributed service needs durable records, concurrency control, and a reconciliation process. The local file demonstrates preserved intent without claiming those production guarantees.
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.