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

Session Configuration and Utility Methods

The BBRESession class exposes a rich set of configuration and utility methods that give you fine-grained control over browser speed, session state inspection, browser profile analysis, and cookie management. These methods operate on the local session instance and do not make API calls to the BBRE server, which means they execute instantly and consume zero credits. The setBrowserSpeed() method lets you switch between three speed modes during a session to balance performance against detection risk. The profile methods (getProfile(), hasProfile(), getProfileSummary()) provide access to the browser fingerprint profile that the BBRE engine assigned to your session, including user agent, platform, screen resolution, device memory, CPU cores, GPU renderer, timezone, locale, and country information. The session state methods (getSessionId(), isActive()) let you check whether a session is currently active and retrieve its identifier for logging or debugging purposes. The cookie management methods (getCookies(), setCookie(), deleteCookie(), clearCookies()) provide full control over the session cookie jar, allowing you to read, write, delete, and clear cookies that persist across requests within the session. This page documents every configuration and utility method with complete signatures, parameter tables, return types, practical code examples, best practices, common issues, and links to related documentation.

About Configuration and Utility Methods

All methods documented on this page are local operations that read from or write to the BBRESession instance properties. They do not send any HTTP requests to the BBRE API server and do not consume any credits. The browser speed setting affects how the BBRE engine times its interactions with target websites during subsequent requests. The profile data becomes available after the session is started and the BBRE engine assigns a browser fingerprint. Cookie data accumulates as you make requests through the session and can be manually modified using the cookie management methods.

session.setBrowserSpeed(speed)

The setBrowserSpeed() method changes the browser interaction speed for the current session. The speed setting controls how quickly the BBRE engine performs actions like typing, clicking, scrolling, and navigating between pages. A faster speed completes operations more quickly but may appear less human-like to sophisticated bot detection systems. A slower speed mimics natural human behavior more closely, reducing the chance of detection at the cost of longer execution times. You can call this method at any point during a session to switch speeds dynamically based on the target website or the type of operation you are performing. The method validates the input and throws an error if you pass a value that is not one of the three accepted speed strings.

Method Signature

JavaScript
session.setBrowserSpeed(speed);

Parameters

The setBrowserSpeed() method accepts a single string parameter that must be one of the three predefined speed values. Passing any other value causes the method to throw an Error with a descriptive message.

Parameter Type Required Description
speed string Required The browser interaction speed. Must be one of: "instant", "fast", or "human". Any other value throws an error.

Return Type

The method does not return a value. It updates the internal browserSpeed property of the session instance. If the provided speed is invalid, the method throws an Error instead of silently ignoring the input.

Speed Comparison

The following table compares the three available browser speed settings, their characteristics, and the scenarios where each speed is most appropriate. Choosing the right speed for your use case is important because it directly affects both performance and detection risk.

Speed Behavior Performance Detection Risk Best For
"instant" No artificial delays between actions. Operations execute as fast as the browser engine allows. Fastest Highest Internal tools, testing environments, APIs without bot detection, high-volume data extraction from permissive targets.
"fast" Short randomized delays between actions. Faster than human but with some timing variation. Moderate Medium General-purpose scraping, moderate bot detection, balanced workflows where speed matters but some caution is needed.
"human" Realistic human-like delays with natural variation. Typing speed, mouse movement pauses, and reading time are simulated. Slowest Lowest Heavily protected websites, login flows, form submissions on sites with advanced behavioral analysis.

Basic Usage

Set the browser speed when you create a session or change it at any point during the session lifecycle. The speed takes effect on the next request or browser action you perform through the session.

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

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

async function configureSpeed() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

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

  await session.close();
}

configureSpeed();

Changing Speed Mid-Session

One of the most powerful patterns is switching browser speed during a session based on what you are doing. For example, you might use "human" speed for the login flow where behavioral analysis is strictest, then switch to "fast" for data extraction where speed matters more than stealth. This approach gives you the best of both worlds: careful behavior where it counts and fast execution where it is safe.

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

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

async function adaptiveSpeedWorkflow() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  session.setBrowserSpeed("human");
  console.log("Phase 1: Login with human speed");
  await session.request({
    url: "https://example.com/login",
    method: "POST",
    body: { username: "[email protected]", password: "secure_password" }
  });

  session.setBrowserSpeed("fast");
  console.log("Phase 2: Data extraction with fast speed");
  const pages = ["https://example.com/data/1", "https://example.com/data/2", "https://example.com/data/3"];

  for (const pageUrl of pages) {
    const response = await session.request({ url: pageUrl });
    console.log("Fetched:", pageUrl, "Status:", response.statusCode);
  }

  await session.close();
}

adaptiveSpeedWorkflow();

Speed Selection Based on Target

Different websites have different levels of bot detection sophistication. You can maintain a mapping of known targets to their recommended speed settings and apply the appropriate speed before making requests to each target.

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

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

const targetSpeedMap = {
  "api.example.com": "instant",
  "shop.example.com": "fast",
  "bank.example.com": "human"
};

