Skip to main content

Node.js API Reference

Complete API reference for the Browser7 Node.js SDK.

Browser7 Class

The main class for interacting with the Browser7 API.

Constructor

new Browser7(options)

Creates a new Browser7 client instance.

Parameters:

  • options (object, required) - Configuration options
    • apiKey (string, required) - Your Browser7 API key from the Dashboard
    • baseUrl (string, optional) - Full API base URL including version path (e.g., 'https://api.browser7.com/v1'). Defaults to 'https://api.browser7.com/v1'

Returns: Browser7 instance

Example:

// Production (default)
const client = new Browser7({ apiKey: 'b7_your_api_key_here' });

// Custom endpoint (e.g., Canadian datacenter)
const client = new Browser7({
apiKey: 'b7_your_api_key_here',
baseUrl: 'https://ca-api.browser7.com/v1'
});

Throws:

  • Browser7Error - If apiKey is not provided

Instance Methods

client.render(url, options, onProgress)

Render a URL and automatically poll for the result. This is the recommended method for most use cases.

Parameters:

  • url (string, required) - The URL to render
  • options (RenderOptions, optional) - Render configuration
  • onProgress (function, optional) - Progress callback function

Returns: Promise<RenderResult>

RenderOptions:

OptionTypeDescriptionDefault
countryCodestringCountry code (e.g., 'US', 'GB', 'DE')Auto-select
citystringCity name (e.g., 'new.york', 'london')Auto-select
waitForWaitAction[]Array of wait actions (max 10)[]
captchastringCAPTCHA mode: 'disabled', 'auto', 'recaptcha_v2', 'recaptcha_v3', 'turnstile''disabled'
blockImagesbooleanBlock images for faster renderingtrue
fetchUrlsstring[]Additional URLs to fetch after render (max 10)[]
includeScreenshotbooleanEnable screenshot capturefalse
screenshotFormatstringScreenshot format: 'jpeg' or 'png''jpeg'
screenshotQualitynumberJPEG quality (1-100, only for JPEG)80
screenshotFullPagebooleanCapture full page or viewport onlyfalse
debugbooleanEnable debug mode: syncs HTML, fetch responses, and screenshots to dashboard for 7 daysfalse

Example:

const result = await client.render(
'https://example.com',
{
countryCode: 'US',
city: 'new.york',
blockImages: true,
waitFor: [
Browser7.waitForClick('.cookie-accept'),
Browser7.waitForSelector('.main-content', 'visible')
]
},
(progress) => {
console.log(`[${progress.type}] ${progress.status || ''}`);
}
);

Progress Callback:

The onProgress callback receives a ProgressEvent object:

{
type: 'started' | 'polling' | 'completed' | 'failed',
renderId: string,
timestamp: string, // ISO timestamp
status?: string, // Current render status (for 'polling' events)
attempt?: number, // Current polling attempt (for 'polling' events)
retryAfter?: number // Server-suggested retry interval in seconds
}

Throws:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • ValidationError - Invalid parameters (400)
  • RateLimitError - Too many concurrent requests (429)
  • InsufficientBalanceError - Insufficient account balance (402)
  • RenderError - Render failed or timed out
  • Browser7Error - Network errors or other failures

client.createRender(url, options)

Create a render job without polling. Use this for low-level control when you want to poll manually.

Parameters:

  • url (string, required) - The URL to render
  • options (RenderOptions, optional) - Same as render() options

Returns: Promise<RenderResponse>

RenderResponse:

{
renderId: string // Use this with getRender()
}

Example:

const { renderId } = await client.createRender('https://example.com', {
countryCode: 'US'
});

console.log('Render job created:', renderId);
// Poll manually with getRender(renderId)

Throws:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • ValidationError - Invalid parameters (400)
  • RateLimitError - Too many concurrent requests (429)
  • InsufficientBalanceError - Insufficient account balance (402)
  • Browser7Error - Network errors or other failures

client.getRender(renderId)

Get the status and result of a render job. Use this to manually poll for results.

Parameters:

  • renderId (string, required) - The render ID from createRender()

Returns: Promise<RenderResult>

Example:

// Create render
const { renderId } = await client.createRender('https://example.com');

