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

BBRESession Overview

The BBRESession class is the session-aware counterpart to BBREClient in the mydisctsolver-bbre SDK. While BBREClient handles stateless, one-off requests to the BBRE engine, BBRESession extends it with full session lifecycle management, persistent cookie storage, browser profile tracking, and direct access to the BrowserAPI for browser automation. When you create a BBRESession instance, you get everything that BBREClient offers plus the ability to start a persistent browser session, send multiple requests within that session while preserving cookies and identity, control browser speed, manage session state, and execute high-level browser workflows like form submission, multi-step interactions, and page checking. The class inherits all BBREClient methods (including request(), get(), post(), getBalance(), getAccountInfo(), and the default setters) and adds session-specific methods for lifecycle control, cookie management, profile inspection, and browser automation. This page provides a complete overview of the BBRESession class, its relationship to BBREClient, the constructor configuration, session lifecycle concepts, the internal BrowserAPI instance, force mode behavior, browser speed settings, session time configuration, a full method reference table, quick start examples, and a detailed comparison between BBRESession and BBREClient to help you decide which class to use for your specific use case.

When to Use BBRESession

Use BBRESession when your workflow requires maintaining state across multiple requests. This includes scenarios like logging into a website and performing authenticated actions, filling out multi-step forms, navigating through paginated content while preserving cookies, interacting with JavaScript-heavy single-page applications, or any workflow where you need the BBRE engine to remember your browser identity between requests. If you only need to make isolated, stateless HTTP requests, BBREClient is the simpler and more appropriate choice.

What is BBRESession?

The BBRESession class represents a stateful browser session managed by the BBRE engine. Unlike BBREClient, which treats every request as an independent operation, BBRESession creates a persistent server-side session that maintains a real browser instance with its own cookies, fingerprint profile, and browsing history. Every request you send through a BBRESession instance goes through the same browser context on the server, which means the target website sees a consistent visitor identity across all your requests.

At its core, BBRESession is a BBREClient with session state bolted on. It extends BBREClient through standard JavaScript class inheritance, so every method available on BBREClient is also available on BBRESession. On top of that, it adds session lifecycle methods (start(), close(), status()), session-scoped request handling, cookie persistence, profile tracking, browser speed configuration, and a built-in BrowserAPI instance for direct browser automation.

The BBRE system allows a maximum of 10 active sessions per account at any given time. Each session consumes server resources (a dedicated browser instance), so it is important to close sessions when you are done with them. Sessions also have a configurable timeout (between 0.5 and 5 minutes) after which they expire automatically if no activity is detected.

Class Hierarchy

The SDK is built around three classes that work together. Understanding their relationship helps you choose the right tool for each task.

Text
BBREClient (base class)
  |
  +-- BBRESession (extends BBREClient)
        |
        +-- this.browser (BrowserAPI instance)

BBREClient is the foundation. It handles API authentication, request creation, response polling, HTTP convenience methods, account queries, session management via the API, and default configuration. Every interaction with the BBRE API goes through methods defined on BBREClient.

BBRESession extends BBREClient and adds session awareness. When you call start(), it uses the inherited createSession() method to open a session on the server, then stores the session ID, expiration time, and profile locally. All subsequent requests through the session instance automatically include the session ID and merge cookies. When you call close(), it uses the inherited closeSession() method to terminate the server-side session and resets the local state.

BrowserAPI is a helper class that provides a clean interface for browser automation actions. Every BBRESession instance creates a BrowserAPI instance at this.browser during construction. The BrowserAPI methods (like navigate(), click(), fill()) internally call the session's _browserAction() method, which sends browser action requests to the BBRE API using the session ID.

Inheritance from BBREClient

Because BBRESession extends BBREClient, every method and property defined on BBREClient is available on your session instance. This means you can use a BBRESession instance for both session-based workflows and standalone operations without creating a separate BBREClient. The following table lists all inherited methods and what they do when called on a BBRESession instance.

Inherited Methods from BBREClient

Method Category Description
get(url, options) HTTP Sends a GET request through the BBRE engine. When called on a session instance, this sends a standalone request outside the session context.
post(url, body, options) HTTP Sends a POST request through the BBRE engine. Operates independently of the session state.
put(url, body, options) HTTP Sends a PUT request through the BBRE engine.
delete(url, options) HTTP Sends a DELETE request through the BBRE engine.
patch(url, body, options) HTTP Sends a PATCH request through the BBRE engine.
head(url, options) HTTP Sends a HEAD request through the BBRE engine.
options(url, options) HTTP Sends an OPTIONS request through the BBRE engine.
getBalance() Account Returns your current account balance as a number.
getAccountInfo() Account Returns an object with account and statistics properties containing your account details and usage metrics.
createSession(options) Session Creates a new session on the server. The start() method calls this internally, so you typically do not call it directly on a BBRESession instance.
closeSession(sessionId) Session Closes a session by ID. The close() method calls this internally using the current session ID.
getSessionStatus(sessionId) Session Gets the status of a session by ID. The status() method calls this internally using the current session ID.
setDefaultFingerprint(fp) Config Sets the default fingerprint object for future requests.
setDefaultProxy(proxy) Config Sets the default proxy for future requests.
setDefaultMode(mode) Config Sets the default mode ("passive" or "adaptive") for future requests.
setDefaultSensibility(level) Config Sets the default sensibility level ("low", "medium", or "high") for future requests.

