Chat with us, powered by LiveChat
← Return to MyDisct Solver

Node.js SDK Overview

The mydisctsolver-bbre Node.js SDK is the official client library for interacting with the BBRE (Browser-Backed Request Engine) API from Node.js applications. Instead of manually constructing HTTP requests, managing authentication headers, polling for results, and parsing response payloads, the SDK wraps every BBRE API endpoint into clean, promise-based methods that you can call directly from your code. The SDK is built around three core classes that map to the three layers of the BBRE system. BBREClient is the base class that handles direct API communication, including stateless requests, account management, and session lifecycle operations. BBRESession extends BBREClient and adds session-based workflow management with automatic session creation, cookie persistence, profile tracking, and browser speed configuration. BrowserAPI provides a fluent interface for browser automation actions like navigating pages, clicking elements, filling forms, taking screenshots, and executing JavaScript within adaptive mode sessions. Together, these three classes give you complete programmatic control over the BBRE engine without writing a single raw HTTP call. This page covers installation, basic usage patterns for each class, import options, configuration parameters, error handling strategies, and a comparison between using the SDK and calling the API directly. Whether you are building a web scraper, automating form submissions, or integrating BBRE into a larger data pipeline, this overview will get you productive with the SDK quickly and point you to the detailed per-method documentation for deeper reference.

About the BBRE Node.js SDK

The mydisctsolver-bbre package is published on npm and works with Node.js 14 and above. It uses axios internally for HTTP communication and exposes a fully promise-based API. Every method returns a Promise, so you can use async/await or .then() chains depending on your preference. The SDK automatically handles API key injection, request formatting, response parsing, and error normalization. If you have been using the BBRE API through raw HTTP calls, switching to the SDK will significantly reduce your code complexity and eliminate common integration mistakes like forgetting authentication headers or misformatting request bodies.

Installation

Install the SDK from npm using your preferred package manager. The package name is mydisctsolver-bbre and it includes all three classes (BBREClient, BBRESession, and BrowserAPI) in a single package. There are no native dependencies or build steps required. The installation is straightforward and works on any platform that supports Node.js.

Bash
npm install mydisctsolver-bbre

If you use Yarn as your package manager:

Bash
yarn add mydisctsolver-bbre

After installation, verify that the package is available by requiring it in a Node.js script or REPL session. If the require statement executes without errors, the SDK is installed correctly and ready to use.

JavaScript
const BBREClient = require("mydisctsolver-bbre");
console.log("SDK loaded successfully");

Quick Start

The fastest way to get started with the SDK is to create a BBREClient instance with your API key and make a simple request. The following example demonstrates the minimal code needed to send a request through the BBRE engine and receive the response. This single example covers client initialization, request execution, and result handling, which are the three fundamental operations you will use in every BBRE integration.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY"
});

async function quickStart() {
  const result = await client.request({
    url: "https://httpbin.org/get",
    method: "GET"
  });

  console.log("Status:", result.statusCode);
  console.log("Body:", result.body);
}

quickStart();

That is all it takes. The SDK handles authentication, sends the request to the BBRE API, waits for the result (polling automatically if the request is processed asynchronously), and returns the parsed response. You do not need to manage headers, poll for task completion, or parse nested response structures. The result object contains the HTTP status code, response headers, and body from the target website, exactly as if you had made the request directly from a real browser.

Class Overview

The SDK is organized around three classes, each serving a distinct purpose in the BBRE ecosystem. Understanding when to use each class is the key to writing efficient and maintainable BBRE integrations. The classes form an inheritance hierarchy where BBRESession extends BBREClient, inheriting all of its methods while adding session-specific functionality. BrowserAPI is a separate class that is accessed through the browser property of a BBRESession instance.

Class Purpose When to Use
BBREClient Base client for direct API interaction. Provides methods for stateless requests, account management, and manual session lifecycle control. Use when you need simple, one-off requests without session state, when you want to manage session creation and closure manually, or when you need account information like balance and usage history.
BBRESession Session-based client that extends BBREClient. Automatically manages a persistent browser session with cookie persistence, profile tracking, and browser speed configuration. Use when your workflow requires multiple requests that share state (cookies, login sessions, CSRF tokens), when you need to interact with websites that track user sessions, or when you want the SDK to handle session lifecycle automatically.
BrowserAPI Browser automation interface accessed through session.browser. Provides methods for page navigation, element interaction, content extraction, waiting, scrolling, and JavaScript execution. Use when you need to automate browser actions like clicking buttons, filling forms, taking screenshots, or executing JavaScript on a page. Requires an adaptive mode session.

Class Hierarchy

