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

Create Session

The POST /session/create endpoint creates a new BBRE (Browser-Backed Request Engine) session that maintains browser state across multiple requests. Sessions are the foundation of stateful web interaction through the BBRE system. When you create a session, the BBRE engine allocates a dedicated browser context with its own cookie jar, fingerprint identity, and optional proxy configuration. Every subsequent request made through that session shares the same browser state, which means cookies set by one request are automatically available to the next, login sessions persist across multiple page navigations, and the target website sees a consistent browser identity throughout the entire interaction. This is fundamentally different from the stateless POST /request/create and POST /request/execute endpoints, where each request starts with a clean browser context and no memory of previous interactions. Sessions are essential when you need to authenticate with a website and then access protected pages, navigate through multi-step workflows like checkout processes or form wizards, maintain CSRF tokens across requests, accumulate cookies that unlock content progressively, or interact with single-page applications that rely on client-side state. Each session has a configurable timeout that determines how long the browser context stays alive. Once a session expires or is explicitly closed, the browser context is destroyed and all associated state is lost. You can have up to 10 active sessions per account at any given time. This page covers every parameter accepted by the session creation endpoint, explains the session lifecycle in detail, provides working code examples in JavaScript, Python, and cURL, documents the SDK integration, and offers best practices for effective session management.

Understanding Sessions

A BBRE session is a persistent browser context that preserves cookies, fingerprint identity, and browsing state across multiple requests. Think of it as opening a browser tab that stays open while you navigate between pages. Without sessions, every request to the BBRE API starts fresh with no memory of previous interactions. With sessions, you can log into a website with one request and then access authenticated pages with subsequent requests, just like a real user would. Sessions support both passive and adaptive modes. In passive mode, the session maintains HTTP-level state (cookies, headers). In adaptive mode, the session additionally maintains a full browser instance with JavaScript state, DOM state, and navigation history. Use the POST /session/request endpoint to send requests within a session, and the POST /session/close endpoint to explicitly close a session when you are done.

Endpoint

POST https://bbre-solver-api.mydisct.com/session/create

Authentication

All requests to the BBRE API require authentication via an API key. You must include your API key in the HTTP headers of every request, including session creation. The API accepts the key through either the x-api-key header or the apikey header. Both header names are supported and functionally identical. If no API key is provided, the API returns a 401 error with the API_KEY_REQUIRED error code. If the provided key is invalid or belongs to a suspended or inactive account, the API returns a 403 error with the appropriate error code (INVALID_API_KEY, ACCOUNT_SUSPENDED, or ACCOUNT_INACTIVE).

Header Type Required Description
x-api-key string required Your BBRE API key. You can find this in your MyDisct Solver dashboard.
Content-Type string required Must be set to application/json for all requests.

Request Body Parameters

The request body must be a JSON object containing the configuration for your new session. All parameters are optional. If you send an empty JSON object {}, the session is created with default settings: passive mode, medium sensibility, auto-generated fingerprint, no proxy, and a 120-second timeout. The following table describes every parameter accepted by this endpoint, including the data type, default value, validation rules, and detailed usage information. Understanding these parameters is critical for configuring sessions that match your specific use case, whether that is simple cookie persistence for API interactions or full browser automation for complex web workflows.