Important Note About Inherited HTTP Methods

The inherited HTTP convenience methods (get(), post(), etc.) call the parent BBREClient.request() method, not the overridden BBRESession.request() method. This means they send standalone requests through the BBRE engine without using the session context. If you want to send requests within the session (preserving cookies and using the session's browser instance), use the session's own request() method directly:

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

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

const sessionResponse = await session.request({
  url: "https://example.com/dashboard",
  method: "GET"
});

const standaloneResponse = await session.get("https://example.com/public-page");

await session.close();

Constructor Configuration

The BBRESession constructor accepts a configuration object that includes all BBREClient parameters plus three session-specific parameters: browserSpeed, force, and sessionTime. The constructor calls super(config) to initialize the BBREClient base class with the shared parameters, then sets up the session-specific state including an empty cookie store, null session ID, null profile, and a new BrowserAPI instance.

Constructor Signature

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

const session = new BBRESession(config);

Inherited Parameters (from BBREClient)

These parameters are passed to the BBREClient constructor through super(config) and control the base client behavior.

Parameter Type Required Default Description
apiKey string Required null Your BBRE API key for authentication. All API calls use this key in the X-API-Key header.
mode string Optional "passive" Default request mode. Use "passive" for simple HTTP requests or "adaptive" for full browser automation. Sessions that use browser actions require "adaptive" mode.
sensibility string Optional "medium" Default sensibility level. Accepts "low", "medium", or "high". Higher sensibility means slower but more careful request handling.
timeout number Optional 120 Default timeout in seconds for individual requests.
pollingInterval number Optional 2000 Polling interval in milliseconds for async request result checking.
fingerprint object Optional {} Default fingerprint configuration object containing browser identity properties like userAgent, platform, screen dimensions, timezone, and locale.
proxy string Optional null Default proxy URL for routing requests. Format: protocol://user:pass@host:port.

Session-Specific Parameters

These parameters are unique to BBRESession and control session behavior, browser speed, and error handling.

Parameter Type Required Default Description
browserSpeed string Optional "instant" Controls the speed of browser actions. Accepts "instant" (no artificial delays), "fast" (minimal delays between actions), or "human" (realistic human-like delays). Affects all browser actions sent through this.browser and the high-level methods.
force boolean Optional false Controls error handling for browser actions. When false (default), any browser action error automatically closes the session and throws an error prefixed with [SESSION_STOPPED]. When true, errors return a result object instead of closing the session, allowing you to handle errors and continue.
sessionTime number Optional 2 Session duration in minutes. Accepts values between 0.5 and 5. Values outside this range are clamped automatically. Converted to seconds when start() creates the session on the server.

Full Constructor Example

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

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive",
  sensibility: "high",
  timeout: 180,
  pollingInterval: 3000,
  fingerprint: {
    userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    platform: "Win32",
    screenWidth: 1920,
    screenHeight: 1080,
    timezone: "America/New_York",
    locale: "en-US"
  },
  proxy: "http://user:[email protected]:8080",
  browserSpeed: "human",
  force: true,
  sessionTime: 4
});

Minimal Constructor Example

For most use cases, you only need to provide the API key and the mode. The following example creates a session with adaptive mode (required for browser actions) and all other parameters at their default values.

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

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

What Happens During Construction

When you create a new BBRESession instance, the constructor performs the following steps in order:

  1. Calls super(config) to initialize the BBREClient base class with apiKey, mode, sensibility, timeout, pollingInterval, fingerprint, and proxy.
  2. Initializes this.sessionCookies as an empty object to store cookies accumulated during the session.
  3. Sets this.sessionId to null (no active session yet).
  4. Sets this.sessionExpiresAt to null (no expiration until session starts).
  5. Sets this.sessionProfile to null (no browser profile until session starts).
  6. Sets this.browserSpeed from the config or defaults to "instant".
  7. Sets this.force to true only if config.force === true, otherwise false.
  8. Calculates this.sessionTime by clamping the provided value between 0.5 and 5 minutes (default: 2).
  9. Creates a new BrowserAPI instance at this.browser, passing the session instance as the context.

Note that construction does not start a session on the server. The session is only created when you explicitly call start(). This separation allows you to configure the instance and perform pre-flight checks (like balance verification) before consuming a session slot.

Session Lifecycle

Every BBRESession follows a predictable lifecycle: construct, start, perform work, and close. Understanding this lifecycle is essential for writing reliable session-based code and avoiding resource leaks. The BBRE system enforces a limit of 10 active sessions per account, so failing to close sessions properly can prevent you from creating new ones.