function getSpeedForUrl(url) {
  const hostname = new URL(url).hostname;
  return targetSpeedMap[hostname] || "fast";
}

async function smartSpeedRequest(session, url) {
  const speed = getSpeedForUrl(url);
  session.setBrowserSpeed(speed);
  console.log("Using speed:", speed, "for:", url);

  const response = await session.request({ url });
  return response;
}

async function main() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  const urls = [
    "https://api.example.com/data",
    "https://shop.example.com/products",
    "https://bank.example.com/account"
  ];

  for (const url of urls) {
    const response = await smartSpeedRequest(session, url);
    console.log("Status:", response.statusCode);
  }

  await session.close();
}

main();

Error Handling for Invalid Speed

The setBrowserSpeed() method performs strict validation on the input parameter. If you pass a value that is not "instant", "fast", or "human", the method throws an Error with the message "Invalid speed. Use: instant, fast, or human". This validation prevents silent misconfiguration that could lead to unexpected behavior.

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

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

async function safeSetSpeed(session, speed) {
  try {
    session.setBrowserSpeed(speed);
    console.log("Speed changed to:", speed);
  } catch (error) {
    console.log("Invalid speed value:", speed);
    console.log("Error:", error.message);
    console.log("Valid options: instant, fast, human");
  }
}

async function main() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  await safeSetSpeed(session, "human");
  await safeSetSpeed(session, "turbo");
  await safeSetSpeed(session, "slow");

  console.log("Current speed:", session.getBrowserSpeed());

  await session.close();
}

main();

session.getBrowserSpeed()

The getBrowserSpeed() method returns the current browser speed setting for the session as a string. This is a simple getter that reads the internal browserSpeed property without any side effects. Use this method to verify the current speed before making requests, to log the active speed configuration for debugging, or to implement conditional logic that behaves differently based on the current speed setting.

Method Signature

JavaScript
const speed = session.getBrowserSpeed();

Parameters

The getBrowserSpeed() method does not accept any parameters.

Parameter Type Required Description
This method does not accept any parameters.

Return Type

The method returns a string representing the current browser speed. The returned value is always one of "instant", "fast", or "human".

Return Type Description
string The current browser speed setting. One of "instant", "fast", or "human".

Usage Example

Use getBrowserSpeed() to log the current speed or to make decisions based on the active speed configuration.

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

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

async function logSpeedTransitions() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  console.log("Initial speed:", session.getBrowserSpeed());

  session.setBrowserSpeed("human");
  console.log("After change:", session.getBrowserSpeed());

  session.setBrowserSpeed("instant");
  console.log("After second change:", session.getBrowserSpeed());

  await session.close();
}

logSpeedTransitions();

Conditional Logic Based on Speed

You can use getBrowserSpeed() to implement logic that adjusts timeout values or retry counts based on the current speed. Slower speeds need longer timeouts because the BBRE engine introduces deliberate delays between actions.

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

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

function getTimeoutForSpeed(speed) {
  const timeouts = {
    instant: 30000,
    fast: 60000,
    human: 120000
  };
  return timeouts[speed] || 60000;
}

async function requestWithAdaptiveTimeout(session, url) {
  const speed = session.getBrowserSpeed();
  const timeout = getTimeoutForSpeed(speed);

  console.log("Speed:", speed, "Timeout:", timeout, "ms");

  const response = await session.request({ url, timeout });
  return response;
}

async function main() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  session.setBrowserSpeed("human");
  const response = await requestWithAdaptiveTimeout(session, "https://example.com/data");
  console.log("Status:", response.statusCode);

  await session.close();
}

main();

session.getProfile()

The getProfile() method returns the complete browser fingerprint profile object that the BBRE engine assigned to the current session, or null if no profile has been assigned yet. The profile object contains detailed information about the simulated browser identity, including the user agent string, platform, screen dimensions, device memory, hardware concurrency (CPU cores), WebGL renderer (GPU), timezone, locale, country code, and whether the profile represents a mobile device. This data is populated by the BBRE engine when the session is started and remains constant throughout the session lifetime. The profile is used internally by the BBRE engine to present a consistent browser identity across all requests made through the session, which is critical for avoiding detection by fingerprint-based bot detection systems.

Method Signature

JavaScript
const profile = session.getProfile();

Parameters

The getProfile() method does not accept any parameters.

Parameter Type Required Description
This method does not accept any parameters.

Return Type

The method returns the full profile object or null if no profile has been assigned. The profile object structure depends on the BBRE engine configuration, but typically includes the fields listed below. The returned object is the actual internal reference, so avoid modifying it directly.

Return Type Description
object | null The complete browser fingerprint profile object, or null if no profile has been assigned to the session.

Profile Object Fields

The profile object returned by getProfile() contains the following fields. Not all fields are guaranteed to be present in every profile; some may be null or undefined depending on the BBRE engine configuration and the fingerprint database.