Parameter Type Required Default Description
mode string optional "passive" The session operating mode. "passive" mode creates a lightweight session that maintains cookies and headers across requests using a browser-like HTTP client without launching a full browser instance. This is faster and uses fewer resources, making it ideal for API interactions, cookie-based authentication, and server-rendered websites. "adaptive" mode creates a session backed by a full browser instance with JavaScript execution, DOM rendering, and support for browser actions like navigate, click, fill, and screenshot. Use adaptive mode when the target website requires JavaScript rendering, has advanced bot detection that checks browser behavior, or when you need to perform browser automation actions through the Browser Action endpoint. The mode you choose at session creation applies to all requests made within that session and cannot be changed after the session is created.
sensibility string optional "medium" The detection evasion sensitivity level for the session. This setting applies to all requests made within the session. "low" provides basic evasion with faster processing, suitable for sites with minimal bot protection. "medium" balances evasion quality and speed, appropriate for most websites and the recommended starting point. "high" applies maximum evasion techniques including human-like timing delays, realistic mouse movements, and advanced fingerprint consistency checks. High sensibility is ideal for sites with sophisticated anti-bot systems like DataDome, PerimeterX, or Cloudflare Bot Management. Higher sensibility levels result in slower request processing but significantly better success rates on protected sites.
fingerprint object optional {} Custom browser fingerprint configuration for the session. The fingerprint defines the browser identity that the session presents to target websites. You can specify attributes like userAgent (string), platform (string, e.g., "Win32", "MacIntel"), screen (object with width and height), timezone (string, e.g., "America/New_York"), language (string, e.g., "en-US"), and webgl (object with vendor and renderer). Any attributes you do not specify are generated automatically by BBRE to ensure internal consistency. The fingerprint is locked to the session at creation time and remains consistent across all requests, which is important because anti-bot systems track fingerprint consistency across page loads. See the Fingerprint and Profile Guide for detailed information on fingerprint attributes and best practices.
proxy object optional null Proxy server configuration for routing all session requests through a specific proxy. When set, every request made within this session uses the specified proxy. The object must contain host (string, required) and port (number, required). For authenticated proxies, include username (string) and password (string). Using a consistent proxy throughout a session is strongly recommended because switching IP addresses mid-session is a common trigger for bot detection systems. Example: {"host": "proxy.example.com", "port": 8080, "username": "user", "password": "pass"}
timeout number optional 120 Session timeout in seconds. This defines how long the session stays alive after creation. Once the timeout expires, the session status changes to expired and no further requests can be made through it. The validator accepts values between 60 and 3600 seconds (1 to 60 minutes). The controller internally clamps the value to a minimum of 10 and a maximum of 300 seconds. The default timeout is 120 seconds (2 minutes), which is sufficient for most short workflows like logging in and fetching a few pages. For longer workflows such as multi-page form submissions, checkout processes, or extensive data collection, increase the timeout to 300 seconds. Plan your session timeout based on the total time you expect your workflow to take, including network latency and processing time for each request within the session.

Session Lifecycle

Understanding the session lifecycle is essential for building reliable integrations with the BBRE session system. A session goes through a well-defined sequence of states from creation to termination, and knowing how these transitions work helps you design workflows that handle every scenario gracefully.

1. Creation

When you call POST /session/create, the BBRE engine allocates a new browser context with the specified mode, sensibility, fingerprint, and proxy configuration. The session is assigned a unique session ID and its status is set to active. The expiration timestamp is calculated as the current time plus the timeout value in seconds. If session pricing is configured, the session creation cost is deducted from your account balance at this point. The response includes the session ID, status, and expiration timestamp, which you need to store for subsequent requests.

2. Active Usage

While the session is active, you can send requests through it using the POST /session/request endpoint. Each request within the session shares the same browser context, which means cookies set by one request are automatically included in subsequent requests. If the session is in adaptive mode, you can also perform browser actions like navigate, click, fill, and screenshot through the POST /browser/action endpoint. The session tracks the number of requests made and the total amount charged. Cookies received from target websites are automatically merged into the session's cookie jar after each request. If the BBRE engine generates a browser profile during processing, it is stored in the session and returned with subsequent request results.

3. Expiration

Every session has an expiration timestamp set at creation time. When the current time exceeds the expiresAt timestamp, the session is considered expired. Any attempt to use an expired session returns a 400 SESSION_EXPIRED error. The session status is updated to expired when the expiration is detected. Expired sessions cannot be reactivated or extended. You must create a new session to continue your workflow. To avoid unexpected expirations, monitor the expiresAt value returned at creation time and plan your workflow to complete within the timeout window.

4. Explicit Close