Lifecycle Stages

Text
1. CONSTRUCT    new BBRESession(config)     Local instance created, no server session
2. START        await session.start()       Server session created, browser allocated
3. WORK         await session.request(...)  Send requests, use browser, manage cookies
                await session.browser.navigate(...)
                await session.submitForm(...)
4. CLOSE        await session.close()       Server session terminated, resources freed

Stage 1 - Construct: You create a BBRESession instance with your configuration. At this point, no server resources are consumed. The instance is configured but idle. You can call inherited methods like getBalance() or getAccountInfo() to perform pre-flight checks before starting the session.

Stage 2 - Start: Calling start() creates a session on the BBRE server. The server allocates a browser instance, generates a browser profile (fingerprint), and returns a session ID and expiration timestamp. The BBRESession instance stores these values locally. From this point, the session is active and consuming one of your 10 available session slots.

Stage 3 - Work: This is where you perform your actual tasks. You can send HTTP requests through the session using request(), automate browser actions using this.browser methods, submit forms using submitForm(), run multi-step workflows using runSteps(), or check pages using checkPage(). All requests within this stage share the same cookies and browser identity. Cookies received from responses are automatically merged into the session cookie store.

Stage 4 - Close: Calling close() terminates the server-side session, releases the browser instance, and resets the local state (session ID, cookies, profile all set to null). The session slot becomes available for new sessions. If you do not call close(), the session will eventually expire based on the sessionTime configuration, but it is always better to close explicitly.

Basic Lifecycle Example

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

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

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

    await session.browser.navigate("https://example.com/login");
    await session.browser.fill("#email", "[email protected]");
    await session.browser.fill("#password", "securepassword");
    await session.browser.click("#login-button");
    await session.browser.waitForSelector(".dashboard");

    const response = await session.request({
      url: "https://example.com/api/profile",
      method: "GET"
    });

    console.log("Profile data:", response.data);
  } finally {
    await session.close();
    console.log("Session closed");
  }
}

runWorkflow();

Lifecycle with Pre-flight Checks

Before starting a session, it is good practice to verify that your account has sufficient balance and available session slots. This prevents wasting time on session creation that would fail due to account limitations.

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

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

async function safeWorkflow() {
  const { account, statistics } = await session.getAccountInfo();

  if (account.status !== "active") {
    console.log("Account is not active:", account.status);
    return;
  }

  if (account.balance < 5) {
    console.log("Low balance:", account.balance);
    return;
  }

  if (statistics.activeSessions >= 10) {
    console.log("No available session slots");
    return;
  }

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

    await session.browser.navigate("https://example.com");
    const title = await session.browser.getTitle();
    console.log("Page title:", title);
  } finally {
    await session.close();
  }
}

safeWorkflow();

Session State Management

The BBRESession class maintains several pieces of state that are updated throughout the session lifecycle. Understanding what state is tracked and how it changes helps you write predictable session-based code.

State Properties

Property Type Initial Value Description
sessionId string | null null The unique identifier for the active session. Set when start() completes, reset to null when close() is called. Access via getSessionId().
sessionExpiresAt string | null null ISO 8601 timestamp indicating when the session will expire. Set by start(), reset by close().
sessionProfile object | null null The browser fingerprint profile generated by the BBRE engine. Contains userAgent, platform, screen dimensions, timezone, locale, and hardware details. Updated after start() and after browser actions. Access via getProfile().
sessionCookies object {} Key-value store of cookies accumulated during the session. Automatically updated when responses include cookies. Manage via getCookies(), setCookie(), deleteCookie(), clearCookies().
browserSpeed string "instant" Current browser action speed. Sent with every browser action as the _speed parameter. Change via setBrowserSpeed(), read via getBrowserSpeed().
force boolean false Error handling mode flag. When false, browser action errors auto-close the session. When true, errors return result objects without closing.
browser BrowserAPI new BrowserAPI(this) The BrowserAPI instance for browser automation. Created during construction and bound to this session instance.

Cookie Persistence

One of the key features of BBRESession is automatic cookie persistence. When you send a request through the session's request() method, any cookies returned in the response are automatically merged into the sessionCookies store. On the next request, these cookies are automatically included along with any cookies you have set manually. This means you do not need to manually extract and re-send cookies between requests, which is essential for workflows that involve authentication, CSRF tokens, or any server-side state tracked via cookies.

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

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

async function cookieExample() {
  try {
    await session.start();

    const loginResponse = await session.request({
      url: "https://example.com/api/login",
      method: "POST",
      body: { username: "user", password: "pass" }
    });

    console.log("Cookies after login:", session.getCookies());

    const dashboardResponse = await session.request({
      url: "https://example.com/api/dashboard",
      method: "GET"
    });

    console.log("Dashboard data:", dashboardResponse.data);

    session.setCookie("custom_preference", "dark_mode");
    console.log("All cookies:", session.getCookies());
  } finally {
    await session.close();
  }
}