The relationship between the three classes is straightforward. BBREClient is the foundation that handles all API communication. BBRESession inherits from BBREClient, which means every method available on BBREClient is also available on BBRESession. The BrowserAPI instance is created internally by BBRESession and exposed through the browser property. You never instantiate BrowserAPI directly.

JavaScript
const { BBREClient, BBRESession } = require("mydisctsolver-bbre");

const client = new BBREClient({ apiKey: "YOUR_API_KEY" });

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive"
});

const browser = session.browser;

BBREClient Quick Example

BBREClient is the right choice when you need to make independent requests that do not share state with each other. Each request through BBREClient starts with a clean browser context, which means no cookies carry over between requests and no session state is maintained. This is ideal for scraping public pages, checking website availability, fetching API responses through the BBRE engine, or any scenario where you do not need to log in or maintain a browsing session. The following example demonstrates a typical BBREClient workflow: creating the client, making a POST request with custom headers and a JSON body, and processing the response.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "medium"
});

async function fetchProductData() {
  const result = await client.post("https://api.example.com/products", {
    body: {
      category: "electronics",
      limit: 50
    },
    headers: {
      "Accept": "application/json"
    }
  });

  console.log("Status:", result.statusCode);

  const products = JSON.parse(result.body);
  console.log("Products found:", products.length);

  return products;
}

fetchProductData();

The BBREClient also provides convenience methods for common HTTP verbs. Instead of specifying the method in the options object, you can call client.get(), client.post(), client.put(), client.delete(), client.patch(), client.head(), or client.options() directly. These methods accept the URL as the first argument and an options object as the second argument, making your code more readable and concise.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "low"
});

async function httpMethodExamples() {
  const getResult = await client.get("https://httpbin.org/get");
  console.log("GET status:", getResult.statusCode);

  const postResult = await client.post("https://httpbin.org/post", {
    body: { key: "value" }
  });
  console.log("POST status:", postResult.statusCode);

  const putResult = await client.put("https://httpbin.org/put", {
    body: { updated: true }
  });
  console.log("PUT status:", putResult.statusCode);

  const deleteResult = await client.delete("https://httpbin.org/delete");
  console.log("DELETE status:", deleteResult.statusCode);
}

httpMethodExamples();

Account Operations with BBREClient

Beyond making requests, BBREClient provides methods for managing your BBRE account. You can check your balance, retrieve account information, and manage sessions programmatically. These methods are useful for building monitoring dashboards, implementing balance checks before batch operations, or automating session cleanup.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY"
});

async function accountOperations() {
  const balance = await client.getBalance();
  console.log("Current balance:", balance);

  const accountInfo = await client.getAccountInfo();
  console.log("Account:", accountInfo);

  const session = await client.createSession({
    mode: "passive",
    timeout: 300
  });
  console.log("Session ID:", session.sessionId);

  const status = await client.getSessionStatus(session.sessionId);
  console.log("Session status:", status);

  await client.closeSession(session.sessionId);
  console.log("Session closed");
}

accountOperations();

BBRESession Quick Example

BBRESession is designed for workflows that require persistent state across multiple requests. When you call session.start(), the SDK creates a BBRE session on the server and stores the session ID internally. Every subsequent call to session.request() automatically includes the session ID, so cookies, login state, and browser identity persist across all requests within the session. When your workflow is complete, calling session.close() terminates the server-side session and frees up your active session slot. The following example demonstrates a complete login-and-scrape workflow using BBRESession.

JavaScript
const { BBRESession } = require("mydisctsolver-bbre");

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "medium",
  sessionTime: 3
});

async function loginAndScrape() {
  await session.start();
  console.log("Session started:", session.getSessionId());

  const loginResult = await session.request({
    url: "https://example.com/api/login",
    method: "POST",
    body: {
      username: "myuser",
      password: "mypassword"
    }
  });
  console.log("Login status:", loginResult.statusCode);

  const dashboardResult = await session.request({
    url: "https://example.com/dashboard",
    method: "GET"
  });
  console.log("Dashboard status:", dashboardResult.statusCode);
  console.log("Dashboard body length:", dashboardResult.body.length);

  const profileResult = await session.request({
    url: "https://example.com/api/profile",
    method: "GET"
  });
  console.log("Profile data:", profileResult.body);

  const cookies = await session.getCookies();
  console.log("Session cookies:", cookies);

  await session.close();
  console.log("Session closed");
}

loginAndScrape();

Notice how the login cookies from the first request are automatically available to the dashboard and profile requests. You do not need to extract cookies manually or pass them between requests. The BBRESession handles all of this internally through the server-side session. The sessionTime parameter controls how long the session stays alive in minutes, with a range of 0.5 to 5 minutes. The SDK converts this value into the appropriate timeout for the API.

Session with Form Submission