You can explicitly close a session at any time using the POST /session/close endpoint. Closing a session immediately releases the browser context and frees up one of your 10 active session slots. The session status changes to closed and no further requests can be made through it. It is a best practice to always close sessions when you are done with them, rather than waiting for them to expire naturally. This ensures you do not hit the active session limit unnecessarily and frees up server resources for other users.

Session State Diagram

The following diagram summarizes the possible session states and transitions:

State Description Transitions To
active Session is created and ready to accept requests. Cookies and browser state are maintained. expired (timeout reached), closed (explicit close)
expired Session timeout has been reached. No further requests are accepted. Browser context is released. Terminal state (no further transitions)
closed Session was explicitly closed by the user. Browser context is released immediately. Terminal state (no further transitions)

Session Limits

Each account is limited to a maximum of 10 active sessions at any given time. This limit exists to ensure fair resource allocation across all users, since each active session consumes server-side resources including memory for the browser context, cookie storage, and in adaptive mode, a dedicated browser instance. The limit applies only to sessions with active status that have not yet expired. Sessions that have been explicitly closed or that have expired do not count toward this limit.

When you attempt to create a session and you already have 10 active sessions, the API returns a 429 error with the SESSION_LIMIT_REACHED error code. The error response includes the current number of active sessions (activeCount) and the maximum allowed (maxAllowed: 10). To resolve this, close one or more existing sessions using the POST /session/close endpoint before creating a new one. You can also check your active sessions using the Account Sessions endpoint to see which sessions are still active and decide which ones to close.

Session Limit Strategy

If your application needs to process more than 10 concurrent workflows, design your system to reuse sessions where possible and close them promptly when finished. Implement a session pool pattern where you maintain a fixed number of sessions and assign incoming workflows to available sessions. This approach maximizes throughput while staying within the 10-session limit. Avoid creating sessions with very long timeouts unless you genuinely need them, as idle sessions still count toward your limit.

Request Examples

The following examples demonstrate how to create BBRE sessions in different programming languages and for different use cases. All examples show complete, working code that you can copy and run directly. Remember to replace YOUR_API_KEY with your actual BBRE API key.

Basic Session Creation

The simplest way to create a session. This uses all default settings: passive mode, medium sensibility, auto-generated fingerprint, no proxy, and a 120-second timeout. This is suitable for basic cookie persistence and simple multi-step workflows on sites without aggressive bot detection.

JavaScript
const axios = require("axios");

const API_BASE = "https://bbre-solver-api.mydisct.com";
const API_KEY = "YOUR_API_KEY";

async function createBasicSession() {
  const response = await axios.post(
    API_BASE + "/session/create",
    {},
    {
      headers: {
        "Content-Type": "application/json",
        "x-api-key": API_KEY
      }
    }
  );

  const session = response.data.session;
  console.log("Session ID:", session.id);
  console.log("Status:", session.status);
  console.log("Expires At:", new Date(session.expiresAt).toISOString());

  return session;
}

createBasicSession();
Python
import requests
from datetime import datetime

API_BASE = "https://bbre-solver-api.mydisct.com"
API_KEY = "YOUR_API_KEY"

headers = {
    "Content-Type": "application/json",
    "x-api-key": API_KEY
}

response = requests.post(
    API_BASE + "/session/create",
    headers=headers,
    json={}
)

data = response.json()
session = data["session"]
print("Session ID:", session["id"])
print("Status:", session["status"])
expires = datetime.fromtimestamp(session["expiresAt"] / 1000)
print("Expires At:", expires.isoformat())
Bash
curl -X POST https://bbre-solver-api.mydisct.com/session/create \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{}'

Adaptive Session with Custom Fingerprint

This example creates an adaptive mode session with high sensibility and a custom browser fingerprint. Adaptive sessions are required when you need to perform browser actions like clicking buttons, filling forms, or taking screenshots. The custom fingerprint ensures the session presents a consistent and realistic browser identity to the target website, which is critical for bypassing advanced bot detection systems that track fingerprint consistency across page loads.