// Poll manually
let result;
while (true) {
result = await client.getRender(renderId);

if (result.status === 'completed') {
break;
} else if (result.status === 'failed') {
throw new Error(`Render failed: ${result.error}`);
}

// Wait before next poll (use server-suggested interval)
await new Promise(resolve =>
setTimeout(resolve, (result.retryAfter || 1) * 1000)
);
}

console.log(result.html);

Throws:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • RenderError - Render failed or timed out
  • Browser7Error - Network errors or other failures

client.getAccountBalance()

Get the current account balance.

Parameters: None

Returns: Promise<AccountBalance>

AccountBalance:

{
totalBalanceCents: number, // Total balance in cents (1 cent = 1 render)
totalBalanceFormatted: string, // Formatted as USD (e.g., "$13.00")
breakdown: {
paid: {
cents: number, // Paid balance in cents
formatted: string // Formatted as USD
},
free: {
cents: number, // Free balance in cents
formatted: string // Formatted as USD
},
bonus: {
cents: number, // Bonus balance in cents
formatted: string // Formatted as USD
}
}
}

Example:

const balance = await client.getAccountBalance();

console.log(`Total: ${balance.totalBalanceFormatted}`);
console.log(`Renders remaining: ${balance.totalBalanceCents}`);
console.log(`\nBreakdown:`);
console.log(` Paid: ${balance.breakdown.paid.formatted}`);
console.log(` Free: ${balance.breakdown.free.formatted}`);
console.log(` Bonus: ${balance.breakdown.bonus.formatted}`);

Note: Since 1 cent = 1 render, totalBalanceCents directly shows how many renders you can perform.

Throws:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • Browser7Error - Network errors or other failures

client.getRegions()

Get available API regions. Useful for validating region codes or building region-selection UIs.

This is a public endpoint - no API key is required to call it, but the SDK makes the call for you with a consistent interface.

Parameters: None

Returns: Promise<RegionsResponse>

Example:

const { regions } = await client.getRegions();

// List all active regions
regions
.filter(r => r.status === 'active')
.forEach(r => console.log(`${r.code}: ${r.name}`));

Throws:

  • Browser7Error - Network errors or other failures

Static Helper Methods

These static methods help you create wait action objects.

Browser7.waitForDelay(duration)

Create a delay wait action.

Parameters:

  • duration (number, required) - Duration in milliseconds (100-60000)

Returns: WaitAction object

Example:

const action = Browser7.waitForDelay(3000);
// { type: 'delay', duration: 3000 }

Browser7.waitForSelector(selector, state, timeout)

Create a selector wait action to wait for a DOM element.

Parameters:

  • selector (string, required) - CSS selector
  • state (string, optional) - Element state: 'visible', 'hidden', or 'attached'. Default: 'visible'
  • timeout (number, optional) - Timeout in milliseconds (1000-60000). Default: 30000

Returns: WaitAction object

Example:

const action = Browser7.waitForSelector('.main-content', 'visible', 10000);
// {
// type: 'selector',
// selector: '.main-content',
// state: 'visible',
// timeout: 10000
// }

Browser7.waitForText(text, selector, timeout)

Create a text wait action to wait for specific text content.

Parameters:

  • text (string, required) - Text to wait for
  • selector (string, optional) - CSS selector to limit search scope
  • timeout (number, optional) - Timeout in milliseconds (1000-60000). Default: 30000

Returns: WaitAction object

Example:

const action = Browser7.waitForText('In Stock', '.availability', 10000);
// {
// type: 'text',
// text: 'In Stock',
// selector: '.availability',
// timeout: 10000
// }

Browser7.waitForClick(selector, timeout)

Create a click wait action to click an element.

Parameters:

  • selector (string, required) - CSS selector of element to click
  • timeout (number, optional) - Timeout in milliseconds (1000-60000). Default: 30000

Returns: WaitAction object

Example:

const action = Browser7.waitForClick('.cookie-accept', 5000);
// {
// type: 'click',
// selector: '.cookie-accept',
// timeout: 5000
// }

Type Definitions

RenderResult

The complete result returned by a successful render.