BBRESession includes a submitForm() method that simplifies form submission workflows. Instead of manually constructing POST requests with form data, you provide the form URL and field values, and the SDK handles the rest. This is particularly useful for multi-step form wizards where each step depends on the state established by the previous step.

JavaScript
const { BBRESession } = require("mydisctsolver-bbre");

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "high"
});

async function submitRegistrationForm() {
  await session.start();

  const formResult = await session.submitForm({
    url: "https://example.com/register",
    fields: {
      firstName: "John",
      lastName: "Doe",
      email: "[email protected]",
      password: "securePassword123"
    }
  });
  console.log("Form submitted:", formResult.statusCode);

  const confirmResult = await session.request({
    url: "https://example.com/registration-complete",
    method: "GET"
  });
  console.log("Confirmation page:", confirmResult.statusCode);

  await session.close();
}

submitRegistrationForm();

BrowserAPI Quick Example

The BrowserAPI class provides browser automation capabilities through the session.browser property. This is where the BBRE engine truly shines for complex web interactions. You can navigate to pages, click buttons, fill input fields, select dropdown options, take screenshots, scroll through content, wait for elements to appear, and execute arbitrary JavaScript on the page. Browser actions require an adaptive mode session because they need a full browser instance running on the server. The following example demonstrates a complete browser automation workflow that navigates to a website, fills a login form, clicks the submit button, waits for the dashboard to load, and takes a screenshot of the result.

JavaScript
const { BBRESession } = require("mydisctsolver-bbre");

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive",
  sensibility: "high",
  browserSpeed: "human",
  sessionTime: 5
});

async function browserAutomation() {
  await session.start();

  await session.browser.navigate("https://example.com/login");

  await session.browser.fill("#email", "[email protected]");
  await session.browser.fill("#password", "mypassword");
  await session.browser.click("#login-button");

  await session.browser.waitForElement(".dashboard-container", {
    timeout: 10000
  });

  const title = await session.browser.getTitle();
  console.log("Page title:", title);

  const dashboardText = await session.browser.getText(".welcome-message");
  console.log("Welcome message:", dashboardText);

  const screenshot = await session.browser.screenshot();
  console.log("Screenshot captured, size:", screenshot.length);

  await session.browser.click(".settings-link");
  await session.browser.waitForElement(".settings-form");

  const currentUrl = await session.browser.getUrl();
  console.log("Current URL:", currentUrl);

  await session.close();
}

browserAutomation();

Every BrowserAPI method sends a browser action to the BBRE engine through the POST /browser/action endpoint. The SDK handles the action formatting, session ID injection, and response parsing automatically. If a browser action fails and the session was created with force: false (the default), the session will stop processing further actions. If you set force: true in the session configuration, the session will continue even when individual browser actions fail, which is useful for resilient scraping workflows where some elements might not always be present on the page.

Data Extraction with BrowserAPI

One of the most common use cases for BrowserAPI is extracting data from JavaScript-rendered pages that cannot be scraped with simple HTTP requests. The following example navigates to a product listing page, scrolls to load dynamic content, extracts product information using getText() and getHtml(), and uses execute() to run custom JavaScript for more complex data extraction.

JavaScript
const { BBRESession } = require("mydisctsolver-bbre");

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive",
  sensibility: "medium",
  browserSpeed: "fast"
});

async function extractProductData() {
  await session.start();

  await session.browser.navigate("https://example.com/products");
  await session.browser.waitForElement(".product-grid");

  await session.browser.scrollDown();
  await session.browser.wait(2000);
  await session.browser.scrollDown();
  await session.browser.wait(2000);

  const pageHtml = await session.browser.getHtml(".product-grid");
  console.log("Product grid HTML length:", pageHtml.length);

  const productCount = await session.browser.execute(
    "return document.querySelectorAll('.product-card').length"
  );
  console.log("Products loaded:", productCount);

  const firstProductName = await session.browser.getText(".product-card:first-child .name");
  console.log("First product:", firstProductName);

  await session.close();
}

extractProductData();

Import Patterns

The mydisctsolver-bbre package supports multiple import patterns to fit different coding styles and project configurations. The default export is the BBREClient class, and all three classes are also available as named exports. Choose the pattern that best matches your project conventions and the classes you need.

Default Import (BBREClient Only)

The simplest import pattern. When you require the package without destructuring, you get the BBREClient class directly. This is the most common pattern when you only need stateless request functionality and account management.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY"
});

Named Import (Single Class)

Use destructuring to import a specific class by name. This is useful when you need BBRESession or BrowserAPI specifically, or when you want to make it explicit which class you are importing.

JavaScript
const { BBREClient } = require("mydisctsolver-bbre");
const { BBRESession } = require("mydisctsolver-bbre");
const { BrowserAPI } = require("mydisctsolver-bbre");

Multiple Named Imports