JavaScript
const axios = require("axios");

const API_BASE = "https://bbre-solver-api.mydisct.com";
const API_KEY = "YOUR_API_KEY";

async function createAdaptiveSession() {
  const response = await axios.post(
    API_BASE + "/session/create",
    {
      mode: "adaptive",
      sensibility: "high",
      timeout: 300,
      fingerprint: {
        platform: "Win32",
        timezone: "America/New_York",
        language: "en-US",
        screen: { width: 1920, height: 1080 }
      }
    },
    {
      headers: {
        "Content-Type": "application/json",
        "x-api-key": API_KEY
      }
    }
  );

  const session = response.data.session;
  console.log("Session ID:", session.id);
  console.log("Status:", session.status);
  console.log("Expires At:", new Date(session.expiresAt).toISOString());

  return session;
}

createAdaptiveSession();
Python
import requests

API_BASE = "https://bbre-solver-api.mydisct.com"
API_KEY = "YOUR_API_KEY"

headers = {
    "Content-Type": "application/json",
    "x-api-key": API_KEY
}

response = requests.post(
    API_BASE + "/session/create",
    headers=headers,
    json={
        "mode": "adaptive",
        "sensibility": "high",
        "timeout": 300,
        "fingerprint": {
            "platform": "Win32",
            "timezone": "America/New_York",
            "language": "en-US",
            "screen": {"width": 1920, "height": 1080}
        }
    }
)

data = response.json()
session = data["session"]
print("Session ID:", session["id"])
print("Status:", session["status"])
Bash
curl -X POST https://bbre-solver-api.mydisct.com/session/create \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "mode": "adaptive",
    "sensibility": "high",
    "timeout": 300,
    "fingerprint": {
      "platform": "Win32",
      "timezone": "America/New_York",
      "language": "en-US",
      "screen": {"width": 1920, "height": 1080}
    }
  }'

Session with Proxy Configuration

This example creates a session with a dedicated proxy server. Using a proxy with sessions is highly recommended for production use cases because it ensures all requests within the session originate from the same IP address. Anti-bot systems commonly flag sessions where the IP address changes between requests, so maintaining IP consistency through a proxy significantly improves success rates on protected websites.

JavaScript
const axios = require("axios");

const API_BASE = "https://bbre-solver-api.mydisct.com";
const API_KEY = "YOUR_API_KEY";

async function createProxySession() {
  const response = await axios.post(
    API_BASE + "/session/create",
    {
      mode: "passive",
      sensibility: "medium",
      timeout: 300,
      proxy: {
        host: "us-residential.proxy.com",
        port: 8080,
        username: "proxyuser",
        password: "proxypass"
      },
      fingerprint: {
        timezone: "America/Chicago",
        language: "en-US"
      }
    },
    {
      headers: {
        "Content-Type": "application/json",
        "x-api-key": API_KEY
      }
    }
  );

  const session = response.data.session;
  console.log("Session ID:", session.id);
  console.log("Expires At:", new Date(session.expiresAt).toISOString());

  return session;
}

createProxySession();
Python
import requests

API_BASE = "https://bbre-solver-api.mydisct.com"
API_KEY = "YOUR_API_KEY"

headers = {
    "Content-Type": "application/json",
    "x-api-key": API_KEY
}

response = requests.post(
    API_BASE + "/session/create",
    headers=headers,
    json={
        "mode": "passive",
        "sensibility": "medium",
        "timeout": 300,
        "proxy": {
            "host": "us-residential.proxy.com",
            "port": 8080,
            "username": "proxyuser",
            "password": "proxypass"
        },
        "fingerprint": {
            "timezone": "America/Chicago",
            "language": "en-US"
        }
    }
)