cookieExample();

Profile Tracking

When a session starts, the BBRE engine generates a browser fingerprint profile for the session's browser instance. This profile contains detailed information about the simulated browser environment, including the user agent string, platform, screen resolution, device memory, CPU cores, GPU renderer, timezone, locale, and more. The profile is stored locally in sessionProfile and updated whenever a browser action returns new profile data. You can access the full profile with getProfile() or get a simplified summary with getProfileSummary().

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

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

async function profileExample() {
  try {
    await session.start();

    console.log("Has profile:", session.hasProfile());

    const profile = session.getProfile();
    console.log("User Agent:", profile.userAgent);
    console.log("Platform:", profile.platform);
    console.log("Timezone:", profile.timezone);

    const summary = session.getProfileSummary();
    console.log("Screen:", summary.screen);
    console.log("Memory:", summary.deviceMemory);
    console.log("CPU Cores:", summary.cpuCores);
    console.log("GPU:", summary.gpu);
    console.log("Country:", summary.country);
    console.log("Mobile:", summary.mobile);
  } finally {
    await session.close();
  }
}

profileExample();

BrowserAPI Instance

Every BBRESession instance has a browser property that holds a BrowserAPI instance. This object is created during construction and provides a clean, method-based interface for browser automation actions. Instead of manually constructing browser action payloads and sending them through the API, you call methods like session.browser.navigate(), session.browser.click(), and session.browser.fill(). Each method internally calls the session's _browserAction() method, which sends the action to the BBRE API with the current session ID and browser speed setting.

The BrowserAPI class groups its methods into several categories: navigation (navigate, goto, reload, back, forward), interaction (click, fill, type, select, checkbox, fillForm, clear), page querying (getHtml, getText, getTitle, getUrl, find, findByText), waiting (wait, waitForElement, waitForText, waitForSelector), scrolling (scroll, scrollDown, scrollUp, scrollToTop, scrollToBottom), cookies (getCookies, setCookie, clearCookies), and advanced operations (screenshot, execute, evaluate).

Browser actions require the session to be in "adaptive" mode. If you created the session with "passive" mode, browser actions will fail because passive mode does not allocate a real browser instance on the server.

Using the BrowserAPI

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

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

async function browserExample() {
  try {
    await session.start();

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

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

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

    await session.browser.click("a.products-link");
    await session.browser.waitForSelector(".product-list");

    const html = await session.browser.getHtml();
    console.log("Page HTML length:", html.length);

    await session.browser.scrollDown(500);
    await session.browser.wait(1);

    const text = await session.browser.getText(".product-count");
    console.log("Product count:", text);
  } finally {
    await session.close();
  }
}

browserExample();

BrowserAPI Method Categories

Category Methods Description
Navigation navigate(), goto(), reload(), back(), forward() Control page navigation. goto() is an alias for navigate().
Interaction click(), fill(), type(), select(), checkbox(), fillForm(), clear() Interact with page elements. fill() sets a value instantly, type() simulates keystroke-by-keystroke input.
Page Query getHtml(), getText(), getTitle(), getUrl(), find(), findByText() Extract information from the current page.
Waiting wait(), waitForElement(), waitForText(), waitForSelector() Wait for conditions to be met before proceeding.
Scrolling scroll(), scrollDown(), scrollUp(), scrollToTop(), scrollToBottom() Control page scroll position.
Cookies getCookies(), setCookie(), clearCookies() Manage browser-level cookies (separate from session-level cookie store).
Advanced screenshot(), execute(), evaluate() Take screenshots, execute JavaScript in the browser context. evaluate() is an alias for execute().

Force Mode vs Default Error Handling

The force configuration parameter controls how the session responds to browser action errors. This is one of the most important behavioral differences you need to understand when working with BBRESession, because it determines whether a single failed browser action can terminate your entire session.

Default Behavior (force: false)

When force is false (the default), the session operates in a "fail-safe" mode. If any browser action fails (for example, a click on a selector that does not exist, a navigation timeout, or a JavaScript execution error), the session automatically closes itself and throws an error with the prefix [SESSION_STOPPED]. This behavior protects you from continuing to work with a session that may be in an inconsistent state after an error.

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

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

async function defaultErrorHandling() {
  try {
    await session.start();
    await session.browser.navigate("https://example.com");

    await session.browser.click("#nonexistent-button");
  } catch (error) {
    console.log(error.message);
    console.log("Session active:", session.isActive());
  }
}

defaultErrorHandling();

Force Mode (force: true)

When force is true, browser action errors do not automatically close the session. Instead, the method returns a result object with success: false and an error property describing what went wrong. The session remains active, and you can continue sending actions or requests. This mode is useful for workflows where you expect some actions to fail (for example, checking whether an element exists by trying to click it) or where you want to implement your own error recovery logic.

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

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

