Build browser automation with Browser API
Build a complete remote-browser workflow from session options through connection and cleanup.
Build browser automation with Browser API
This guide covers a complete Browser API workflow: choose live options, create
a session, wait until it is connectable, automate Chromium or Firefox, retain
state with a profile when supported, inspect usage, and terminate cleanly.
Before you begin
You need a Raspbytes API key with:
browser:readto read options, sessions, and profiles;browser:writeto create, update, and terminate resources.
Store the key in a server-side secret:
export RASPBYTES_API_KEY='rb_live_your_key_here'Never place the key or a browser connection URL in frontend JavaScript.
1. Read live options
Do not hard-code browser versions, environment profiles, or proxy countries.
Read the available values before creating sessions:
curl --fail-with-body --silent --show-error \
'https://api.raspbytes.com/api/v1/browser/session-options/' \
-H "X-API-Key: $RASPBYTES_API_KEY"
curl --fail-with-body --silent --show-error \
'https://api.raspbytes.com/api/v1/browser/proxy-options/' \
-H "X-API-Key: $RASPBYTES_API_KEY"Session options report the browsers, versions, and environments currently
accepted for session creation. Proxy options report available proxy products
and countries. Review profile availability, traffic, concurrency, and timeout
allowances in the Raspbytes dashboard.
2. Create a session
Create an ephemeral Chromium session with a managed desktop environment and a
sticky residential route:
curl --fail-with-body --silent --show-error \
-X POST 'https://api.raspbytes.com/api/v1/browser/sessions/' \
-H "X-API-Key: $RASPBYTES_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"browser": "chromium",
"browser_version": "stable",
"environment_profile": "desktop-balanced",
"proxy": {
"type": "residential",
"country": "GB",
"sticky": true
},
"session_timeout_seconds": 900
}'Omit proxy.country to let Raspbytes choose an available country for the proxy
product. The resolved proxy and managed environment are returned on the
session. Do not send raw fingerprint overrides; select a managed environment
profile instead.
3. Wait until the session is connectable
Creation can return before the browser is ready. Poll the session detail with a
bounded delay. Continue when connection.url is present, and stop on a terminal
status.
const apiKey = process.env.RASPBYTES_API_KEY;
const baseUrl = "https://api.raspbytes.com/api/v1/browser";
if (!apiKey) throw new Error("RASPBYTES_API_KEY is required");
const terminal = new Set(["terminated", "expired", "failed", "node_lost"]);
async function waitForConnection(sessionId, timeoutMs = 60_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const response = await fetch(`${baseUrl}/sessions/${sessionId}/`, {
headers: { "X-API-Key": apiKey },
});
if (!response.ok) {
throw new Error(`Session lookup failed with HTTP ${response.status}`);
}
const session = await response.json();
if (terminal.has(session.status)) {
throw new Error(
`Browser ended with ${session.status}: ${session.termination_reason}`,
);
}
if (session.connection?.url) return session;
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
throw new Error("Browser did not become connectable before the client timeout");
}The client timeout controls how long your application waits. It does not extend
the remote session timeout.
4. Connect to Chromium with Playwright
When protocol is cdp, use a CDP-compatible client:
import { chromium } from "playwright";
async function automateChromium(session) {
if (session.protocol !== "cdp") {
throw new Error(`Expected CDP, received ${session.protocol}`);
}
const browser = await chromium.connectOverCDP(session.connection.url);
try {
const context = browser.contexts()[0];
if (!context) throw new Error("Browser context unavailable");
const page = await context.newPage();
await page.goto("https://example.com", {
waitUntil: "domcontentloaded",
timeout: 30_000,
});
return {
title: await page.title(),
url: page.url(),
};
} finally {
await browser.close();
}
}Use the context already supplied by the remote browser. Creating an unrelated
local context can bypass the configured environment and profile behaviour.
5. Connect to Firefox with WebDriver BiDi
Firefox sessions return bidi. Use a WebDriver BiDi-compatible client such as
Puppeteer:
import { connect } from "puppeteer-core";
async function automateFirefox(session) {
if (session.protocol !== "bidi") {
throw new Error(`Expected BiDi, received ${session.protocol}`);
}
const browser = await connect({
browserWSEndpoint: session.connection.url,
protocol: "webDriverBiDi",
});
try {
const page = await browser.newPage();
await page.goto("https://example.com", {
waitUntil: "domcontentloaded",
timeout: 30_000,
});
return { title: await page.title(), url: page.url() };
} finally {
browser.disconnect();
}
}Choose the client from the returned protocol rather than assuming it from the
requested browser.
6. Use persistent profiles when enabled
Profiles retain supported browser state for compatible sessions. Confirm that
the dashboard shows profile support for the account, then create a profile:
curl --fail-with-body --silent --show-error \
-X POST 'https://api.raspbytes.com/api/v1/browser/profiles/' \
-H "X-API-Key: $RASPBYTES_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"name": "catalog-session",
"browser": "chromium",
"browser_version": "stable"
}'Pass the returned profile ID as profile_id when creating later sessions. Keep
the browser family and version compatible with the profile. Read profile detail
to inspect its current snapshot, and delete profiles no longer required.
Profiles are not a substitute for an application secret manager. Do not depend
on browser storage as the only copy of a credential or business record.
7. Terminate and inspect session usage
A client disconnect does not guarantee that the remote session has ended.
Always issue an explicit termination request from a finally block:
async function terminateSession(sessionId) {
const response = await fetch(`${baseUrl}/sessions/${sessionId}/`, {
method: "DELETE",
headers: { "X-API-Key": apiKey },
});
if (!response.ok && response.status !== 404) {
throw new Error(`Session termination failed with HTTP ${response.status}`);
}
}The session response contains duration, proxy bytes, and gateway bytes recorded
for that session. Use the Raspbytes dashboard for aggregate account usage and
allowance information.
8. Handle failures safely
400: refresh options and validate browser, version, environment, proxy,
country, or timeout.401: verify the API key is present and valid.402: review product access and remaining allowance in the dashboard.403: grant the required Browser API permission.404: verify the session belongs to the authenticated account.429: wait for concurrency capacity before creating another session.503: retry with exponential backoff only when the response marks the error
as retryable.
Never retry session creation in an unbounded loop. Track the created session ID
as soon as it is returned so cleanup remains possible after later steps fail.
Complete Chromium workflow
import { chromium } from "playwright";
const apiKey = process.env.RASPBYTES_API_KEY;
const baseUrl = "https://api.raspbytes.com/api/v1/browser";
if (!apiKey) throw new Error("RASPBYTES_API_KEY is required");
async function api(path, init = {}) {
const response = await fetch(baseUrl + path, {
...init,
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
...init.headers,
},
});
if (!response.ok) {
throw new Error(`${init.method ?? "GET"} ${path}: HTTP ${response.status}`);
}
return response.json();
}
async function waitForConnection(sessionId, timeoutMs = 60_000) {
const terminal = new Set(["terminated", "expired", "failed", "node_lost"]);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const session = await api(`/sessions/${sessionId}/`);
if (terminal.has(session.status)) {
throw new Error(`Browser ended with status ${session.status}`);
}
if (session.connection?.url) return session;
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
throw new Error("Browser did not become connectable before the client timeout");
}
const session = await api("/sessions/", {
method: "POST",
body: JSON.stringify({
browser: "chromium",
browser_version: "stable",
environment_profile: "desktop-balanced",
proxy: { type: "datacenter", country: "GB", sticky: false },
session_timeout_seconds: 900,
}),
});
try {
const ready = await waitForConnection(session.id);
const browser = await chromium.connectOverCDP(ready.connection.url);
try {
const context = browser.contexts()[0];
if (!context) throw new Error("Browser context unavailable");
const page = await context.newPage();
await page.goto("https://example.com", {
waitUntil: "domcontentloaded",
timeout: 30_000,
});
console.log(await page.title());
} finally {
await browser.close();
}
} finally {
await fetch(`${baseUrl}/sessions/${session.id}/`, {
method: "DELETE",
headers: { "X-API-Key": apiKey },
});
}Keep session creation, connection, work, and cleanup in one owned lifecycle.
That makes concurrency, traffic usage, and failure recovery predictable.
Updated 16 days ago