data = response.json()
session = data["session"]
print("Session ID:", session["id"])
print("Expires At:", session["expiresAt"])
Bash
curl -X POST https://bbre-solver-api.mydisct.com/session/create \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "mode": "passive",
    "sensibility": "medium",
    "timeout": 300,
    "proxy": {
      "host": "us-residential.proxy.com",
      "port": 8080,
      "username": "proxyuser",
      "password": "proxypass"
    },
    "fingerprint": {
      "timezone": "America/Chicago",
      "language": "en-US"
    }
  }'

Response Format

The session creation endpoint returns a JSON response indicating whether the session was created successfully. On success, the response includes the session ID, status, and expiration timestamp. On failure, the response includes an error code, a human-readable message, and additional details where applicable.

Success Response (200)

A successful session creation returns the following structure. The session.id is the unique identifier you will use for all subsequent operations on this session. The expiresAt value is a Unix timestamp in milliseconds representing when the session will automatically expire. The profile field is null at creation time and gets populated after the first request is processed through the session.

JSON
{
  "success": true,
  "service": "MyDisct Solver BBRE",
  "session": {
    "id": "session_abc123def456",
    "status": "active",
    "expiresAt": 1706789012345
  },
  "profile": null
}
Field Type Description
success boolean Always true for successful responses.
service string Always "MyDisct Solver BBRE". Identifies the service that processed the request.
session.id string The unique session identifier. Use this ID in all subsequent session operations including /session/request, /session/close, /session/status, and /browser/action.
session.status string The current session status. Always "active" for newly created sessions.
session.expiresAt number Unix timestamp in milliseconds when the session will expire. Calculated as the creation time plus the timeout value in seconds multiplied by 1000.
profile object / null The browser profile generated by the BBRE engine. Always null at session creation. Gets populated after the first request is processed through the session.

Error Response Examples

When session creation fails, the API returns an error response with the appropriate HTTP status code, error code, and a descriptive message. Some error responses include additional details to help you diagnose and resolve the issue.

429 - Session Limit Reached

JSON
{
  "success": false,
  "service": "MyDisct Solver BBRE",
  "error": {
    "code": "SESSION_LIMIT_REACHED",
    "message": "Maximum active sessions limit reached. Please close an existing session before creating a new one.",
    "details": {
      "activeCount": 10,
      "maxAllowed": 10
    }
  }
}

402 - Insufficient Balance

JSON
{
  "success": false,
  "service": "MyDisct Solver BBRE",
  "error": {
    "code": "INSUFFICIENT_BALANCE",
    "message": "Insufficient balance. Please add funds to your account.",
    "details": {
      "required": 0.05,
      "current_balance": 0.02
    }
  }
}

400 - Invalid Mode

JSON
{
  "success": false,
  "service": "MyDisct Solver BBRE",
  "error": {
    "code": "INVALID_MODE",
    "message": "Invalid mode. Valid modes: passive, adaptive.",
    "details": {
      "details": "Invalid mode: aggressive",
      "allowedModes": ["passive", "adaptive"],
      "hint": "Use \\"passive\\" for simple HTTP requests or \\"adaptive\\" for browser automation",
      "warning": "Browser actions (navigate, click, etc.) only work with \\"adaptive\\" mode"
    }
  }
}

Error Codes

The following table lists all error codes that can be returned by the session creation endpoint, along with their HTTP status codes, descriptions, and recommended solutions. Implementing proper error handling for each of these codes ensures your application can recover gracefully from any failure scenario.