Field Type Description
userAgent string The full user agent string that identifies the simulated browser, operating system, and version. Example: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36.
platform string The operating system platform string. Common values include Win32, MacIntel, Linux x86_64, and Linux armv81 for mobile devices.
screenWidth number The simulated screen width in pixels. Combined with screenHeight to form the screen resolution.
screenHeight number The simulated screen height in pixels. Combined with screenWidth to form the screen resolution.
deviceMemory number The simulated device memory in gigabytes. Common values are 2, 4, 8, and 16. Used by some fingerprinting scripts to identify device class.
hardwareConcurrency number The simulated number of logical CPU cores. Common values range from 2 to 16. Exposed through navigator.hardwareConcurrency in the browser.
webglRenderer string The simulated WebGL renderer string identifying the GPU. Example: ANGLE (Intel, Intel(R) UHD Graphics 630, OpenGL 4.5).
timezone string The IANA timezone identifier for the simulated browser. Example: America/New_York, Europe/London.
locale string The browser locale string. Example: en-US, de-DE, ja-JP. Affects language headers and JavaScript locale APIs.
countryCode string The two-letter ISO 3166-1 country code associated with the profile. Example: us, gb, de.
mobile boolean Whether the profile represents a mobile device. When true, the user agent, screen dimensions, and other properties reflect a mobile browser.

Basic Usage

Retrieve the full profile object after starting a session to inspect the browser identity that the BBRE engine assigned. The profile is available immediately after session.start() completes.

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

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

async function inspectProfile() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  const profile = session.getProfile();

  if (profile) {
    console.log("User Agent:", profile.userAgent);
    console.log("Platform:", profile.platform);
    console.log("Screen:", profile.screenWidth + "x" + profile.screenHeight);
    console.log("Memory:", profile.deviceMemory, "GB");
    console.log("CPU Cores:", profile.hardwareConcurrency);
    console.log("GPU:", profile.webglRenderer);
    console.log("Timezone:", profile.timezone);
    console.log("Locale:", profile.locale);
    console.log("Country:", profile.countryCode);
    console.log("Mobile:", profile.mobile);
  } else {
    console.log("No profile assigned yet");
  }

  await session.close();
}

inspectProfile();

Logging Profile for Debugging

When troubleshooting issues with specific websites, logging the full profile helps you understand what browser identity the BBRE engine is presenting. You can compare this against the target website's requirements to identify potential mismatches.

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

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

async function debugSession() {
  const session = await client.createSession({
    mode: "adaptive",
    sensibility: "high"
  });
  await session.start();

  const profile = session.getProfile();
  console.log("Session ID:", session.getSessionId());
  console.log("Full profile:", JSON.stringify(profile, null, 2));

  const response = await session.request({ url: "https://example.com" });
  console.log("Response status:", response.statusCode);

  if (response.statusCode === 403) {
    console.log("Access denied. Profile details for investigation:");
    console.log("  UA:", profile.userAgent);
    console.log("  Platform:", profile.platform);
    console.log("  Timezone:", profile.timezone);
    console.log("  Country:", profile.countryCode);
  }

  await session.close();
}

debugSession();

session.hasProfile()

The hasProfile() method returns a boolean indicating whether the session has a browser fingerprint profile assigned. This is a convenience method that checks if the internal sessionProfile property is not null. Use this method as a guard before calling getProfile() or getProfileSummary() to avoid working with null values. A session typically receives its profile after session.start() completes successfully. Before starting the session, or if the session was created in passive mode without fingerprint generation, hasProfile() returns false.

Method Signature

JavaScript
const hasIt = session.hasProfile();

Parameters

Parameter Type Required Description
This method does not accept any parameters.

Return Type

Return Type Description
boolean Returns true if the session has a profile assigned, false otherwise.

Guard Pattern

Use hasProfile() as a guard before accessing profile data to write defensive code that handles both cases cleanly.

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

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

async function safeProfileAccess() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  if (session.hasProfile()) {
    const summary = session.getProfileSummary();
    console.log("Browser:", summary.userAgent);
    console.log("Screen:", summary.screen);
    console.log("Location:", summary.country, summary.timezone);
  } else {
    console.log("No profile available for this session");
    console.log("Profile is typically assigned after session.start() completes");
  }

  await session.close();
}

safeProfileAccess();

session.getProfileSummary()

The getProfileSummary() method returns a simplified, human-readable version of the browser fingerprint profile. Unlike getProfile() which returns the raw profile object with all its internal fields, this method extracts the most important fields and formats them into a clean summary object. Screen dimensions are combined into a single "1920x1080" string, device memory is formatted with a "GB" suffix, and the country code is converted to uppercase. This method is designed for logging, debugging, and displaying profile information in user interfaces where you need a quick overview of the session identity without dealing with the full profile structure. If no profile has been assigned to the session, the method returns null.

Method Signature

JavaScript
const summary = session.getProfileSummary();

Parameters

Parameter Type Required Description
This method does not accept any parameters.

Return Type

The method returns a formatted summary object or null if no profile is assigned. Each field in the summary is either a formatted string, a number, a boolean, or null if the corresponding raw profile field is missing.