Import multiple classes in a single statement when your code uses more than one class. This is the recommended pattern for applications that use both BBREClient for stateless operations and BBRESession for session-based workflows.

JavaScript
const { BBREClient, BBRESession, BrowserAPI } = require("mydisctsolver-bbre");

const client = new BBREClient({ apiKey: "YOUR_API_KEY" });

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive"
});

ES Module Import

If your project uses ES modules (with "type": "module" in package.json or .mjs file extensions), you can use the import syntax. The package supports both CommonJS and ES module imports.

JavaScript
import BBREClient from "mydisctsolver-bbre";
import { BBRESession, BrowserAPI } from "mydisctsolver-bbre";

Configuration Options

Both BBREClient and BBRESession accept a configuration object in their constructors. The configuration controls API connectivity, default request behavior, and session-specific settings. The following tables document every configuration option, its type, default value, and detailed description. Understanding these options allows you to fine-tune the SDK behavior for your specific use case without needing to pass the same parameters on every method call.

BBREClient Configuration

These options are available when creating a BBREClient instance. Since BBRESession extends BBREClient, all of these options are also available when creating a BBRESession instance.

Parameter Type Required Default Description
apiKey string required - Your BBRE API key. This is the only required parameter. The SDK includes this key in the x-api-key header of every API request automatically. You can find your API key in the MyDisct Solver dashboard.
mode string optional "passive" The default operating mode for requests. "passive" uses a lightweight HTTP client without launching a full browser. "adaptive" uses a full browser instance with JavaScript execution and DOM rendering. This default can be overridden on individual requests.
sensibility string optional "medium" The default detection evasion sensitivity level. "low" is fastest with basic evasion. "medium" balances speed and evasion quality. "high" applies maximum evasion techniques including human-like timing and advanced fingerprint consistency. This default can be overridden on individual requests.
timeout number optional 120 The default timeout in seconds for API requests. This controls how long the SDK waits for a response from the BBRE API before throwing a timeout error. For long-running adaptive mode requests, you may need to increase this value.
pollingInterval number optional 2000 The interval in milliseconds between polling attempts when waiting for an asynchronous request to complete. The SDK uses this interval when calling /request/result to check if a task has finished processing. Lower values mean faster result detection but more API calls. Higher values reduce API call volume but increase latency.
fingerprint object optional {} Default browser fingerprint configuration applied to all requests. Includes attributes like userAgent, platform, screen, timezone, language, and webgl. Can be overridden per-request or updated using setDefaultFingerprint().
proxy object optional null Default proxy configuration applied to all requests. Must contain host (string) and port (number). Optionally includes username and password for authenticated proxies. Can be overridden per-request or updated using setDefaultProxy().

BBRESession Additional Configuration

In addition to all BBREClient options, BBRESession accepts the following session-specific configuration parameters. These control the behavior of the managed session that the SDK creates when you call session.start().

Parameter Type Required Default Description
browserSpeed string optional "instant" Controls the speed of browser actions within the session. "instant" executes actions immediately with no artificial delays. "fast" adds small delays between actions to appear more natural. "human" adds realistic human-like delays including variable typing speed and mouse movement pauses. Use "human" for websites with sophisticated bot detection that monitors interaction timing.
force boolean optional false When set to true, the session continues processing even when a browser action fails. By default (false), a failed browser action stops the session to prevent cascading errors. Set to true for resilient scraping workflows where some elements might not always be present on the page.
sessionTime number optional 2 Session duration in minutes. Accepts values between 0.5 and 5. The SDK uses this value to calculate the appropriate timeout for the session creation API call. A value of 2 means the session stays alive for approximately 2 minutes after creation. Increase this for longer workflows like multi-page form submissions or extensive data collection.

Configuration Example

The following example shows a fully configured BBRESession instance with all available options specified. In practice, you will only need to set the options relevant to your use case. The apiKey is the only required parameter.

JavaScript
const { BBRESession } = require("mydisctsolver-bbre");

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive",
  sensibility: "high",
  timeout: 180,
  pollingInterval: 3000,
  fingerprint: {
    platform: "Win32",
    timezone: "America/New_York",
    language: "en-US",
    screen: { width: 1920, height: 1080 }
  },
  proxy: {
    host: "us-residential.proxy.com",
    port: 8080,
    username: "proxyuser",
    password: "proxypass"
  },
  browserSpeed: "human",
  force: false,
  sessionTime: 4
});

Error Handling Patterns

The SDK throws errors when API calls fail, when sessions expire, when browser actions encounter problems, or when network connectivity issues occur. Proper error handling is essential for building reliable BBRE integrations. The SDK normalizes error responses from the API into JavaScript Error objects with descriptive messages, so you can use standard try/catch blocks to handle failures gracefully. The following patterns demonstrate how to handle errors at different levels of your application.