HTTP Status Error Code Description Solution
400 INVALID_MODE The provided mode value is not valid. Only "passive" and "adaptive" are accepted. Check the mode parameter value. Use exactly "passive" or "adaptive" (case-sensitive, lowercase).
400 INVALID_SENSIBILITY The provided sensibility value is not valid. Only "low", "medium", and "high" are accepted. Check the sensibility parameter value. Use exactly "low", "medium", or "high" (case-sensitive, lowercase).
400 INVALID_REQUEST The timeout value is outside the allowed range (60-3600 seconds) or the proxy configuration is missing required fields. For timeout errors, provide a value between 60 and 3600 seconds. For proxy errors, ensure both host and port fields are included in the proxy object.
401 API_KEY_REQUIRED No API key was provided in the request headers. Include your API key in the x-api-key or apikey header.
402 INSUFFICIENT_BALANCE Your account balance is too low to cover the session creation cost. Add funds to your account through the MyDisct Solver dashboard. The error response includes the required amount and your current balance.
403 INVALID_API_KEY The provided API key is not valid or does not exist. Verify your API key in the MyDisct Solver dashboard. Ensure you are copying the complete key without extra spaces.
403 ACCOUNT_SUSPENDED Your account has been suspended. Contact MyDisct Solver support for information about your account suspension.
403 ACCOUNT_INACTIVE Your account is inactive. Activate your account through the MyDisct Solver dashboard or contact support.
429 SESSION_LIMIT_REACHED You have reached the maximum of 10 active sessions. No more sessions can be created until existing ones are closed or expire. Close one or more active sessions using POST /session/close. Check your active sessions with POST /account/sessions to identify sessions that can be closed.
500 SERVICE_ERROR An internal server error occurred while processing the session creation request. Retry the request after a short delay (2-5 seconds). If the error persists, contact support.
503 SERVICE_UNAVAILABLE The BBRE engine is temporarily unavailable. This can happen during maintenance or when the internal processing service is unreachable. Wait 10-30 seconds and retry. If the error persists for more than a few minutes, check the MyDisct Solver status page or contact support.

Complete Session Workflow Example

The following example demonstrates a complete session workflow: creating a session, making multiple requests within the session to maintain state, checking the session status, and closing the session when finished. This pattern is the foundation for any multi-step interaction with a website through the BBRE API.

JavaScript
const axios = require("axios");

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

async function completeSessionWorkflow() {
  const createResponse = await axios.post(
    API_BASE + "/session/create",
    {
      mode: "passive",
      sensibility: "medium",
      timeout: 300
    },
    { headers: authHeaders }
  );

  const sessionId = createResponse.data.session.id;
  console.log("Session created:", sessionId);

  const loginResponse = await axios.post(
    API_BASE + "/session/request",
    {
      sessionId: sessionId,
      url: "https://example.com/api/login",
      method: "POST",
      body: {
        username: "myuser",
        password: "mypassword"
      }
    },
    { headers: authHeaders }
  );
  console.log("Login status:", loginResponse.data.data.task.result.statusCode);

  const dashboardResponse = await axios.post(
    API_BASE + "/session/request",
    {
      sessionId: sessionId,
      url: "https://example.com/dashboard",
      method: "GET"
    },
    { headers: authHeaders }
  );
  console.log("Dashboard status:", dashboardResponse.data.data.task.result.statusCode);

  const statusResponse = await axios.post(
    API_BASE + "/session/status",
    { sessionId: sessionId },
    { headers: authHeaders }
  );
  console.log("Request count:", statusResponse.data.session.requestCount);

  await axios.post(
    API_BASE + "/session/close",
    { sessionId: sessionId },
    { headers: authHeaders }
  );
  console.log("Session closed");
}

completeSessionWorkflow();
Python
import requests

API_BASE = "https://bbre-solver-api.mydisct.com"
API_KEY = "YOUR_API_KEY"

headers = {
    "Content-Type": "application/json",
    "x-api-key": API_KEY
}

create_response = requests.post(
    API_BASE + "/session/create",
    headers=headers,
    json={
        "mode": "passive",
        "sensibility": "medium",
        "timeout": 300
    }
)

session_id = create_response.json()["session"]["id"]
print("Session created:", session_id)

login_response = requests.post(
    API_BASE + "/session/request",
    headers=headers,
    json={
        "sessionId": session_id,
        "url": "https://example.com/api/login",
        "method": "POST",
        "body": {
            "username": "myuser",
            "password": "mypassword"
        }
    }
)
print("Login status:", login_response.json()["data"]["task"]["result"]["statusCode"])