Return Type Description
object | null A formatted profile summary object, or null if no profile has been assigned to the session.

Summary Fields

The summary object contains the following fields. Each field is derived from the raw profile data and formatted for readability. Fields that are missing from the raw profile are set to null in the summary, except for mobile which defaults to false.

Field Type Source Description
userAgent string | null profile.userAgent The full user agent string, passed through unchanged from the raw profile.
platform string | null profile.platform The operating system platform string, passed through unchanged.
screen string | null profile.screenWidth + profile.screenHeight Screen resolution formatted as "WIDTHxHEIGHT" (e.g., "1920x1080"). Returns null if either dimension is missing.
deviceMemory string | null profile.deviceMemory Device memory formatted with GB suffix (e.g., "8 GB"). Returns null if the raw value is missing.
cpuCores number | null profile.hardwareConcurrency The number of logical CPU cores as a number, passed through unchanged.
gpu string | null profile.webglRenderer The WebGL renderer string identifying the simulated GPU.
timezone string | null profile.timezone The IANA timezone identifier, passed through unchanged.
locale string | null profile.locale The browser locale string, passed through unchanged.
country string | null profile.countryCode The country code converted to uppercase (e.g., "US", "GB"). Returns null if the raw value is missing.
mobile boolean profile.mobile Whether the profile represents a mobile device. Defaults to false if the raw value is missing.

Example Return Value

The following JSON shows a typical return value from getProfileSummary() for a desktop profile with all fields populated.

JSON
{
  "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  "platform": "Win32",
  "screen": "1920x1080",
  "deviceMemory": "8 GB",
  "cpuCores": 8,
  "gpu": "ANGLE (Intel, Intel(R) UHD Graphics 630, OpenGL 4.5)",
  "timezone": "America/New_York",
  "locale": "en-US",
  "country": "US",
  "mobile": false
}

Logging Profile Summary

The summary format is ideal for logging because it presents the most important profile information in a compact, readable format. Use it to create session logs that help you track which browser identity was used for each operation.

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

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

async function logSessionIdentity() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  const summary = session.getProfileSummary();

  if (summary) {
    console.log("=== Session Identity ===");
    console.log("Session ID:", session.getSessionId());
    console.log("Browser:", summary.userAgent);
    console.log("Platform:", summary.platform);
    console.log("Screen:", summary.screen);
    console.log("Memory:", summary.deviceMemory);
    console.log("CPU:", summary.cpuCores, "cores");
    console.log("GPU:", summary.gpu);
    console.log("Timezone:", summary.timezone);
    console.log("Locale:", summary.locale);
    console.log("Country:", summary.country);
    console.log("Mobile:", summary.mobile);
  }

  await session.close();
}

logSessionIdentity();

Using Profile Data for Request Validation

You can use the profile summary to validate that the BBRE engine assigned an appropriate identity for your target. For example, if you are targeting a US-specific website, you might want to verify that the profile has a US country code and an American timezone before proceeding with requests.

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

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

async function validateProfileForTarget(targetCountry) {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  const summary = session.getProfileSummary();

  if (!summary) {
    console.log("No profile available, cannot validate");
    await session.close();
    return null;
  }

  console.log("Assigned country:", summary.country);
  console.log("Target country:", targetCountry);

  if (summary.country !== targetCountry) {
    console.log("Profile country mismatch. Closing session.");
    await session.close();
    return null;
  }

  console.log("Profile matches target country. Proceeding.");
  return session;
}

async function main() {
  const session = await validateProfileForTarget("US");

  if (session) {
    const response = await session.request({ url: "https://us-only-site.example.com" });
    console.log("Status:", response.statusCode);
    await session.close();
  }
}

main();

Comparing Profiles Across Sessions

When running multiple sessions in parallel, you can use getProfileSummary() to verify that each session received a unique browser identity. This is important because using identical profiles across concurrent sessions targeting the same website can trigger detection.

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

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

async function compareSessionProfiles(sessionCount) {
  const sessions = [];

  for (let i = 0; i < sessionCount; i++) {
    const session = await client.createSession({ mode: "adaptive" });
    await session.start();
    sessions.push(session);
  }

  console.log("=== Profile Comparison ===");

  for (let i = 0; i < sessions.length; i++) {
    const summary = sessions[i].getProfileSummary();
    console.log("Session " + (i + 1) + ":");
    console.log("  UA:", summary.userAgent);
    console.log("  Screen:", summary.screen);
    console.log("  Country:", summary.country);
    console.log("  Mobile:", summary.mobile);
  }

  for (const session of sessions) {
    await session.close();
  }
}

compareSessionProfiles(3);

session.getSessionId()

The getSessionId() method returns the unique identifier string for the current session, or null if the session has not been started yet. The session ID is assigned by the BBRE server when you call session.start() and remains constant throughout the session lifetime. This identifier is used internally by the SDK to route requests through the correct session on the server side. You can use it for logging, debugging, correlating requests with server-side logs, or passing to other parts of your application that need to reference the session.

Method Signature

JavaScript
const sessionId = session.getSessionId();

