Browser Automation
1. Introduction
Run browser-based workflows in managed cloud browsers and control them from the Nstdata dashboard or your existing automation code. Cloud Browser supports websites that need a real browser, JavaScript rendering, and user-like interaction, without operating browser infrastructure yourself.
How It Works
Create a session, choose its proxy and browser environment, and launch it in the cloud. Each session has a Session ID, browser configuration, proxy context, and usage record. Operate it with Live View or attach Playwright or Puppeteer through the Chrome DevTools Protocol (CDP).
Manual and automated work can share a session: sign in through Live View, then attach a script and select the signed-in page. The quick-start scripts below create a new session and page; they do not attach to an existing dashboard session.
When to Use Cloud Browser
- Interact with JavaScript-heavy websites that static HTTP requests cannot handle reliably.
- Automate sign-in, search, navigation, form entry, and data extraction.
- Check website access from a selected proxy region.
- Investigate a workflow with live HTML, Console, and Network diagnostics.
- Record interactions for replay and troubleshooting.
Core Capabilities
| Capability | What it provides |
|---|---|
| Managed remote browsers | No local browser process or browser installation is required by an attached script |
| Proxy country or custom proxy | Request an exit location, or supply a supported custom proxy URL through the HTTP API; a country does not guarantee a fixed IP |
| Browser environment | Operating system, language, timezone, resolution, and optional custom User-Agent; proxy location and browser region are separate |
| Automatic CAPTCHA | Optional handling of supported challenges; verify the target website’s result before continuing |
| Live diagnostics | Read-only HTML snapshots, recent Console output, and Network metadata for a selected running page |
| Recording and replay | Review interactions and available diagnostics after archiving; input masking is available and passwords remain masked |
| CDP automation | Attach Playwright or Puppeteer to the remote browser with short-lived connection credentials |
Important Notes
Availability, concurrency, runtime duration, and configuration depend on current workspace and service limits. Browser runtime, proxy traffic, and CAPTCHA usage are tracked separately. Keep API keys, CDP credentials, Live URLs, proxy credentials, and recordings private. Use the service in accordance with applicable laws, website terms, and your organization’s policies.
2. Quick Start
Use a business API key to create a session through the HTTP API, wait for ready, request short-lived CDP credentials, and connect your chosen client. After the task, stop the session through the API and confirm ended.
Prepare Your Project
Use Node.js 22.12 or later. Check the installed version:
node -v
npm -vUse your existing project directory if you have one. Install only the selected -core package and retain the lockfile to record dependency versions.
mkdir nstdata-browser-example
cd nstdata-browser-example
npm init -y
npm install playwright-coreConfigure Your API Key
Sign in to the Nstdata dashboard (opens in a new tab). Get a personal API key from Settings → Account (opens in a new tab), or a team member key from Members (opens in a new tab). Create .env beside package.json and the example scripts.
NSTDATA_API_KEY=REPLACE_WITH_YOUR_API_KEY
# Optional: select a joined team when using a personal key
# NSTDATA_TEAM_ID=REPLACE_WITH_YOUR_TEAM_IDA personal key can use optional NSTDATA_TEAM_ID to select a joined team; otherwise omit it. Team member keys use their bound team and cannot switch teams. Accounts migrated to team mode must use a team member key. All lifecycle HTTP requests use x-api-key without a Bearer prefix, not a login JWT. CDP uses separately issued short-lived credentials.
Add these entries to .gitignore:
node_modules/
.env
.env.*
!.env.exampleSave the Files and Run
Save the shared module and selected client from section 4 using the filenames shown. npm init -y only creates package.json; npm install does not create the example .mjs files. The layout is shown below; only the selected client is required:
nstdata-browser-example/
├── package.json
├── nstdata-session.mjs
├── connect-playwright.mjs
├── connect-puppeteer.mjs
├── .gitignore
└── .envRun the selected example from that directory:
node --env-file=.env connect-playwright.mjsA successful run prints requestId, sessionId, Title: Example Domain, page HTML, and finally Session ended:. Page verification and confirmed session shutdown are separate outcomes. The script incurs real browser and proxy usage; recording and Automatic CAPTCHA are disabled by default.
3. Lifecycle
A creation response, a ready browser, and a successful target-site task are separate outcomes.
| State | Meaning and action |
|---|---|
creating | Preparing the browser; wait for this session instead of creating another |
unknown | Current state is unconfirmed; inspect the original session, since a timeout is not proof of failure |
ready | CDP / Live View can connect; verify the target-site result separately |
stopping | Stop requested, but completion is not yet confirmed |
ended | Session ended and cannot resume; a new task needs a new session |
failed | Session failed; inspect the error and phase, and do not report normal shutdown |
Retry the same creation operation with an identical request body and the same UUID v4 requestId. Generate a new ID only for changed configuration or a deliberately new task. Do not rerun the full script while the original create result is unknown: that generates a new ID and may launch a duplicate session.
Disconnect and Stop a Session
Closing the dashboard, closing or refreshing Live View, and disconnecting a CDP client do not stop the cloud session. Reconnecting does not extend its duration. Use Stop Browser in the dashboard or DELETE /api/v1/cloud-browser/sessions/{sessionId}, then query the same session until ended.
Session Duration is an automatic safety limit, not normal cleanup. Stop proactively after the task; stopping only confirms a request to stop. finally handles ordinary completion and errors, but may not run after forced termination or power loss. Retain requestId and sessionId so you can inspect and stop the original session in Session History when necessary.
4. Code Examples
4.1 Make Your First Connection
Save the shared nstdata-session.mjs module and your selected client. HTTP calls have timeouts; transient errors are retried up to 3 total attempts. Create retries retain the same body and ID. The module retrieves current options, selects an available resource class, proxy country, and default duration, waits for readiness, obtains credentials, runs the task, and confirms shutdown.
NSTDATA_API_ORIGIN defaults to https://api.nstdata.io; override it only with a trusted HTTPS API origin if needed. The code does not print complete CDP credentials. Review the creation response’s warnings and effectiveConfiguration before customizing settings; do not write complete responses containing proxy credentials to shared logs.
Save this as nstdata-session.mjs:
import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
const apiKey = process.env.NSTDATA_API_KEY?.trim();
if (!apiKey) throw new Error('Missing NSTDATA_API_KEY');
const team = process.env.NSTDATA_TEAM_ID;
if (team !== undefined && (!team || team.trim() !== team)) {
throw new Error('Set a nonempty NSTDATA_TEAM_ID or omit it');
}
const origin = new URL(process.env.NSTDATA_API_ORIGIN || 'https://api.nstdata.io');
if (origin.protocol !== 'https:' || origin.username || origin.password ||
origin.pathname !== '/' || origin.search || origin.hash) {
throw new Error('NSTDATA_API_ORIGIN must be an HTTPS origin');
}
async function api(path, { method = 'GET', body } = {}) {
const headers = { 'x-api-key': apiKey };
if (team) headers['x-team-id'] = team;
if (body) headers['Content-Type'] = 'application/json';
let response;
try {
response = await fetch(new URL(`/api/v1/cloud-browser${path}`, origin), {
method, headers, body: body ? JSON.stringify(body) : undefined,
redirect: 'error', signal: AbortSignal.timeout(20_000),
});
} catch {
throw Object.assign(new Error(`${method} ${path}: network error or timeout`), { retryable: true });
}
const retryable = response.status === 429 || response.status >= 500;
let result;
try { result = await response.json(); } catch {
throw Object.assign(new Error(`${method} ${path}: invalid JSON (HTTP ${response.status})`), {
retryable: response.ok || retryable,
});
}
if (!response.ok || result?.err === true || result?.success === false) {
const code = [result?.code, result?.msg].find(value =>
typeof value === 'string' && /^CLOUD_BROWSER_[A-Z0-9_]+$/.test(value));
const field = typeof result?.field === 'string' && /^[A-Za-z0-9_.\[\]-]+$/.test(result.field)
? `; field: ${result.field}` : '';
throw Object.assign(new Error(`${method} ${path}: HTTP ${response.status}; ${code || 'API request failed'}${field}`), { retryable });
}
if (!result?.data) throw new Error(`${method} ${path}: missing response data`);
return result.data;
}
async function retry(operation) {
for (let attempt = 0; ; attempt++) {
try { return await operation(); } catch (error) {
if (!error.retryable || attempt >= 2) throw error;
await delay(1000 * 2 ** attempt);
}
}
}
async function waitForState(sessionId, expected, timeoutMs = 90_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
const session = await api(`/sessions/${encodeURIComponent(sessionId)}`);
if (session.state === expected) return session;
if (['ended', 'failed'].includes(session.state)) {
throw new Error(`Session ${sessionId}: ${session.state}; expected ${expected}`);
}
if (!['creating', 'unknown', 'ready', 'stopping'].includes(session.state)) {
throw new Error(`Session ${sessionId}: unrecognized state`);
}
} catch (error) {
if (!error.retryable) throw error;
}
await delay(2000);
}
throw new Error(`Session ${sessionId}: status wait timed out; inspect the same session`);
}
export async function withSession(task) {
const options = await retry(() => api('/sessions/options'));
const select = (items, preferred) => items?.find(item => item.value === preferred)?.value ?? items?.[0]?.value;
const resourceClass = select(options.resourceClasses, options.defaults?.resourceClass);
const proxyCountry = select(options.proxyCountries, options.defaults?.proxyCountry);
const ttlSeconds = options.defaults?.ttlSeconds;
if (!resourceClass || !proxyCountry || !Number.isInteger(ttlSeconds) ||
ttlSeconds < options.session?.minSeconds || ttlSeconds > options.session?.maxSeconds) {
throw new Error('No valid session defaults; inspect current session options');
}
const body = {
requestId: randomUUID(), name: 'developer-example',
resourceClass, proxyCountry, ttlSeconds, targetUrl: 'https://example.com/',
recording: false, captchaSolver: { enabled: false },
};
console.log('requestId:', body.requestId);
let sessionId;
let taskError;
try {
const created = await retry(() => api('/sessions', { method: 'POST', body }));
sessionId = created.sessionId;
if (typeof sessionId !== 'string' || !sessionId) throw new Error('Missing sessionId; inspect the original requestId');
console.log('sessionId:', sessionId);
if (created.warnings?.length) console.warn('Configuration warnings:', created.warnings);
console.log('Review effectiveConfiguration in the creation response before customizing this example.');
await waitForState(sessionId, 'ready');
const credential = await retry(() => api(`/sessions/${encodeURIComponent(sessionId)}/automation-credentials`, { method: 'POST' }));
const { cdpUrl, headerName, accessToken, expiresAt } = credential;
if (credential.sessionId !== sessionId || typeof headerName !== 'string' || !headerName ||
typeof accessToken !== 'string' || !accessToken || !(Date.parse(expiresAt) > Date.now())) {
throw new Error('Invalid or expired CDP credentials');
}
let url;
try { url = new URL(cdpUrl); } catch { throw new Error('Invalid CDP URL'); }
if (url.protocol !== 'wss:') throw new Error('Expected a secure CDP URL');
const headers = {
[headerName]: headerName.toLowerCase() === 'authorization' ? `Bearer ${accessToken}` : accessToken,
};
await task({ cdpUrl, headers, sessionId });
} catch (error) {
taskError = error;
throw error;
} finally {
if (typeof sessionId === 'string' && sessionId) {
try {
await retry(() => api(`/sessions/${encodeURIComponent(sessionId)}`, { method: 'DELETE' }));
await waitForState(sessionId, 'ended');
console.log('Session ended:', sessionId);
} catch (error) {
console.error('Stop not confirmed. Inspect sessionId:', sessionId);
if (!taskError) throw error;
}
} else {
console.error('No sessionId received. Inspect original requestId:', body.requestId);
}
}
}Save the selected script as connect-playwright.mjs or connect-puppeteer.mjs. Both open example.com, verify its title, and release the client connection before the shared module calls the Stop API.
import { chromium } from 'playwright-core';
import { withSession } from './nstdata-session.mjs';
await withSession(async ({ cdpUrl, headers }) => {
let browser;
try {
browser = await chromium.connectOverCDP(cdpUrl, { headers, timeout: 30_000 });
const context = browser.contexts()[0];
if (!context) throw new Error('No browser context available');
const page = await context.newPage();
await page.goto('https://example.com/', {
waitUntil: 'domcontentloaded', timeout: 30_000,
});
const title = await page.title();
console.log('Title:', title);
if (title !== 'Example Domain') throw new Error('Unexpected page result');
console.log('HTML:', await page.content());
} finally {
if (browser) await browser.close();
}
}).catch(error => {
const message = String(error.message)
.replace(/wss?:\/\/[^\s"'<>]+/gi, '[CDP URL]')
.replace(/Bearer\s+[^\s"'<>]+/gi, 'Bearer [REDACTED]');
console.error('Automation failed:', message);
process.exitCode = 1;
});4.2 Common Automation Snippets
These snippets assume the connected page from your chosen example. Insert one after page creation and before finally, replacing the default navigation and title checks. Do not concatenate snippets unchanged, as their variables repeat. They do not create or stop sessions; retain the outer connection and cleanup logic.
Set each snippet’s listed variables in .env and use authorized target URLs. Output paths are on the machine running Node.js; create their parent directories first. HTML, text, and screenshots can contain page data and should be stored according to your organization’s policies.
1. Retrieve Page HTML
Set TARGET_URL and HTML_OUTPUT_PATH. Navigate, save the DOM, and log the title and HTML byte length.
const targetUrl = process.env.TARGET_URL;
const outputPath = process.env.HTML_OUTPUT_PATH;
if (!targetUrl || !outputPath) {
throw new Error('Set TARGET_URL, HTML_OUTPUT_PATH');
}
const { writeFile } = await import('node:fs/promises');
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30_000 });
const html = await page.content();
await writeFile(outputPath, html, 'utf8');
console.log({ title: await page.title(), htmlBytes: Buffer.byteLength(html) });2. Extract Text and Links
Set TARGET_URL, TEXT_SELECTOR, and LINK_SELECTOR; the link selector must match <a> elements. Print visible text and structured links for the caller to store.
const targetUrl = process.env.TARGET_URL;
const textSelector = process.env.TEXT_SELECTOR;
const linkSelector = process.env.LINK_SELECTOR;
if (!targetUrl || !textSelector || !linkSelector) {
throw new Error('Set TARGET_URL, TEXT_SELECTOR, LINK_SELECTOR');
}
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30_000 });
await page.locator(textSelector).first().waitFor({ state: 'visible', timeout: 30_000 });
const text = await page.locator(textSelector).first().innerText();
const links = await page.locator(linkSelector).evaluateAll(elements =>
elements.map(element => ({ text: element.textContent?.trim() ?? '', url: element.href })),
);
console.log({ text, links });3. Capture Full-page and Element Screenshots
Set TARGET_URL, ELEMENT_SELECTOR, FULL_PAGE_SCREENSHOT_PATH, and ELEMENT_SCREENSHOT_PATH. Use .png output paths. For dynamic pages, wait for the required content before capturing it.
const targetUrl = process.env.TARGET_URL;
const elementSelector = process.env.ELEMENT_SELECTOR;
const fullPagePath = process.env.FULL_PAGE_SCREENSHOT_PATH;
const elementPath = process.env.ELEMENT_SCREENSHOT_PATH;
if (!targetUrl || !elementSelector || !fullPagePath || !elementPath) {
throw new Error('Set TARGET_URL, ELEMENT_SELECTOR, FULL_PAGE_SCREENSHOT_PATH, ELEMENT_SCREENSHOT_PATH');
}
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30_000 });
await page.screenshot({ path: fullPagePath, fullPage: true });
const element = page.locator(elementSelector).first();
await element.waitFor({ state: 'visible', timeout: 30_000 });
await element.screenshot({ path: elementPath });4. Wait for Dynamic Content
Set TARGET_URL, TRIGGER_SELECTOR, and RESULT_SELECTOR. Click the trigger, wait for a visible result, and print its text. Use selectors that uniquely identify the intended elements; wait for the website’s result instead of a fixed delay.
const targetUrl = process.env.TARGET_URL;
const triggerSelector = process.env.TRIGGER_SELECTOR;
const resultSelector = process.env.RESULT_SELECTOR;
if (!targetUrl || !triggerSelector || !resultSelector) {
throw new Error('Set TARGET_URL, TRIGGER_SELECTOR, RESULT_SELECTOR');
}
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30_000 });
await page.locator(triggerSelector).click({ timeout: 30_000 });
await page.locator(resultSelector).waitFor({ state: 'visible', timeout: 30_000 });
console.log(await page.locator(resultSelector).innerText());5. Block Selected Resource Types
Set TARGET_URL and comma-separated BLOCK_RESOURCE_TYPES, for example image,font,media. Review dependencies first: blocking images or scripts can affect website and CAPTCHA behavior.
Register interception before navigation and remove it in finally afterward. Use a fresh page without other interception handlers. Put further interactions inside the same try if interception must remain active longer.
const targetUrl = process.env.TARGET_URL;
const types = new Set((process.env.BLOCK_RESOURCE_TYPES ?? '').split(',').map(value => value.trim()).filter(Boolean));
if (!targetUrl || types.size === 0) throw new Error('Set TARGET_URL and BLOCK_RESOURCE_TYPES');
const handler = async route => {
if (types.has(route.request().resourceType())) await route.abort();
else await route.continue();
};
await page.route('**/*', handler);
try {
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30_000 });
} finally {
await page.unroute('**/*', handler);
}6. Block One Exact Request URL
Set TARGET_URL and BLOCK_URL. Block only exact equality with BLOCK_URL, not a prefix or wildcard match.
Register interception before navigation and remove it in finally afterward. Use a fresh page without other interception handlers. Put further interactions inside the same try if interception must remain active longer.
const targetUrl = process.env.TARGET_URL;
const blockedUrl = process.env.BLOCK_URL;
if (!targetUrl || !blockedUrl) {
throw new Error('Set TARGET_URL, BLOCK_URL');
}
const handler = async route => {
if (route.request().url() === blockedUrl) await route.abort();
else await route.continue();
};
await page.route('**/*', handler);
try {
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 30_000 });
} finally {
await page.unroute('**/*', handler);
}4.3 Use Case Examples
- Automate form filling and submission: Turn repetitive data entry into repeatable workflows with live dashboard visibility. Watch the demo (opens in a new tab).
- Automate QA: Validate web workflows from login to checkout, with live dashboard viewing and a local QA report containing results and screenshots. Watch the demo (opens in a new tab).
5. Configuration Options
Before creation, call GET /api/v1/cloud-browser/sessions/options. Display each option’s label and submit its value; review warnings and effectiveConfiguration in the creation response. Configure settings before launch; they cannot be changed while the session runs. See Cloud Browser Schemas (opens in a new tab) for field types, units, defaults, and valid ranges.
| Setting | Behavior |
|---|---|
| Proxy Country | Select an exit from proxyCountries; the default lets the service allocate one. It does not guarantee a fixed IP. proxyCountry and proxyUrl are mutually exclusive |
| Custom Proxy | HTTP integrations can supply an http://, https://, or socks5:// proxy URL without a query or fragment; protect any embedded credentials |
| Resource Class | Choose from resourceClasses; runtime resources are separate from proxy country and resolution |
| Session Duration | ttlSeconds is browser lifetime in seconds, not a page-load or script timeout; follow session bounds and defaults.ttlSeconds |
| Automatic CAPTCHA | captchaSolver.enabled is off by default. No extension installation or third-party solver key is required; still verify the website’s result |
| Session Recording | Enable recording before launch to review interactions and available Console / Network diagnostics after archiving |
| Operating System | Choose an available platform, such as Windows, macOS, or Linux, to set platform information visible to websites |
| Language & Timezone | Follow IP at startup or customize language and timezone separately; proxy region is separate from custom browser region |
| Resolution Fingerprint | Use whole pixels within current limits, such as 1280 × 720, 1440 × 900, 1920 × 1080, or custom dimensions; controls screen and initial window, not page viewport or Live View zoom |
| Custom User-Agent | Optional custom string; does not change the browser engine or guarantee consistency with other fingerprint values |
Invalid, disabled, or out-of-range explicit values return 400. Omitted fields use service defaults; do not hardcode workspace limits. Use a new requestId after changing configuration. See the Cloud Browser guide for more details.
6. Live View & Recording
Live Preview
Browser Preview is the interactive view of the running browser; keyboard and mouse actions inside it operate that remote browser. Live URL opens the same browser in another tab, Refresh Preview reconnects to the same session, and Enter Fullscreen enlarges it. Stop Browser ends the session; wait for confirmation.
Open DevTools in the preview’s upper-right tools area, using Expand Tools if collapsed. Wait for Connected, then select the Page:
- Elements: Read-only HTML snapshot.
- Console: Newly received messages and exceptions.
- Network: Method, status or failure reason, URL, MIME type, and available sanitized headers.
Selecting a DevTools page does not select the page in your script. Live URLs contain short-lived access credentials; keep them private. If a URL expires or disconnects, check the original session is still running, then reopen it from the dashboard.
Record and Replay a Session
- Enable Session Recording before launch. Keep Hide Input Content on to mask ordinary form inputs; passwords remain masked even when it is off. This setting does not hide other page text or data printed by the website.
- Run the task, stop the session, and wait for archiving. Recording duration follows current workspace limits; the browser can keep running and incur usage after recording stops.
- Open Cloud Browser → Session History and click the session name. Page Observations and Session Replay load automatically when data is available.
- If there are multiple recorded documents, select Replay Page, click Play, drag the timeline, or change speed. Each document has its own timeline; there is no synchronized timeline across tabs.
- Replay DevTools shows saved data for the selected page and playback position. It does not connect to or operate a running browser.
Replay reconstructs recorded page changes rather than playing an MP4. Page scripts and external resources are not loaded, so images, fonts, and canvas may differ. ready means archived and readable; partial means archived but incomplete. Neither guarantees a usable snapshot for every page. Unrecorded, missing, expired, or deleted data cannot be replayed. Retention is separate from session and recording duration. See the full guide.
7. Troubleshooting
| Problem | What to do |
|---|---|
| 401, 403, or 470 | Check the business API key, workspace, and permissions. Send x-api-key without Bearer. Keep team context consistent on all requests; omit x-team-id for a personal workspace. Do not switch to a login JWT |
400 / CLOUD_BROWSER_INVALID_PARAMETER | Inspect field, retrieve current options, and correct the configuration. Do not retry the same invalid request; use a new requestId after changing it |
| 409 | Query the original session with GET /api/v1/cloud-browser/sessions/{sessionId} and inspect creating, ready, or stopping. For idempotency conflicts, check whether parameters changed under the same ID |
| 410 | The original session or accessed resource expired; inspect the original session state instead of treating old credentials as current |
| 429, 503, or network error | Use bounded backoff for the same operation. Create retries retain the same ID and body; do not restart the full workflow while its outcome is unknown |
Missing .mjs file or package | Save the shared module and selected client in the project directory; install the matching playwright-core or puppeteer-core dependency there |
Missing NSTDATA_API_KEY | Check .env name, location, variable spelling, and --env-file=.env. Existing process environment variables can override file values |
| CDP authentication failure | Confirm the same session is ready, get fresh credentials, and construct headers from returned headerName and accessToken; do not use the business key directly for CDP |
| Stop unconfirmed or cleanup interrupted | Query and stop the original sessionId, then wait for ended. A CDP disconnect does not stop the browser. Without a sessionId, retain the original requestId and inspect that create operation in the dashboard |
For support, provide Session ID, requestId, time, attempted action, and sanitized errors. Do not send API keys, CDP credentials, or private recordings. See the Cloud Browser developer documentation (opens in a new tab) for API details.