dashboard_response = requests.post(
    API_BASE + "/session/request",
    headers=headers,
    json={
        "sessionId": session_id,
        "url": "https://example.com/dashboard",
        "method": "GET"
    }
)
print("Dashboard status:", dashboard_response.json()["data"]["task"]["result"]["statusCode"])

status_response = requests.post(
    API_BASE + "/session/status",
    headers=headers,
    json={"sessionId": session_id}
)
print("Request count:", status_response.json()["session"]["requestCount"])

requests.post(
    API_BASE + "/session/close",
    headers=headers,
    json={"sessionId": session_id}
)
print("Session closed")

Node.js SDK Usage

The mydisctsolver-bbre Node.js SDK provides a convenient createSession() method on the BBREClient class that wraps the POST /session/create endpoint. The SDK handles authentication headers, request formatting, and response parsing automatically. It also merges your default fingerprint and proxy settings with the session-specific options, so you do not need to repeat common configuration for every session.

Basic SDK Session Creation

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

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

async function createSessionWithSDK() {
  const result = await client.createSession({
    timeout: 300
  });

  console.log("Session ID:", result.sessionId);
  console.log("Expires At:", new Date(result.expiresAt).toISOString());
  console.log("Profile:", result.profile);

  return result;
}

createSessionWithSDK();

Adaptive Session with SDK

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

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

async function createAdaptiveSessionSDK() {
  const result = await client.createSession({
    mode: "adaptive",
    sensibility: "high",
    timeout: 300,
    fingerprint: {
      platform: "Win32",
      timezone: "America/New_York",
      language: "en-US",
      screen: { width: 1920, height: 1080 }
    },
    proxy: {
      host: "us-proxy.example.com",
      port: 8080,
      username: "proxyuser",
      password: "proxypass"
    }
  });

  console.log("Session ID:", result.sessionId);
  console.log("Expires At:", new Date(result.expiresAt).toISOString());

  return result;
}

createAdaptiveSessionSDK();

SDK Session with Default Settings

When you configure default fingerprint and proxy settings on the BBREClient instance, those defaults are automatically merged into every session you create. This eliminates the need to repeat common configuration and ensures consistency across all your sessions.

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

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

client.setDefaultFingerprint({
  platform: "Win32",
  timezone: "America/New_York",
  language: "en-US"
});

client.setDefaultProxy({
  host: "us-proxy.example.com",
  port: 8080,
  username: "proxyuser",
  password: "proxypass"
});

async function createSessionWithDefaults() {
  const result = await client.createSession({
    timeout: 300
  });

  console.log("Session ID:", result.sessionId);
  return result;
}

createSessionWithDefaults();

The SDK createSession() method returns an object with success, sessionId, expiresAt, and profile fields. If the session creation fails, the method throws an error with the error message from the API response. For more details on the SDK, see the Node.js SDK Overview and the Session Management documentation.

Pricing and Balance

Session creation has an associated cost that is determined by the BBRE_SESSION pricing tier configured in the system. When you create a session, the system checks the current price for the BBRE_SESSION captcha type and verifies that your account balance is sufficient to cover the cost. If pricing is configured and your balance is insufficient, the API returns a 402 INSUFFICIENT_BALANCE error that includes the required amount and your current balance. The balance deduction happens after the session is successfully created in the BBRE engine. Note that the session creation cost is separate from the per-request cost that may be charged for individual requests made within the session. You can check your current balance at any time using the Account Balance endpoint.

Best Practices

Always Close Sessions When Finished

Do not rely on session timeout expiration to clean up your sessions. Always explicitly close sessions using the POST /session/close endpoint when your workflow is complete. This immediately frees up one of your 10 active session slots and releases server-side resources. Implement a try/finally pattern in your code to ensure sessions are closed even when errors occur during your workflow. Leaving sessions open unnecessarily can cause you to hit the session limit when you need to create new ones.

Use Passive Mode Unless You Need Browser Actions