Basic Try/Catch Pattern

The simplest error handling approach wraps your SDK calls in a try/catch block. This catches any error thrown by the SDK, whether it is an API error, a network error, or a timeout error.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY"
});

async function safeRequest() {
  try {
    const result = await client.get("https://example.com/data");
    console.log("Success:", result.statusCode);
    return result;
  } catch (error) {
    console.error("Request failed:", error.message);
    return null;
  }
}

safeRequest();

Session Error Handling with Cleanup

When working with sessions, it is critical to ensure the session is closed even when errors occur. Use a try/finally pattern to guarantee session cleanup regardless of whether the workflow succeeds or fails. This prevents orphaned sessions from consuming your active session slots.

JavaScript
const { BBRESession } = require("mydisctsolver-bbre");

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive",
  sessionTime: 3
});

async function safeSessionWorkflow() {
  try {
    await session.start();
    console.log("Session started:", session.getSessionId());

    await session.browser.navigate("https://example.com");
    await session.browser.fill("#search", "BBRE SDK");
    await session.browser.click("#search-button");
    await session.browser.waitForElement(".results");

    const results = await session.browser.getText(".results");
    console.log("Results:", results);

    return results;
  } catch (error) {
    console.error("Workflow failed:", error.message);
    return null;
  } finally {
    if (session.isActive()) {
      await session.close();
      console.log("Session cleaned up");
    }
  }
}

safeSessionWorkflow();

Retry Pattern for Transient Errors

Some errors are transient and can be resolved by retrying the request after a short delay. Network timeouts, temporary service unavailability, and rate limiting are common examples. The following pattern implements a simple retry mechanism with exponential backoff that works well for BBRE SDK operations.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  sensibility: "medium"
});

async function retryableRequest(url, maxRetries) {
  let lastError;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const result = await client.get(url);
      return result;
    } catch (error) {
      lastError = error;
      console.log("Attempt " + attempt + " failed:", error.message);

      if (attempt < maxRetries) {
        const delay = Math.pow(2, attempt) * 1000;
        console.log("Retrying in " + delay + "ms...");
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  }

  throw lastError;
}

retryableRequest("https://example.com/api/data", 3);

Balance Check Before Batch Operations

When running batch operations that make many requests, check your account balance before starting to avoid running out of credits mid-operation. The getBalance() method returns your current balance, which you can compare against the estimated cost of your batch.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY"
});

async function batchWithBalanceCheck(urls) {
  const balance = await client.getBalance();
  console.log("Current balance:", balance);

  const estimatedCost = urls.length * 0.01;
  if (balance < estimatedCost) {
    console.log("Insufficient balance for batch. Need:", estimatedCost);
    return [];
  }

  const results = [];
  for (const url of urls) {
    try {
      const result = await client.get(url);
      results.push({ url, status: result.statusCode, body: result.body });
    } catch (error) {
      results.push({ url, error: error.message });
    }
  }

  return results;
}

batchWithBalanceCheck([
  "https://example.com/page1",
  "https://example.com/page2",
  "https://example.com/page3"
]);

SDK vs Direct API Comparison

You can interact with the BBRE engine either through the SDK or by making direct HTTP calls to the API. Both approaches give you access to the same functionality, but the SDK significantly reduces the amount of boilerplate code you need to write. The following comparison shows the same operation implemented both ways, so you can see exactly what the SDK handles for you behind the scenes.

Making a Request: Direct API

When using the API directly, you need to manage authentication headers, construct the request body, handle the asynchronous polling loop, and parse the nested response structure yourself. This is approximately 40 lines of code for a single request.

JavaScript
const axios = require("axios");

const API_BASE = "https://bbre-solver-api.mydisct.com";
const API_KEY = "YOUR_API_KEY";
const headers = {
  "Content-Type": "application/json",
  "x-api-key": API_KEY
};

async function directApiRequest() {
  const createResponse = await axios.post(
    API_BASE + "/request/create",
    {
      url: "https://example.com/data",
      method: "GET",
      mode: "passive",
      sensibility: "medium"
    },
    { headers }
  );

  const taskId = createResponse.data.data.task.taskId;

  let result;
  while (true) {
    const resultResponse = await axios.post(
      API_BASE + "/request/result",
      { taskId },
      { headers }
    );

    if (resultResponse.data.data.task.status === "completed") {
      result = resultResponse.data.data.task.result;
      break;
    }

    if (resultResponse.data.data.task.status === "failed") {
      throw new Error("Request failed");
    }

    await new Promise(resolve => setTimeout(resolve, 2000));
  }

  console.log("Status:", result.statusCode);
  console.log("Body:", result.body);
}

directApiRequest();

Making a Request: SDK