Parameters

Parameter Type Required Description
This method does not accept any parameters.

Return Type

Return Type Description
string | null The unique session identifier string assigned by the BBRE server, or null if the session has not been started.

Usage Example

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

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

async function trackSessionId() {
  const session = await client.createSession({ mode: "adaptive" });

  console.log("Before start:", session.getSessionId());

  await session.start();

  console.log("After start:", session.getSessionId());

  const response = await session.request({ url: "https://example.com" });
  console.log("Request completed in session:", session.getSessionId());
  console.log("Status:", response.statusCode);

  await session.close();

  console.log("After close:", session.getSessionId());
}

trackSessionId();

Session ID for Structured Logging

Include the session ID in your log entries to correlate client-side operations with server-side processing. This is invaluable when debugging issues across multiple concurrent sessions.

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

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

function sessionLog(session, message) {
  const id = session.getSessionId() || "not-started";
  const timestamp = new Date().toISOString();
  console.log("[" + timestamp + "] [session:" + id + "] " + message);
}

async function structuredLoggingExample() {
  const session = await client.createSession({ mode: "adaptive" });
  sessionLog(session, "Session created, starting...");

  await session.start();
  sessionLog(session, "Session started successfully");

  const urls = ["https://example.com/page1", "https://example.com/page2"];

  for (const url of urls) {
    sessionLog(session, "Requesting: " + url);
    const response = await session.request({ url });
    sessionLog(session, "Response: " + response.statusCode);
  }

  await session.close();
  sessionLog(session, "Session closed");
}

structuredLoggingExample();

session.isActive()

The isActive() method returns a boolean indicating whether the session is currently active. Internally, it checks if the sessionId property is truthy using the double-negation pattern (!!this.sessionId). A session is considered active after session.start() assigns a session ID and before session.close() clears it. Use this method to guard against making requests on inactive sessions, to implement cleanup logic that only runs for active sessions, or to build monitoring dashboards that display session status.

Method Signature

JavaScript
const active = session.isActive();

Parameters

Parameter Type Required Description
This method does not accept any parameters.

Return Type

Return Type Description
boolean Returns true if the session has an active session ID, false if the session has not been started or has been closed.

Guard Pattern for Safe Requests

Use isActive() to prevent making requests on sessions that have not been started or have already been closed. This avoids confusing error messages from the BBRE API and makes your code more robust.

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

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

async function safeRequest(session, url) {
  if (!session.isActive()) {
    console.log("Cannot make request: session is not active");
    console.log("Session ID:", session.getSessionId());
    return null;
  }

  const response = await session.request({ url });
  return response;
}

async function main() {
  const session = await client.createSession({ mode: "adaptive" });

  console.log("Before start - active:", session.isActive());

  await session.start();
  console.log("After start - active:", session.isActive());

  const response = await safeRequest(session, "https://example.com");
  if (response) {
    console.log("Status:", response.statusCode);
  }

  await session.close();
  console.log("After close - active:", session.isActive());

  await safeRequest(session, "https://example.com");
}

main();

Cleanup Pattern with isActive()

When your application manages multiple sessions, use isActive() to identify which sessions need to be closed during cleanup. This prevents errors from trying to close sessions that are already inactive.

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

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

async function cleanupSessions(sessions) {
  let closedCount = 0;
  let skippedCount = 0;

  for (const session of sessions) {
    if (session.isActive()) {
      await session.close();
      closedCount++;
      console.log("Closed session:", session.getSessionId());
    } else {
      skippedCount++;
    }
  }

  console.log("Cleanup complete. Closed:", closedCount, "Skipped:", skippedCount);
}

async function main() {
  const sessions = [];

  for (let i = 0; i < 3; i++) {
    const session = await client.createSession({ mode: "adaptive" });
    await session.start();
    sessions.push(session);
  }

  await sessions[1].close();
  console.log("Manually closed session 2");

  await cleanupSessions(sessions);
}

main();

session.getCookies()

The getCookies() method returns a shallow copy of the session cookie jar as a plain JavaScript object. Each key in the returned object is a cookie name, and each value is the corresponding cookie value string. The method creates a copy using the spread operator, so modifying the returned object does not affect the internal session cookies. Cookies accumulate as you make requests through the session and the target server sets cookies in its responses. You can also add cookies manually using setCookie(). This method is useful for inspecting what cookies the session has collected, exporting cookies for use in other tools, debugging authentication flows that depend on specific cookies, and verifying that login operations set the expected session tokens.

Method Signature

JavaScript
const cookies = session.getCookies();

Parameters

Parameter Type Required Description
This method does not accept any parameters.

Return Type

Return Type Description
object A shallow copy of the session cookies as a key-value object. Keys are cookie names (strings), values are cookie values (strings). Returns an empty object if no cookies are set.

Reading Session Cookies

After making requests through a session, use getCookies() to inspect what cookies the target server has set. This is particularly useful after login operations to verify that authentication cookies were received.

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

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