Passive mode sessions are significantly lighter on resources and faster to process than adaptive mode sessions. If your workflow only needs cookie persistence and consistent headers across requests (which covers most authentication and multi-step API workflows), use passive mode. Reserve adaptive mode for scenarios where you genuinely need full browser rendering, JavaScript execution, or browser automation actions like clicking buttons and filling forms. You can always create a new adaptive session later if you discover that passive mode is insufficient for a particular target website.

Match Fingerprint and Proxy to Your Target Geography

When creating sessions for websites that serve region-specific content or have geo-based bot detection, ensure your fingerprint timezone, language, and proxy location are geographically consistent. For example, if you are using a US-based proxy, set the timezone to a US timezone like America/New_York and the language to en-US. Anti-bot systems commonly flag sessions where the IP geolocation does not match the browser timezone or language settings. This consistency check is one of the easiest ways to improve your success rate on protected websites.

Set Timeout Based on Your Workflow Duration

Calculate the total time your workflow needs and set the session timeout accordingly. If your workflow involves logging in (5 seconds), navigating to 3 pages (15 seconds each), and extracting data (10 seconds), the total is approximately 60 seconds. Add a generous buffer for network variability and set the timeout to 120-180 seconds. Avoid setting extremely long timeouts (like 3600 seconds) unless you genuinely need them, because idle sessions still count toward your 10-session limit. For most workflows, 120-300 seconds is the optimal range.

Implement Session Pooling for High-Volume Workflows

If your application processes many concurrent workflows, implement a session pool pattern. Maintain a fixed number of sessions (up to 10) and assign incoming workflows to available sessions. When a workflow completes, return the session to the pool for reuse instead of closing it and creating a new one. This reduces the overhead of session creation and teardown, and ensures you never exceed the session limit. Reusing sessions also has the benefit of maintaining accumulated cookies and browser state, which can improve success rates on sites that track returning visitors.

Common Issues

Issue 1: SESSION_LIMIT_REACHED When Creating Sessions

Problem

You receive a 429 SESSION_LIMIT_REACHED error when trying to create a new session, even though you believe you should have available slots. The error response shows activeCount: 10 and maxAllowed: 10.

Solution: This happens when you have 10 sessions that are still in active status and have not yet expired. The most common cause is forgetting to close sessions after your workflow completes. Sessions remain active until they either expire naturally or are explicitly closed. First, use the POST /account/sessions endpoint to list your active sessions and identify which ones can be closed. Then close unnecessary sessions using POST /session/close. To prevent this issue in the future, always implement session cleanup in your code using try/finally blocks, and avoid creating sessions with unnecessarily long timeouts.

Issue 2: Session Expires Before Workflow Completes

Problem

Your session expires mid-workflow, causing subsequent requests to fail with 400 SESSION_EXPIRED. This typically happens when the default 120-second timeout is too short for your multi-step workflow.

Solution: Increase the timeout parameter when creating the session. Calculate the total expected duration of your workflow including all requests, processing time, and network latency, then add a 50-100% buffer. For example, if your workflow takes approximately 90 seconds, set the timeout to 180-240 seconds. The maximum allowed timeout through the validator is 3600 seconds (1 hour), though the controller clamps the effective value to a maximum of 300 seconds. For workflows that genuinely need more than 300 seconds, consider breaking them into multiple shorter sessions where each session handles a portion of the workflow.

Issue 3: Timeout Validation Error When Sending Values Below 60

Problem

You receive a 400 INVALID_REQUEST error when setting the timeout to a value less than 60 seconds, with the message "Session timeout must be between 60 and 3600 seconds."

Solution: The session creation endpoint has a minimum timeout of 60 seconds enforced by the request validator. Unlike the request endpoints where timeouts can be as low as 1 second, sessions require a minimum of 60 seconds because they are designed for multi-step workflows that inherently take longer. If you need a very short-lived interaction, consider using the stateless POST /request/execute endpoint instead of creating a session. Sessions are most effective when your workflow involves multiple sequential requests that need to share state.