The same operation with the SDK takes about 10 lines of code. The SDK handles authentication, request creation, polling, and response parsing internally. You get the result directly without managing any intermediate steps.

JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "medium"
});

async function sdkRequest() {
  const result = await client.get("https://example.com/data");
  console.log("Status:", result.statusCode);
  console.log("Body:", result.body);
}

sdkRequest();

Feature Comparison

Feature Direct API SDK
Authentication Manual header management on every request Automatic, configured once in constructor
Async Polling Manual polling loop with status checks Automatic with configurable polling interval
Response Parsing Navigate nested response structure manually Parsed and flattened automatically
Session Management Manual session ID tracking and cleanup Automatic with BBRESession class
Browser Actions Manual action formatting and API calls Fluent BrowserAPI interface
Default Settings Must include in every request body Set once, applied automatically
Error Handling Parse error responses manually Normalized JavaScript errors
Code Volume High (40+ lines per operation) Low (5-15 lines per operation)

Method Reference Summary

The following tables provide a quick reference of all methods available on each class. Click the method name to navigate to its detailed documentation page with full parameter descriptions, return types, and working code examples.

BBREClient Methods

Method Description Documentation
request(options) Send a request through the BBRE engine with full control over all parameters. request() Reference
get(url, options) Send a GET request through the BBRE engine. HTTP Methods Reference
post(url, options) Send a POST request with an optional request body. HTTP Methods Reference
put(url, options) Send a PUT request for updating resources. HTTP Methods Reference
delete(url, options) Send a DELETE request for removing resources. HTTP Methods Reference
patch(url, options) Send a PATCH request for partial updates. HTTP Methods Reference
head(url, options) Send a HEAD request to retrieve headers only. HTTP Methods Reference
options(url, options) Send an OPTIONS request to check allowed methods. HTTP Methods Reference
getBalance() Retrieve your current account balance. Account Methods Reference
getAccountInfo() Retrieve detailed account information and statistics. Account Methods Reference
createSession(options) Create a new BBRE session with specified configuration. Session Management Reference
closeSession(sessionId) Close an active session and release its resources. Session Management Reference
getSessionStatus(sessionId) Check the current status and statistics of a session. Session Management Reference
setDefaultFingerprint(fp) Set the default browser fingerprint for all subsequent requests. Default Settings Reference
setDefaultProxy(proxy) Set the default proxy configuration for all subsequent requests. Default Settings Reference
setDefaultMode(mode) Change the default operating mode (passive or adaptive). Default Settings Reference
setDefaultSensibility(level) Change the default sensibility level (low, medium, or high). Default Settings Reference

BBRESession Methods

BBRESession inherits all BBREClient methods listed above and adds the following session-specific methods.

Method Description Documentation
start() Create and activate a new session on the BBRE server. Session Lifecycle Reference
close() Close the active session and release server resources. Session Lifecycle Reference
status() Check the current status of the active session. Session Lifecycle Reference
request(options) Send a request within the active session, maintaining cookies and state. Session Request Reference
submitForm(options) Submit a form with specified field values within the session. Session Request Reference
runSteps(steps) Execute a sequence of steps within the session. Session Request Reference
interact(options) Perform an interactive operation within the session. Session Request Reference
checkPage(url) Check a page within the session context. Session Request Reference
setBrowserSpeed(speed) Change the browser action speed (instant, fast, or human). Session Config Reference
getBrowserSpeed() Get the current browser action speed setting. Session Config Reference
getProfile() Get the full browser profile generated by the BBRE engine. Session Config Reference
hasProfile() Check if a browser profile has been generated for this session. Session Config Reference
getProfileSummary() Get a summary of the browser profile. Session Config Reference
getSessionId() Get the current session ID. Session Lifecycle Reference
isActive() Check if the session is currently active. Session Lifecycle Reference
getCookies() Get all cookies stored in the session. Session Config Reference
setCookie(cookie) Set a cookie in the session. Session Config Reference
deleteCookie(name) Delete a specific cookie from the session. Session Config Reference
clearCookies() Clear all cookies from the session. Session Config Reference

BrowserAPI Methods

Accessed through session.browser. Requires an adaptive mode session.