async function inspectCookiesAfterLogin() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  await session.request({
    url: "https://example.com/login",
    method: "POST",
    body: { username: "[email protected]", password: "secure_password" }
  });

  const cookies = session.getCookies();
  console.log("Cookies after login:");

  const cookieNames = Object.keys(cookies);
  for (const name of cookieNames) {
    console.log("  " + name + ":", cookies[name]);
  }

  console.log("Total cookies:", cookieNames.length);

  await session.close();
}

inspectCookiesAfterLogin();

Exporting Cookies

Export session cookies to a JSON string for storage, transfer to another session, or use in external tools. Since getCookies() returns a plain object, it serializes cleanly with JSON.stringify().

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

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

async function exportSessionCookies() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  await session.request({ url: "https://example.com" });

  const cookies = session.getCookies();
  const cookieJson = JSON.stringify(cookies, null, 2);

  fs.writeFileSync("session-cookies.json", cookieJson);
  console.log("Cookies exported to session-cookies.json");
  console.log("Cookie count:", Object.keys(cookies).length);

  await session.close();
}

exportSessionCookies();

Verifying Authentication Cookies

After a login request, verify that the expected authentication cookies are present before proceeding with authenticated operations. This catches login failures early and provides clear diagnostic information.

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

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

async function verifyLoginCookies(session, expectedCookies) {
  const cookies = session.getCookies();
  const missing = [];

  for (const cookieName of expectedCookies) {
    if (!cookies[cookieName]) {
      missing.push(cookieName);
    }
  }

  if (missing.length > 0) {
    console.log("Login verification failed. Missing cookies:", missing.join(", "));
    return false;
  }

  console.log("Login verified. All expected cookies present.");
  return true;
}

async function main() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  await session.request({
    url: "https://example.com/login",
    method: "POST",
    body: { username: "[email protected]", password: "secure_password" }
  });

  const isLoggedIn = await verifyLoginCookies(session, ["session_token", "csrf_token"]);

  if (isLoggedIn) {
    const response = await session.request({ url: "https://example.com/dashboard" });
    console.log("Dashboard status:", response.statusCode);
  }

  await session.close();
}

main();

session.clearCookies()

The clearCookies() method removes all cookies from the session cookie jar by replacing the internal cookie object with an empty object. After calling this method, subsequent requests through the session will not include any cookies, effectively resetting the session to an unauthenticated state from the cookie perspective. This method is useful for simulating a fresh browser state within an existing session, testing how a target website handles requests without cookies, clearing accumulated cookies before starting a new authentication flow, and resetting the cookie jar when switching between different user accounts within the same session.

Method Signature

JavaScript
session.clearCookies();

Parameters

Parameter Type Required Description
This method does not accept any parameters.

Return Type

The method does not return a value. It replaces the internal cookie jar with an empty object.

Resetting Session State

Clear all cookies to reset the session to an unauthenticated state. This is useful when you want to test the full login flow again without creating a new session.

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

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

async function resetAndRelogin() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  await session.request({
    url: "https://example.com/login",
    method: "POST",
    body: { username: "[email protected]", password: "password1" }
  });

  console.log("Cookies after first login:", Object.keys(session.getCookies()).length);

  const dashboardResponse = await session.request({ url: "https://example.com/dashboard" });
  console.log("Dashboard as user1:", dashboardResponse.statusCode);

  session.clearCookies();
  console.log("Cookies after clear:", Object.keys(session.getCookies()).length);

  await session.request({
    url: "https://example.com/login",
    method: "POST",
    body: { username: "[email protected]", password: "password2" }
  });

  console.log("Cookies after second login:", Object.keys(session.getCookies()).length);

  const dashboardResponse2 = await session.request({ url: "https://example.com/dashboard" });
  console.log("Dashboard as user2:", dashboardResponse2.statusCode);

  await session.close();
}

resetAndRelogin();

Cookie Lifecycle Management

The following example demonstrates a complete cookie lifecycle within a single session: accumulating cookies from requests, inspecting them, selectively removing some, and finally clearing all cookies.

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

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

async function cookieLifecycleDemo() {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  console.log("Step 1: Initial cookies");
  console.log("  Count:", Object.keys(session.getCookies()).length);

  session.setCookie("consent", "accepted");
  session.setCookie("language", "en");
  console.log("Step 2: After manual cookies");
  console.log("  Count:", Object.keys(session.getCookies()).length);
  console.log("  Cookies:", session.getCookies());

  await session.request({ url: "https://example.com" });
  console.log("Step 3: After first request");
  console.log("  Count:", Object.keys(session.getCookies()).length);

  session.deleteCookie("language");
  console.log("Step 4: After deleting 'language'");
  console.log("  Count:", Object.keys(session.getCookies()).length);

  session.clearCookies();
  console.log("Step 5: After clearing all cookies");
  console.log("  Count:", Object.keys(session.getCookies()).length);

  await session.close();
}

cookieLifecycleDemo();

Complete Configuration Workflow

The following examples demonstrate how to combine multiple configuration and utility methods in realistic workflows. These patterns show how browser speed, profile inspection, session state checking, and cookie management work together in production scenarios.