async function forceErrorHandling() {
  try {
    await session.start();
    await session.browser.navigate("https://example.com");

    const result = await session.browser.click("#optional-popup-close");

    if (result.success === false) {
      console.log("Popup not found, continuing:", result.error);
    }

    console.log("Session still active:", session.isActive());

    await session.browser.click("#main-content-link");
    await session.browser.waitForSelector(".content-loaded");

    console.log("Workflow completed successfully");
  } finally {
    await session.close();
  }
}

forceErrorHandling();

Choosing Between Default and Force Mode

Scenario Recommended Mode Reason
Critical workflows where every step must succeed force: false Automatic session cleanup prevents working with corrupted state.
Exploratory scraping with optional elements force: true Some elements may not exist on every page. You want to continue regardless.
Form submission with known structure force: false If a form field is missing, the submission would be incomplete anyway.
Multi-site scraping with varying layouts force: true Different sites have different structures. Graceful degradation is preferred.
Automated testing and monitoring force: true You want to collect error information without losing the session context.
Login and authenticated workflows force: false A failed login step means all subsequent steps would fail anyway.

Browser Speed Settings

The browserSpeed setting controls the timing of browser actions within the session. Every browser action sent through this.browser or through the high-level methods (submitForm(), runSteps(), interact(), checkPage()) includes the current browser speed as a _speed parameter. The BBRE engine uses this parameter to add appropriate delays between actions, making the browser behavior appear more or less human-like depending on the setting.

Speed Options

Speed Behavior Use Case
"instant" No artificial delays between actions. Actions execute as fast as the browser allows. Development, testing, and workflows where speed is the priority and detection risk is low.
"fast" Minimal delays between actions. Faster than human but with small pauses to avoid triggering basic timing-based detection. Production scraping on sites with moderate anti-bot measures. Good balance between speed and stealth.
"human" Realistic human-like delays between actions. Simulates natural browsing patterns with variable pauses between clicks, typing, and navigation. High-security sites with advanced behavioral analysis. When you need maximum stealth and are willing to trade speed for it.

Changing Speed During a Session

You can change the browser speed at any point during a session using the setBrowserSpeed() method. This is useful when different parts of your workflow have different speed requirements. For example, you might use "instant" for initial navigation and "human" for form filling on a sensitive page.

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

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

async function variableSpeedWorkflow() {
  try {
    await session.start();

    console.log("Current speed:", session.getBrowserSpeed());
    await session.browser.navigate("https://example.com");

    session.setBrowserSpeed("human");
    console.log("Speed changed to:", session.getBrowserSpeed());

    await session.browser.fill("#search-input", "product name");
    await session.browser.click("#search-button");
    await session.browser.waitForSelector(".search-results");

    session.setBrowserSpeed("instant");
    const html = await session.browser.getHtml();
    console.log("Results HTML length:", html.length);
  } finally {
    await session.close();
  }
}

variableSpeedWorkflow();

Session Time Configuration

The sessionTime parameter controls how long the server-side session remains active before it expires due to inactivity. The value is specified in minutes and must be between 0.5 and 5. If you provide a value outside this range, it is automatically clamped: values below 0.5 become 0.5, and values above 5 become 5. The default is 2 minutes.

When start() is called, the session time is converted from minutes to seconds and passed as the timeout parameter to the createSession() API call. The server uses this value to set the session expiration. If no requests or browser actions are sent within this time window, the session expires automatically and the browser instance is released.

You can also override the session time for a specific start() call by passing a timeout option (in seconds, capped at 300) directly to the start() method. This override takes precedence over the sessionTime constructor parameter for that particular session.

Session Time Examples

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

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

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

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

async function sessionTimeDemo() {
  try {
    await quickSession.start();
    console.log("Quick session (30 seconds) started");
    await quickSession.browser.navigate("https://example.com");
    const title = await quickSession.browser.getTitle();
    console.log("Title:", title);
  } finally {
    await quickSession.close();
  }
}

sessionTimeDemo();

Overriding Session Time in start()

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

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

async function overrideTimeout() {
  try {
    await session.start({ timeout: 60 });
    console.log("Session started with 60-second timeout override");

    await session.browser.navigate("https://example.com");
    console.log("Page loaded");
  } finally {
    await session.close();
  }
}

overrideTimeout();

Complete Method Reference

The following tables list all methods available on a BBRESession instance, grouped by category. This includes both methods defined directly on BBRESession and methods inherited from BBREClient. Each method links to its detailed documentation page where you can find full parameter descriptions, return types, and usage examples.

Session Lifecycle Methods

Method Returns Description
start(options?) Promise<object> Creates a session on the server, stores the session ID, expiration, and profile locally. Returns the session data object.
close() Promise<void> Terminates the server-side session and resets all local state. Safe to call even if no session is active.
status() Promise<object> Queries the server for the current session status. Throws if no session is active.

Session Request Methods