Method Description Documentation
navigate(url, options) Navigate the browser to a URL. Navigation Reference
goto(url, options) Alias for navigate. Navigate to a URL. Navigation Reference
reload() Reload the current page. Navigation Reference
back() Navigate back in browser history. Navigation Reference
forward() Navigate forward in browser history. Navigation Reference
click(selector) Click an element matching the CSS selector. Interaction Reference
fill(selector, value) Clear and fill an input field with the specified value. Interaction Reference
type(selector, text) Type text into an element character by character. Interaction Reference
select(selector, value) Select an option from a dropdown element. Interaction Reference
checkbox(selector, checked) Set the checked state of a checkbox element. Interaction Reference
fillForm(formData) Fill multiple form fields at once. Interaction Reference
clear(selector) Clear the value of an input field. Interaction Reference
getHtml(selector) Get the HTML content of an element. Query Reference
getText(selector) Get the text content of an element. Query Reference
getTitle() Get the current page title. Query Reference
getUrl() Get the current page URL. Query Reference
screenshot() Capture a screenshot of the current page. Advanced Reference
wait(ms) Wait for a specified number of milliseconds. Wait Reference
waitForElement(selector, options) Wait for an element to appear in the DOM. Wait Reference
waitForText(text, options) Wait for specific text to appear on the page. Wait Reference
waitForSelector(selector, options) Wait for a CSS selector to match an element. Wait Reference
find(selector) Find elements matching a CSS selector. Query Reference
findByText(text) Find elements containing specific text. Query Reference
scroll(options) Scroll the page by specified amount. Scroll Reference
scrollDown() Scroll down by one viewport height. Scroll Reference
scrollUp() Scroll up by one viewport height. Scroll Reference
scrollToTop() Scroll to the top of the page. Scroll Reference
scrollToBottom() Scroll to the bottom of the page. Scroll Reference
getCookies() Get all browser cookies. Advanced Reference
setCookie(cookie) Set a browser cookie. Advanced Reference
clearCookies() Clear all browser cookies. Advanced Reference
execute(script) Execute JavaScript code in the browser context. Advanced Reference
evaluate(script) Evaluate JavaScript and return the result. Advanced Reference

Complete Integration Example

The following example demonstrates a realistic integration scenario that combines all three SDK classes. The workflow creates an adaptive session, navigates to a website, logs in through a form, extracts data from the authenticated dashboard, and handles errors gracefully with proper session cleanup. This pattern is representative of how production BBRE integrations typically work.

JavaScript
const { BBREClient, BBRESession } = require("mydisctsolver-bbre");

const API_KEY = "YOUR_API_KEY";

async function completeIntegration() {
  const client = new BBREClient({ apiKey: API_KEY });

  const balance = await client.getBalance();
  console.log("Account balance:", balance);

  if (balance < 0.50) {
    console.log("Low balance, aborting");
    return;
  }

  const session = new BBRESession({
    apiKey: API_KEY,
    mode: "adaptive",
    sensibility: "high",
    browserSpeed: "human",
    sessionTime: 4,
    fingerprint: {
      platform: "Win32",
      timezone: "America/New_York",
      language: "en-US",
      screen: { width: 1920, height: 1080 }
    },
    proxy: {
      host: "us-residential.proxy.com",
      port: 8080,
      username: "proxyuser",
      password: "proxypass"
    }
  });

  try {
    await session.start();
    console.log("Session started:", session.getSessionId());

    await session.browser.navigate("https://example.com/login");
    await session.browser.waitForElement("#login-form");

    await session.browser.fill("#username", "myuser");
    await session.browser.fill("#password", "mypassword");
    await session.browser.click("#login-submit");

    await session.browser.waitForElement(".dashboard", { timeout: 15000 });
    console.log("Login successful");

    const welcomeText = await session.browser.getText(".welcome-banner");
    console.log("Welcome:", welcomeText);

    await session.browser.navigate("https://example.com/account/orders");
    await session.browser.waitForElement(".orders-table");

    const ordersHtml = await session.browser.getHtml(".orders-table");
    console.log("Orders HTML length:", ordersHtml.length);

    const orderCount = await session.browser.execute(
      "return document.querySelectorAll('.order-row').length"
    );
    console.log("Total orders:", orderCount);

    const screenshot = await session.browser.screenshot();
    console.log("Screenshot size:", screenshot.length);

    if (session.hasProfile()) {
      const profile = session.getProfileSummary();
      console.log("Browser profile:", profile);
    }

    const cookies = await session.getCookies();
    console.log("Session cookies:", cookies.length);

  } catch (error) {
    console.error("Integration failed:", error.message);
  } finally {
    if (session.isActive()) {
      await session.close();
      console.log("Session closed");
    }
  }

  const accountInfo = await client.getAccountInfo();
  console.log("Remaining balance:", accountInfo.balance);
}

completeIntegration();

Best Practices

Always Use Try/Finally for Session Cleanup

Wrap all session-based workflows in a try/finally block to ensure the session is closed even when errors occur. Orphaned sessions consume your active session slots (maximum 10 per account) and waste server resources. The session.isActive() method lets you check whether the session needs to be closed before calling session.close(). This pattern is the single most important practice for reliable BBRE integrations and prevents the most common issue developers encounter, which is hitting the session limit due to unclosed sessions.

Choose the Right Class for Your Use Case