Authenticated Scraping with Full Configuration

This example demonstrates a complete workflow that configures browser speed for different phases, inspects the assigned profile, manages cookies for authentication, and uses session state checks throughout the process.

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

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

async function authenticatedScraping() {
  const session = await client.createSession({
    mode: "adaptive",
    sensibility: "high"
  });
  await session.start();

  if (!session.isActive()) {
    console.log("Failed to start session");
    return;
  }

  console.log("Session started:", session.getSessionId());

  if (session.hasProfile()) {
    const summary = session.getProfileSummary();
    console.log("Identity:", summary.userAgent);
    console.log("Location:", summary.country, summary.timezone);
    console.log("Device:", summary.screen, summary.deviceMemory);
  }

  session.setBrowserSpeed("human");
  console.log("Phase 1: Login (speed:", session.getBrowserSpeed() + ")");

  session.setCookie("cookie_consent", "all");

  await session.request({
    url: "https://example.com/login",
    method: "POST",
    body: { username: "[email protected]", password: "secure_password" }
  });

  const cookies = session.getCookies();
  if (!cookies["session_token"]) {
    console.log("Login failed: no session token received");
    await session.close();
    return;
  }

  console.log("Login successful. Token received.");

  session.setBrowserSpeed("fast");
  console.log("Phase 2: Data extraction (speed:", session.getBrowserSpeed() + ")");

  const results = [];
  const pages = [1, 2, 3, 4, 5];

  for (const page of pages) {
    if (!session.isActive()) {
      console.log("Session became inactive during extraction");
      break;
    }

    const response = await session.request({
      url: "https://example.com/api/products?page=" + page
    });

    results.push({ page, status: response.statusCode });
    console.log("Page", page, "status:", response.statusCode);
  }

  console.log("Extracted", results.length, "pages");
  console.log("Final cookie count:", Object.keys(session.getCookies()).length);

  await session.close();
}

authenticatedScraping();

Multi-Account Session Reuse

This pattern demonstrates how to use cookie management to switch between multiple user accounts within a single session, avoiding the overhead of creating and destroying sessions for each account.

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

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

async function multiAccountWorkflow(accounts) {
  const session = await client.createSession({ mode: "adaptive" });
  await session.start();

  session.setBrowserSpeed("fast");
  const allResults = {};

  for (const account of accounts) {
    session.clearCookies();
    console.log("Switched to account:", account.username);
    console.log("Cookie count after clear:", Object.keys(session.getCookies()).length);

    session.setBrowserSpeed("human");
    await session.request({
      url: "https://example.com/login",
      method: "POST",
      body: { username: account.username, password: account.password }
    });

    session.setBrowserSpeed("fast");
    const response = await session.request({ url: "https://example.com/profile" });

    allResults[account.username] = {
      status: response.statusCode,
      cookies: Object.keys(session.getCookies()).length
    };

    console.log("Result for", account.username + ":", response.statusCode);
  }

  await session.close();
  return allResults;
}

const accounts = [
  { username: "[email protected]", password: "alice_pass" },
  { username: "[email protected]", password: "bob_pass" },
  { username: "[email protected]", password: "charlie_pass" }
];

multiAccountWorkflow(accounts);

Session Diagnostics Report

Build a comprehensive diagnostics report that captures all session configuration and state information. This is useful for debugging and for including in error reports when something goes wrong.

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

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

function generateDiagnostics(session) {
  const report = {
    sessionId: session.getSessionId(),
    isActive: session.isActive(),
    browserSpeed: session.getBrowserSpeed(),
    hasProfile: session.hasProfile(),
    profileSummary: session.getProfileSummary(),
    cookieCount: Object.keys(session.getCookies()).length,
    cookieNames: Object.keys(session.getCookies()),
    timestamp: new Date().toISOString()
  };

  return report;
}

async function runWithDiagnostics() {
  const session = await client.createSession({
    mode: "adaptive",
    sensibility: "medium"
  });
  await session.start();

  session.setBrowserSpeed("fast");

  await session.request({ url: "https://example.com" });

  const diagnostics = generateDiagnostics(session);
  console.log("=== Session Diagnostics ===");
  console.log(JSON.stringify(diagnostics, null, 2));

  await session.close();
}

runWithDiagnostics();

Best Practices

Use Human Speed for Login Flows, Fast Speed for Data Extraction

Login pages and form submissions are the most heavily monitored parts of most websites. Set the browser speed to "human" before performing login operations to minimize detection risk. Once authenticated, switch to "fast" for data extraction where speed matters more. This two-phase approach gives you the best balance between stealth and performance. Reserve "instant" for internal APIs and testing environments where bot detection is not a concern.

Always Check hasProfile() Before Accessing Profile Data

The profile is assigned by the BBRE engine after the session starts. If you call getProfile() or getProfileSummary() before starting the session, both methods return null. Use hasProfile() as a guard to write defensive code that handles the no-profile case gracefully. This is especially important in generic utility functions that might be called at any point in the session lifecycle.