Method Returns Description
request(options) Promise<object> Sends an HTTP request within the session. Automatically includes session cookies and updates the cookie store with response cookies.
submitForm(url, options?) Promise<object> Navigates to a URL, fills form fields, selects dropdowns, checks checkboxes, and clicks a submit button.
runSteps(url, steps, options?) Promise<object> Navigates to a URL and executes an array of step objects in sequence.
interact(url, options?) Promise<object> Navigates to a URL and executes an array of actions from the options object.
checkPage(url, options?) Promise<object> Navigates to a URL and checks for the presence of specific text or elements.

Browser Configuration Methods

Method Returns Description
setBrowserSpeed(speed) void Sets the browser action speed. Accepts "instant", "fast", or "human".
getBrowserSpeed() string Returns the current browser speed setting.

Profile Methods

Method Returns Description
getProfile() object | null Returns the full browser profile object, or null if no profile is available.
hasProfile() boolean Returns true if a browser profile is available.
getProfileSummary() object | null Returns a simplified profile summary with key fields like userAgent, platform, screen, timezone, and country.

Session Info Methods

Method Returns Description
getSessionId() string | null Returns the current session ID, or null if no session is active.
isActive() boolean Returns true if a session is currently active.

Cookie Management Methods

Method Returns Description
getCookies() object Returns a copy of the current session cookie store as a key-value object.
setCookie(name, value) void Sets a cookie in the session cookie store.
deleteCookie(name) void Removes a specific cookie from the session cookie store by name.
clearCookies() void Removes all cookies from the session cookie store.

BrowserAPI Methods (via session.browser)

Method Category Description
browser.navigate(url, options?) Navigation Navigates to the specified URL.
browser.goto(url, options?) Navigation Alias for navigate().
browser.reload(options?) Navigation Reloads the current page.
browser.back() Navigation Navigates back in browser history.
browser.forward() Navigation Navigates forward in browser history.
browser.click(selector, options?) Interaction Clicks an element matching the CSS selector.
browser.fill(selector, value) Interaction Sets the value of an input element instantly.
browser.type(selector, value, options?) Interaction Types text into an input element keystroke by keystroke.
browser.select(selector, value) Interaction Selects an option in a dropdown element.
browser.checkbox(text) Interaction Clicks a checkbox identified by its label text.
browser.fillForm(fields, options?) Interaction Fills multiple form fields at once.
browser.clear(selector) Interaction Clears the value of an input element.
browser.getHtml() Query Returns the full HTML content of the current page.
browser.getText(selector) Query Returns the text content of an element.
browser.getTitle() Query Returns the title of the current page.
browser.getUrl() Query Returns the URL of the current page.
browser.find(selector) Query Finds elements matching a CSS selector.
browser.findByText(text, options?) Query Finds elements containing the specified text.
browser.wait(seconds) Wait Pauses execution for the specified number of seconds.
browser.waitForElement(options) Wait Waits for an element to appear on the page.
browser.waitForText(text, timeout?) Wait Waits for specific text to appear on the page.
browser.waitForSelector(selector, timeout?) Wait Waits for an element matching the CSS selector to appear.
browser.scroll(options?) Scroll Scrolls the page with custom options.
browser.scrollDown(pixels?) Scroll Scrolls down by the specified number of pixels (default: 500).
browser.scrollUp(pixels?) Scroll Scrolls up by the specified number of pixels (default: 500).
browser.scrollToTop() Scroll Scrolls to the top of the page.
browser.scrollToBottom() Scroll Scrolls to the bottom of the page.
browser.getCookies() Cookies Returns browser-level cookies from the browser context.
browser.setCookie(name, value, options?) Cookies Sets a cookie in the browser context.
browser.clearCookies() Cookies Clears all cookies from the browser context.
browser.screenshot(options?) Advanced Takes a screenshot of the current page.
browser.execute(script) Advanced Executes JavaScript code in the browser context.
browser.evaluate(script) Advanced Alias for execute().

Quick Start Example

The following example demonstrates a complete session workflow: creating a session, navigating to a website, filling out a login form, extracting data from the authenticated page, and closing the session. This covers the most common use case for BBRESession and shows how the different components work together.

Complete Login and Data Extraction Workflow

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

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

async function loginAndExtractData() {
  try {
    const balance = await session.getBalance();
    console.log("Account balance:", balance);

    if (balance < 2) {
      console.log("Insufficient balance for session workflow");
      return;
    }

    const sessionData = await session.start();
    console.log("Session ID:", sessionData.sessionId);
    console.log("Expires at:", sessionData.expiresAt);

    await session.browser.navigate("https://example.com/login");
    console.log("Login page loaded");

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

    await session.browser.waitForSelector(".dashboard-container");
    console.log("Login successful, dashboard loaded");

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

    const response = await session.request({
      url: "https://example.com/api/user/orders",
      method: "GET"
    });

    console.log("Orders count:", response.data.length);
    console.log("Cookies accumulated:", Object.keys(session.getCookies()).length);

    if (session.hasProfile()) {
      const summary = session.getProfileSummary();
      console.log("Browser profile:", summary.userAgent);
      console.log("Screen:", summary.screen);
    }
  } catch (error) {
    console.log("Workflow error:", error.message);
  } finally {
    await session.close();
    console.log("Session closed, active:", session.isActive());
  }
}