Use BBREClient for simple, stateless requests where you do not need cookies or session state to persist between requests. Use BBRESession when your workflow requires login persistence, cookie management, or multi-step interactions with a website. Only use adaptive mode and BrowserAPI when you genuinely need browser automation capabilities like clicking, filling forms, or executing JavaScript. Passive mode is faster, cheaper, and sufficient for most HTTP request workflows. Starting with the simplest class that meets your needs keeps your code lean and your costs low.

Configure Defaults at the Client Level

Set common configuration like mode, sensibility, fingerprint, and proxy in the constructor rather than passing them on every method call. The SDK applies these defaults automatically to all requests, which reduces code duplication and ensures consistency. You can override any default on a per-request basis when needed. Use setDefaultFingerprint(), setDefaultProxy(), setDefaultMode(), and setDefaultSensibility() to update defaults at runtime without creating a new client instance.

Check Balance Before Batch Operations

Before starting a batch of requests, call client.getBalance() to verify you have sufficient credits. Running out of balance mid-batch causes INSUFFICIENT_BALANCE errors that interrupt your workflow and may leave sessions in an inconsistent state. Estimate the total cost of your batch based on the number of requests and the per-request pricing, then compare it against your available balance. This simple check prevents wasted processing time and partial results.

Use Human Browser Speed for Protected Websites

When automating interactions on websites with sophisticated bot detection, set browserSpeed: "human" in your BBRESession configuration. This adds realistic delays between browser actions, including variable typing speed and natural pauses between clicks. Combined with sensibility: "high", human browser speed significantly reduces the chance of being detected as a bot. For websites without aggressive bot detection, "instant" or "fast" speeds are more efficient and complete workflows faster.

Reuse Client Instances Across Requests

Create a single BBREClient or BBRESession instance and reuse it for multiple operations rather than creating a new instance for each request. The client instance maintains your configuration, default settings, and internal state efficiently. Creating new instances for every request adds unnecessary overhead and makes it harder to maintain consistent settings across your application. In a web server context, create the client instance once during application startup and share it across request handlers.

Common Issues

Issue 1: "Cannot find module 'mydisctsolver-bbre'" Error

Problem

When you try to require the SDK, Node.js throws a MODULE_NOT_FOUND error with the message "Cannot find module 'mydisctsolver-bbre'". This happens even though you believe the package is installed.

Solution: Verify the package is installed in the correct directory by running npm list mydisctsolver-bbre in your project root. If the package is not listed, run npm install mydisctsolver-bbre to install it. If you are using a monorepo or workspace setup, make sure you are installing the package in the correct workspace. Also check that your node_modules directory exists and is not corrupted. Deleting node_modules and running npm install again often resolves module resolution issues.

Issue 2: Session Limit Reached After Errors

Problem

After running your application several times during development, you start getting SESSION_LIMIT_REACHED errors when trying to create new sessions. This typically happens when your code crashes or throws errors without closing the session, leaving orphaned sessions that count toward your 10-session limit.

Solution: First, use client.getAccountInfo() or the Account Sessions API to list your active sessions and close them manually using client.closeSession(sessionId). To prevent this in the future, always wrap session workflows in try/finally blocks as shown in the error handling section above. The session.isActive() check in the finally block ensures you only attempt to close sessions that are still active, avoiding errors when closing already-closed or expired sessions.

Issue 3: Browser Actions Failing in Passive Mode

Problem

Calls to session.browser.navigate(), session.browser.click(), or other BrowserAPI methods fail with an error indicating that browser actions are not supported. The session was created with the default mode setting.

Solution: Browser actions require an adaptive mode session. The default mode is "passive", which does not launch a full browser instance and therefore cannot execute browser automation actions. Change your session configuration to use mode: "adaptive" when you need to use BrowserAPI methods. If you only need HTTP-level interactions (sending requests and receiving responses), passive mode is sufficient and more efficient. Only switch to adaptive mode when you genuinely need browser automation capabilities like page navigation, element clicking, form filling, or JavaScript execution.

Issue 4: Timeout Errors on Adaptive Mode Requests

Problem

Requests in adaptive mode frequently time out, especially when using high sensibility. The default timeout of 120 seconds is not enough for the BBRE engine to complete the request with full browser rendering and evasion techniques.

Solution: Increase the timeout value in your client configuration. Adaptive mode with high sensibility can take significantly longer than passive mode because the BBRE engine needs to launch a browser, render the page, execute JavaScript, and apply human-like timing delays. A timeout of 180 to 300 seconds is recommended for adaptive mode with high sensibility. You can also increase the sessionTime for BBRESession to ensure the session stays alive long enough for your workflow to complete. If timeouts persist, consider using medium sensibility for less critical requests to reduce processing time.