Use getProfileSummary() for Logging, getProfile() for Programmatic Access

The getProfileSummary() method formats profile data into human-readable strings (screen resolution as "1920x1080", memory as "8 GB", country in uppercase). Use it for logging, debugging output, and display purposes. When you need the raw numeric values for calculations or comparisons (such as checking if screenWidth is above a threshold), use getProfile() instead to access the unformatted data directly.

Verify Authentication Cookies After Login

After performing a login request, call getCookies() and check for the presence of expected authentication cookies (such as session tokens or JWT cookies) before proceeding with authenticated operations. This catches silent login failures early. If the expected cookies are missing, the login likely failed even if the HTTP status code was 200, because some websites return a 200 response with an error message in the body rather than a proper HTTP error status.

Use clearCookies() When Switching User Accounts

When you need to switch between different user accounts within the same session, always call clearCookies() before logging in as the new user. This prevents cookie conflicts where authentication tokens from the previous user interfere with the new login. Without clearing cookies first, the target website might see conflicting session tokens and reject the login or return data for the wrong user.

Check isActive() Before Making Requests in Long-Running Workflows

In long-running workflows that make many sequential requests, periodically check isActive() to verify that the session is still alive. Sessions can expire due to server-side timeouts or be closed by external factors. Checking the active state before each request (or each batch of requests) prevents confusing errors and lets you implement graceful recovery logic such as creating a new session and resuming from where you left off.

Adjust Timeouts Based on Browser Speed

When using "human" speed, the BBRE engine introduces significant delays between actions to simulate natural behavior. This means operations take considerably longer than with "instant" or "fast" speed. Adjust your request timeouts accordingly: use shorter timeouts (30 seconds) for "instant", moderate timeouts (60 seconds) for "fast", and longer timeouts (120 seconds or more) for "human" speed. Use getBrowserSpeed() to dynamically calculate the appropriate timeout value.

Common Issues

setBrowserSpeed() Throws Error for Invalid Speed Values

Symptom: Calling setBrowserSpeed() throws an Error with the message "Invalid speed. Use: instant, fast, or human".
Cause: You passed a string that is not one of the three accepted values. Common mistakes include using uppercase letters ("Fast" instead of "fast"), using alternative names ("slow", "normal", "turbo"), or passing a number instead of a string.
Solution: Use exactly one of the three lowercase strings: "instant", "fast", or "human". The validation is case-sensitive and does not accept any variations. Wrap the call in a try-catch block if the speed value comes from user input or configuration files.

getProfile() and getProfileSummary() Return null Before Session Start

Symptom: Calling getProfile() or getProfileSummary() returns null even though you created the session.
Cause: The browser fingerprint profile is assigned by the BBRE engine when the session is started on the server side. If you call these methods before session.start() completes, the profile has not been assigned yet. Creating a session with client.createSession() does not automatically start it.
Solution: Always call await session.start() before accessing profile data. Use hasProfile() as a guard to check whether the profile is available before accessing it.

getCookies() Returns Empty Object After clearCookies()

Symptom: After calling clearCookies(), all cookies are gone including authentication cookies, and subsequent requests fail with 401 or 403 errors.
Cause: The clearCookies() method removes all cookies without exception, including authentication tokens, session cookies, and CSRF tokens. There is no selective clear operation built into the method.
Solution: If you need to keep certain cookies while removing others, save the important cookies before clearing, then restore them afterwards. Alternatively, use deleteCookie() to remove specific cookies individually while preserving the ones you need.

Modifying the Object Returned by getCookies() Does Not Affect Session Cookies

Symptom: You modify the object returned by getCookies() (adding, changing, or deleting properties), but the session cookies remain unchanged.
Cause: The getCookies() method returns a shallow copy of the internal cookie jar using the spread operator. Changes to the returned object do not propagate back to the session.
Solution: Use setCookie() to add or update cookies, deleteCookie() to remove specific cookies, and clearCookies() to remove all cookies. These methods modify the internal cookie jar directly.

isActive() Returns false After Session Expiration

Symptom: isActive() returns false even though you never called session.close().
Cause: Sessions have a server-side expiration time. When a session expires, the server clears the session data. If the SDK detects that the session is no longer valid (for example, after a failed request that returns a session expiration error), it may clear the local session ID, causing isActive() to return false.
Solution: For long-running workflows, periodically check isActive() and implement recovery logic that creates a new session when the current one expires. You can also call session.status() to get the server-side session status including the expiration time.

Profile Country Does Not Match Expected Region

Symptom: The getProfileSummary().country field shows a country code that does not match your target region, causing geo-restricted content to be blocked.
Cause: The BBRE engine assigns profiles from its fingerprint database, and the country associated with the profile may not match your proxy location or target region. The profile country is part of the browser fingerprint and affects timezone, locale, and other browser properties.
Solution: Use the fingerprint option when creating the session to request a profile from a specific region. If the assigned profile does not match your requirements, close the session and create a new one. You can also use a proxy from the target country to ensure IP-based geolocation matches the profile country.