loginAndExtractData();

Form Submission with submitForm()

For simpler form submission workflows, you can use the submitForm() method which handles navigation, field filling, and submission in a single call.

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

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

async function submitContactForm() {
  try {
    await session.start();

    const result = await session.submitForm("https://example.com/contact", {
      fields: {
        "#name": "John Smith",
        "#email": "[email protected]",
        "#message": "Hello, I have a question about your product."
      },
      select: {
        "#department": "sales"
      },
      checkbox: "I agree to the terms",
      submit: "#send-button",
      waitFor: "Thank you for your message"
    });

    console.log("Form submitted successfully:", result.success);
    console.log("Final URL:", result.finalUrl);
    console.log("Steps completed:", result.stepsCompleted);
  } finally {
    await session.close();
  }
}

submitContactForm();

Multi-Step Workflow with runSteps()

For complex workflows that involve multiple pages and interactions, use runSteps() to define a sequence of actions that execute in order.

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

const session = new BBRESession({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive",
  browserSpeed: "fast",
  force: true,
  sessionTime: 4
});

async function multiStepWorkflow() {
  try {
    await session.start();

    const result = await session.runSteps("https://example.com/search", [
      { fill: { "#search-box": "laptop computers" } },
      { click: "#search-button" },
      { waitFor: ".search-results" },
      { scrollDown: 500 },
      { wait: 1 },
      { click: ".product-card:first-child a" },
      { waitFor: ".product-details" }
    ]);

    console.log("Steps completed:", result.stepsCompleted, "/", result.totalSteps);
    console.log("Final URL:", result.finalUrl);

    const productTitle = await session.browser.getText("h1.product-title");
    const productPrice = await session.browser.getText(".product-price");
    console.log("Product:", productTitle);
    console.log("Price:", productPrice);
  } finally {
    await session.close();
  }
}

multiStepWorkflow();

BBRESession vs BBREClient

Choosing between BBRESession and BBREClient depends on your specific use case. The following comparison table highlights the key differences between the two classes to help you make the right choice.

Feature BBREClient BBRESession
State Management Stateless. Each request is independent. Stateful. Maintains cookies, profile, and session ID across requests.
Cookie Handling Manual. You must extract and re-send cookies yourself. Automatic. Cookies are persisted and merged between requests.
Browser Automation Not available directly. You must use the Browser Action API endpoint manually. Built-in via this.browser (BrowserAPI instance) with methods like navigate, click, fill, etc.
Server Resources No persistent resources. Each request allocates and releases resources independently. Allocates a dedicated browser instance on the server for the session duration.
Session Limit No session limit. Can make unlimited concurrent requests. Maximum 10 active sessions per account.
Browser Profile Profile returned per-request but not tracked. Profile tracked and updated throughout the session. Accessible via getProfile().
High-Level Methods Not available. submitForm(), runSteps(), interact(), checkPage() for complex workflows.
Error Handling Standard try-catch. Errors do not affect other requests. Configurable via force. Default: errors auto-close session. Force mode: errors return result objects.
Browser Speed Not applicable. Configurable via browserSpeed: "instant", "fast", or "human".
Use Case Simple data fetching, API calls, one-off page scraping, batch requests. Login workflows, multi-page navigation, form filling, authenticated scraping, browser automation.
Setup Complexity Minimal. Create instance and start making requests. Requires start() before use and close() after. Must manage session lifecycle.
Cost Pay per request. Pay per request within the session. Session creation itself may have additional cost.

When to Use BBREClient

Use BBREClient when you need to make independent HTTP requests that do not require shared state. Common scenarios include fetching public web pages, calling APIs that do not require session cookies, running batch requests against multiple different URLs, checking website availability, and any workflow where each request is self-contained. BBREClient is simpler to use because it does not require session lifecycle management, and it does not consume session slots on your account.

When to Use BBRESession

Use BBRESession when your workflow requires maintaining state between requests or when you need browser automation capabilities. Common scenarios include logging into websites and performing authenticated actions, filling out multi-step forms that span multiple pages, navigating through paginated content while preserving session cookies, interacting with JavaScript-heavy applications that require a real browser, and any workflow where the target website needs to see a consistent visitor identity across multiple interactions.

Using Both Together

Since BBRESession extends BBREClient, you can use a single BBRESession instance for both session-based and standalone operations. However, if your application has distinct workflows that require different configurations, you might want to create separate instances.

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

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

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

async function combinedWorkflow() {
  const publicData = await client.get("https://example.com/api/public/products");
  console.log("Public products:", publicData.data.length);

  try {
    await session.start();
    await session.browser.navigate("https://example.com/login");
    await session.browser.fill("#email", "[email protected]");
    await session.browser.fill("#password", "password123");
    await session.browser.click("#login-btn");
    await session.browser.waitForSelector(".dashboard");

    const privateData = await session.request({
      url: "https://example.com/api/private/orders",
      method: "GET"
    });
    console.log("Private orders:", privateData.data.length);
  } finally {
    await session.close();
  }
}