{
status: string, // 'completed', 'processing', 'failed'
html?: string, // Rendered HTML (decompressed, only when completed)
screenshot?: string, // Base64-encoded image (if includeScreenshot was true)
fetchResponses?: Array<object>, // Array of fetch responses (decompressed, if fetchUrls provided)
loadStrategy: string, // 'default' or 'custom'
selectedCity: SelectedCity, // City used for rendering
bandwidthMetrics: BandwidthMetrics, // Network bandwidth statistics
captcha: CaptchaInfo, // CAPTCHA detection and handling info
timingBreakdown: object, // Performance timing breakdown (ms)
retryAfter: number, // Server-suggested retry interval in seconds
error?: string // Error message if status is 'failed'
}

SelectedCity

Information about the city used for rendering.

{
name: string, // City identifier (e.g., 'new.york')
displayName: string, // Human-readable name (e.g., 'New York')
latitude: number, // City latitude
longitude: number, // City longitude
timezoneId: string // Timezone (e.g., 'America/New_York')
}

BandwidthMetrics

Network bandwidth statistics for the render.

{
networkBytes: number, // Bytes downloaded from network
cachedBytes: number, // Bytes served from cache
cacheHitRate: string // Cache hit rate percentage (e.g., '16.3%')
}

CaptchaInfo

CAPTCHA detection and solving information.

{
detected: boolean, // Whether CAPTCHA was detected
handled: boolean, // Whether CAPTCHA was solved
sitekey?: string // CAPTCHA sitekey if detected
}

RegionsResponse

Returned by getRegions().

{
regions: Region[] // Available API regions
}

Region

An individual region entry within RegionsResponse.regions.

{
code: string, // Region code (e.g., 'eu', 'ca', 'sg')
name: string, // Human-readable name (e.g., 'Europe')
status: 'active' | 'maintenance' | 'inactive'
}

WaitAction

User-configurable wait action for dynamic content.

Base structure:

{
type: 'delay' | 'selector' | 'text' | 'click'
}

Delay action:

{
type: 'delay',
duration: number // Milliseconds (100-60000)
}

Selector action:

{
type: 'selector',
selector: string, // CSS selector
state?: string, // 'visible' | 'hidden' | 'attached' (default: 'visible')
timeout?: number // Milliseconds (1000-60000, default: 30000)
}

Text action:

{
type: 'text',
text: string, // Text to wait for
selector?: string, // Optional CSS selector to limit scope
timeout?: number // Milliseconds (1000-60000, default: 30000)
}

Click action:

{
type: 'click',
selector: string, // CSS selector of element to click
timeout?: number // Milliseconds (1000-60000, default: 30000)
}

Supported Countries

The following country codes are supported for geo-targeting:

AT, BE, CA, CH, CZ, DE, FR, GB, HR, HU, IT, NL, PL, SK, US

See the Geo-Targeting Guide for available cities within each country.


Error Classes

The SDK provides typed error classes for programmatic error handling. All error classes extend Error.

Import

// ESM
import Browser7, {
Browser7Error,
AuthenticationError,
ValidationError,
RateLimitError,
InsufficientBalanceError,
RenderError,
} from 'browser7';

// CommonJS
const Browser7 = require('browser7');
const { AuthenticationError, ValidationError } = require('browser7');
// Or via static properties:
// Browser7.AuthenticationError, Browser7.ValidationError, etc.

Hierarchy

ClassHTTP StatusProperties
Browser7ErrorNetwork errors, 404, 500+message, statusCode, body
AuthenticationError401, 403(inherits base)
ValidationError400details
RateLimitError429concurrentLimit
InsufficientBalanceError402(inherits base)
RenderError422, render failureserrorCode, renderId, billable

Usage

try {
const result = await client.render('https://example.com');
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Check your API key');
} else if (error instanceof ValidationError) {
console.error('Invalid parameters:', error.details);
} else if (error instanceof RateLimitError) {
console.error(`Rate limited (max: ${error.concurrentLimit})`);
} else if (error instanceof InsufficientBalanceError) {
console.error('Top up your account');
} else if (error instanceof RenderError) {
console.error(`Render failed: ${error.errorCode}, billable: ${error.billable}`);
}
}

All error classes extend Browser7Error, which extends Error. You can catch all SDK errors with catch (error) { if (error instanceof Browser7Error) { ... } }.


Next Steps