combinedWorkflow();

Best Practices

Always Close Sessions in a finally Block

Wrap your session workflow in a try-finally block to ensure the session is closed even if an error occurs. Unclosed sessions continue consuming one of your 10 available session slots until they expire. If your application crashes or throws an unhandled error without closing the session, you may find yourself unable to create new sessions until the abandoned ones expire. The close() method is safe to call even if no session is active, so there is no risk of errors in the finally block.

Use Adaptive Mode for Browser Automation

If your workflow involves any browser actions (navigation, clicking, form filling, screenshots, JavaScript execution), you must set the mode to "adaptive" in the constructor. Passive mode does not allocate a real browser instance on the server, so all this.browser methods and high-level methods like submitForm() will fail. If you only need to send HTTP requests within a session (for cookie persistence without browser automation), passive mode works fine.

Perform Pre-flight Checks Before Starting Sessions

Before calling start(), use the inherited getAccountInfo() method to verify that your account is active, has sufficient balance, and has available session slots (fewer than 10 active sessions). This prevents wasted API calls and provides clear error messages when preconditions are not met. Since BBRESession inherits from BBREClient, you can call account methods on the same instance before starting the session.

Match Browser Speed to Your Target Site's Security Level

Use "instant" speed for development and testing, "fast" for production scraping on sites with moderate protection, and "human" for high-security sites with behavioral analysis. You can change the speed mid-session using setBrowserSpeed(), so consider using faster speeds for non-sensitive actions (like initial navigation) and slower speeds for sensitive actions (like form submission on protected pages).

Set Session Time Based on Your Workflow Duration

Choose a sessionTime that matches the expected duration of your workflow. Short workflows (quick page check, single form submission) should use 0.5 to 1 minute. Standard workflows (login, navigate, extract data) should use 2 to 3 minutes. Complex workflows (multi-page navigation, large form filling, extensive scraping) should use 4 to 5 minutes. Setting the session time too high wastes server resources, while setting it too low risks session expiration mid-workflow.

Use Force Mode for Exploratory and Resilient Workflows

Enable force: true when your workflow needs to handle optional elements, varying page layouts, or when you want to implement custom error recovery. In force mode, browser action errors return result objects instead of closing the session, giving you the opportunity to inspect the error and decide how to proceed. Keep the default force: false for critical workflows where any error should stop execution immediately.

Common Issues

"Session not started. Call start() first." Error

Symptom: Calling request(), browser methods, or high-level methods throws an error saying the session is not started.
Cause: You are trying to use session-specific methods before calling start(). Creating a BBRESession instance does not automatically start a session on the server. The constructor only configures the local instance.
Solution: Always call await session.start() before using any session-specific methods. The start() method creates the server-side session and stores the session ID locally.

Browser Actions Fail with Passive Mode

Symptom: Calling session.browser.navigate() or other browser methods fails with an error about browser actions not being available.
Cause: The session was created with mode: "passive" (the default). Passive mode does not allocate a real browser instance on the server, so browser automation actions cannot be executed.
Solution: Set mode: "adaptive" in the constructor configuration. Adaptive mode allocates a full browser instance that supports all browser automation actions.

SESSION_LIMIT_REACHED When Creating New Sessions

Symptom: Calling start() throws a SESSION_LIMIT_REACHED error.
Cause: Your account already has 10 active sessions, which is the maximum allowed. This can happen if previous sessions were not properly closed, or if multiple parts of your application are creating sessions concurrently.
Solution: Close unused sessions before creating new ones. Use getAccountInfo() to check the statistics.activeSessions count before calling start(). Ensure all session workflows use try-finally blocks to guarantee cleanup. If sessions were abandoned, wait for them to expire based on their session time configuration.

[SESSION_STOPPED] Error Closes Session Unexpectedly

Symptom: A browser action throws an error prefixed with [SESSION_STOPPED] and the session becomes inactive.
Cause: With the default force: false setting, any browser action error automatically closes the session to prevent working with inconsistent state. This is the intended behavior for fail-safe operation.
Solution: If you need the session to survive browser action errors, set force: true in the constructor. In force mode, errors return result objects with success: false instead of closing the session. Alternatively, add more robust selectors and wait conditions to prevent the browser actions from failing in the first place.

Session Expires Before Workflow Completes

Symptom: Session requests or browser actions start failing with session expired errors partway through your workflow.
Cause: The sessionTime was set too low for the duration of your workflow. The default is 2 minutes, which may not be enough for complex multi-step workflows, especially when using "human" browser speed which adds significant delays between actions.
Solution: Increase the sessionTime in the constructor to match your workflow duration. The maximum is 5 minutes. If your workflow takes longer than 5 minutes, consider breaking it into multiple shorter sessions or using "fast" or "instant" browser speed to reduce action delays.