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

Account Sessions

The POST /account/sessions endpoint returns a paginated list of all sessions associated with your BBRE (Browser-Backed Request Engine) account. Sessions are the foundation of stateful browsing in the BBRE system: each session maintains its own browser context, cookies, fingerprint profile, and request history across multiple API calls. This endpoint lets you retrieve a complete inventory of your sessions, including those that are currently active, sessions that have been explicitly closed, and sessions that expired due to inactivity. Understanding your session landscape is critical for effective resource management because the BBRE API enforces a hard limit of 10 concurrent active sessions per account. If you hit this limit, any attempt to create a new session will fail with a SESSION_LIMIT_REACHED error until you close one or more existing sessions. The sessions endpoint supports filtering by status, so you can quickly identify which sessions are still active and consuming your session quota, which sessions have been closed and are no longer usable, and which sessions expired automatically. Combined with the limit and offset pagination parameters, you can efficiently navigate through your entire session history regardless of how many sessions your account has created over time. Each session record in the response includes the session identifier, operating mode, sensibility level, current status, the number of requests made within that session, the total amount charged for all operations in that session, the expiration timestamp, the creation timestamp, and the closure timestamp if applicable. Results are always returned in reverse chronological order (newest first), so the most recently created sessions appear at the top of the list. Whether you are building a session management dashboard, implementing automated cleanup of stale sessions, monitoring session utilization across your application, or debugging why a particular session is no longer responding, this endpoint provides the data you need. This page covers the endpoint definition, authentication requirements, all available request parameters, the complete response format with field descriptions, filtering examples for each session status, session management patterns, working code examples in JavaScript, Python, and cURL, error handling, and best practices for session lifecycle management in production systems.

Session Listing

Your account can have a maximum of 10 active sessions at any given time. When you reach this limit, you must close an existing session before creating a new one. The sessions endpoint is the fastest way to see how many active sessions you currently have and to identify sessions that can be safely closed. Sessions that are no longer needed should be closed explicitly using the POST /session/close endpoint rather than waiting for them to expire, because expired sessions still count against your limit until the system processes the expiration. The endpoint supports filtering by status (active, closed, expired) and pagination through limit and offset parameters. Results are always ordered by creation time, newest first.

Endpoint

The account sessions endpoint accepts only POST requests. Even though this is a read operation that retrieves data without modifying anything, it uses POST because the endpoint accepts an optional JSON request body containing filter and pagination parameters. If you do not need any filters, you can send a POST request with an empty body or an empty JSON object, and the endpoint will return the first 20 sessions ordered by creation date (newest first) with no status filter applied. This means you will see active, closed, and expired sessions mixed together in chronological order.

POST https://bbre-solver-api.mydisct.com/account/sessions

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 listing queries. 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 optional Set to application/json when sending a JSON request body with filter or pagination parameters. Not required if sending an empty body.

The sessions endpoint identifies your account entirely through the API key and returns only sessions that belong to that account. There is no way to view sessions from other accounts, and the API key determines which account's sessions are returned. Make sure your API key is sent as an HTTP header and not as a query parameter, because the BBRE API does not support query parameter authentication.

Request Parameters

The account sessions endpoint accepts an optional JSON request body with filter and pagination parameters. All parameters are optional. If you send an empty body or omit the body entirely, the endpoint returns the first 20 sessions across all statuses, ordered by creation date (newest first). The status parameter lets you filter sessions by their current state, while limit and offset control pagination. These parameters work together: you can filter by status and paginate through the filtered results, or paginate through all sessions without any status filter.

Parameter Type Required Description
status string optional Filter sessions by their current status. Accepted values are "active", "closed", and "expired". When omitted, sessions of all statuses are returned. Active sessions are currently usable and count against your 10-session limit. Closed sessions were explicitly terminated via the close endpoint. Expired sessions reached their timeout duration without being closed or used.
limit number optional Maximum number of sessions to return per page. Defaults to 20 if not specified. Use this parameter to control the response size. Smaller values mean faster responses and less data to process, while larger values reduce the number of API calls needed to iterate through your complete session list.
offset number optional Number of sessions to skip before starting to return results. Defaults to 0 (start from the beginning). Use this parameter in combination with limit to implement pagination. For example, to get the second page of 20 results, set offset to 20. To get the third page, set it to 40.

The status filter is case-sensitive and must be one of the three accepted values exactly as shown. Sending an unrecognized status value will return an empty result set rather than an error. The limit and offset values must be non-negative integers. The pagination applies after the status filter, so if you filter by "active" and set limit to 10, you will get up to 10 active sessions regardless of how many closed or expired sessions exist.

Response Format

The sessions endpoint returns a JSON response containing an array of session objects and a pagination metadata object. On success, the response includes the standard BBRE success fields, the sessions array with detailed information about each session, and a pagination object that tells you the total number of matching sessions, the current limit, and the current offset. This pagination metadata is essential for building pagination controls in your application because it tells you whether there are more pages of results to fetch.

Success Response (200)

A successful sessions query returns the following structure. The sessions array contains session objects ordered by creation time (newest first). Each session object includes all the information you need to understand the session's configuration, current state, usage statistics, and lifecycle timestamps. The pagination object provides the total count of matching sessions (after applying any status filter), the limit that was used for this query, and the offset that was used.

JSON
{
  "success": true,
  "service": "MyDisct Solver BBRE",
  "sessions": [
    {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "mode": "adaptive",
      "sensibility": "medium",
      "status": "active",
      "requestCount": 15,
      "totalCharged": 0.075,
      "expiresAt": "2024-06-15T11:30:00.000Z",
      "createdAt": "2024-06-15T10:30:00.000Z",
      "closedAt": null
    },
    {
      "id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
      "mode": "passive",
      "sensibility": "low",
      "status": "closed",
      "requestCount": 42,
      "totalCharged": 0.210,
      "expiresAt": "2024-06-14T16:00:00.000Z",
      "createdAt": "2024-06-14T14:00:00.000Z",
      "closedAt": "2024-06-14T15:45:00.000Z"
    }
  ],
  "pagination": {
    "total": 42,
    "limit": 20,
    "offset": 0
  }
}

Sessions Array Fields

Each object in the sessions array represents a single session and contains the following fields. These fields provide a complete picture of the session's configuration, current state, and usage statistics.

Field Type Description
id string Unique identifier for the session in UUID format. Use this ID when making requests within the session, checking session status, or closing the session.
mode string The operating mode of the session. Either "passive" for simple HTTP request mode or "adaptive" for full browser automation mode. The mode is set at session creation and cannot be changed afterward.
sensibility string The sensibility level of the session. One of "low", "medium", or "high". Higher sensibility means the BBRE engine applies more sophisticated evasion techniques, which results in slower but more stealthy requests.
status string Current status of the session. One of "active" (session is usable and accepting requests), "closed" (session was explicitly closed via the close endpoint), or "expired" (session reached its timeout duration without being closed).
requestCount number Total number of requests that have been made within this session. This count includes both successful and failed requests. A session with zero requests was created but never used.
totalCharged number Total amount in USD that has been charged for all operations within this session, including the session creation cost and all per-request charges. This value is a floating-point number.
expiresAt string ISO 8601 timestamp indicating when the session will expire if not closed or used. Active sessions have a future expiration time. Expired sessions have an expiration time in the past.
createdAt string ISO 8601 timestamp indicating when the session was created. Sessions are always returned ordered by this field in descending order (newest first).
closedAt string | null ISO 8601 timestamp indicating when the session was closed, or null if the session has not been closed. Active sessions always have null for this field. Expired sessions may also have null if they were never explicitly closed.

Pagination Object

The pagination object provides metadata about the total result set and the current page position. Use these values to calculate whether there are more pages to fetch and to construct the offset for the next page request.

Field Type Description
total number Total number of sessions matching the current filter criteria. If no status filter is applied, this is the total number of sessions across all statuses. Use this value to calculate the total number of pages: Math.ceil(total / limit).
limit number The maximum number of sessions per page that was used for this query. This reflects the limit parameter you sent in the request, or the default value of 20 if you did not specify one.
offset number The number of sessions that were skipped before the current page. This reflects the offset parameter you sent in the request, or 0 if you did not specify one. To get the next page, add the current limit to this value.

Error Response Examples

When the sessions query fails, the API returns an error response with the appropriate HTTP status code, error code, and a descriptive message. The most common error scenarios for this endpoint are authentication-related, since the endpoint parameters are all optional and the endpoint is lenient about unrecognized values.

401 - API Key Required

JSON
{
  "success": false,
  "service": "MyDisct Solver BBRE",
  "error": {
    "code": "API_KEY_REQUIRED",
    "message": "API key is required. Please provide your API key in the x-api-key or apikey header."
  }
}

403 - Invalid API Key

JSON
{
  "success": false,
  "service": "MyDisct Solver BBRE",
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The provided API key is invalid or does not exist."
  }
}

403 - Account Suspended

JSON
{
  "success": false,
  "service": "MyDisct Solver BBRE",
  "error": {
    "code": "ACCOUNT_SUSPENDED",
    "message": "Your account has been suspended. Please contact support for more information."
  }
}

500 - Service Error

JSON
{
  "success": false,
  "service": "MyDisct Solver BBRE",
  "error": {
    "code": "SERVICE_ERROR",
    "message": "An internal server error occurred. Please try again later."
  }
}

Filtering Examples

The status parameter lets you narrow the session list to only sessions in a specific state. This is particularly useful when you need to find active sessions that are consuming your session quota, review closed sessions to understand past usage, or identify expired sessions that were never properly cleaned up. The following examples demonstrate each filter option with the expected request body and a representative response.

Filter by Active Sessions

Filtering by "active" status returns only sessions that are currently usable and accepting requests. This is the most common filter because it tells you exactly how many of your 10 session slots are occupied and which sessions are consuming them. Active sessions have a future expiresAt timestamp and a null value for closedAt.

JSON
{
  "status": "active"
}

Response when you have 3 active sessions:

JSON
{
  "success": true,
  "service": "MyDisct Solver BBRE",
  "sessions": [
    {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "mode": "adaptive",
      "sensibility": "medium",
      "status": "active",
      "requestCount": 15,
      "totalCharged": 0.075,
      "expiresAt": "2024-06-15T11:30:00.000Z",
      "createdAt": "2024-06-15T10:30:00.000Z",
      "closedAt": null
    },
    {
      "id": "c3d4e5f6-a7b8-9012-cdef-123456789012",
      "mode": "passive",
      "sensibility": "low",
      "status": "active",
      "requestCount": 8,
      "totalCharged": 0.040,
      "expiresAt": "2024-06-15T12:00:00.000Z",
      "createdAt": "2024-06-15T10:00:00.000Z",
      "closedAt": null
    },
    {
      "id": "d4e5f6a7-b8c9-0123-defa-234567890123",
      "mode": "adaptive",
      "sensibility": "high",
      "status": "active",
      "requestCount": 3,
      "totalCharged": 0.045,
      "expiresAt": "2024-06-15T11:00:00.000Z",
      "createdAt": "2024-06-15T09:00:00.000Z",
      "closedAt": null
    }
  ],
  "pagination": {
    "total": 3,
    "limit": 20,
    "offset": 0
  }
}

Filter by Closed Sessions

Filtering by "closed" status returns sessions that were explicitly terminated using the POST /session/close endpoint. Closed sessions have a non-null closedAt timestamp that indicates exactly when the session was terminated. Reviewing closed sessions is useful for understanding your session usage patterns and verifying that your cleanup logic is working correctly.

JSON
{
  "status": "closed",
  "limit": 5
}

Filter by Expired Sessions

Filtering by "expired" status returns sessions that reached their timeout duration without being explicitly closed. Expired sessions indicate that your application created sessions but did not close them when they were no longer needed. A high number of expired sessions suggests that your session cleanup logic needs improvement. Expired sessions have an expiresAt timestamp in the past and typically have a null value for closedAt because they were never explicitly closed.

JSON
{
  "status": "expired",
  "limit": 10,
  "offset": 0
}

Pagination Through All Sessions

When you have more sessions than the page size, use the offset parameter to navigate through pages. The pagination.total field in the response tells you the total number of matching sessions, so you can calculate how many pages exist and whether there are more results to fetch. To get the next page, add the current limit to the current offset.

JSON
{
  "limit": 10,
  "offset": 20
}

This request skips the first 20 sessions and returns sessions 21 through 30. If the pagination.total is 42, you know there are 2 more pages after this one (sessions 31-40 and 41-42).

Session Management Patterns

The sessions endpoint is most valuable when combined with other session-related endpoints to implement automated session management. The following patterns demonstrate common approaches to session lifecycle management that you can adapt to your specific use case. These patterns help you stay within the 10 active session limit, clean up unused sessions, and monitor session utilization across your application.

Finding Active Sessions Before Creating New Ones

Before creating a new session, check how many active sessions you currently have. If you are at or near the 10-session limit, you need to close an existing session first. This pre-flight check prevents SESSION_LIMIT_REACHED errors and gives you the opportunity to reuse an existing session instead of creating a new one. Reusing sessions is more efficient because you avoid the session creation overhead and maintain the existing browser context, cookies, and profile data.

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

async function getActiveSessions() {
  const response = await fetch(API_BASE + "/account/sessions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY
    },
    body: JSON.stringify({ status: "active" })
  });

  const data = await response.json();
  return data.sessions;
}

async function createSessionSafely(options) {
  const activeSessions = await getActiveSessions();

  if (activeSessions.length >= MAX_ACTIVE_SESSIONS) {
    console.log("Session limit reached. Active sessions: " + activeSessions.length);
    console.log("Close an existing session before creating a new one.");
    return null;
  }

  console.log("Active sessions: " + activeSessions.length + "/" + MAX_ACTIVE_SESSIONS);

  const response = await fetch(API_BASE + "/session/create", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY
    },
    body: JSON.stringify(options)
  });

  const data = await response.json();
  console.log("New session created: " + data.sessionId);
  return data.sessionId;
}

createSessionSafely({
  mode: "adaptive",
  sensibility: "medium"
});

Cleaning Up Stale Sessions

Over time, your account may accumulate active sessions that are no longer being used by your application. This can happen when your application crashes without closing its sessions, when you restart your application during development, or when a session is created for a one-time task and forgotten. The following pattern identifies active sessions that have not received any requests recently and closes them to free up session slots.

JavaScript
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 cleanupStaleSessions() {
  const response = await fetch(API_BASE + "/account/sessions", {
    method: "POST",
    headers: authHeaders,
    body: JSON.stringify({ status: "active" })
  });

  const data = await response.json();
  const activeSessions = data.sessions;
  let closedCount = 0;

  for (const session of activeSessions) {
    if (session.requestCount === 0) {
      console.log("Closing unused session: " + session.id);
      await closeSession(session.id);
      closedCount++;
    }
  }

  console.log("Cleanup complete. Closed " + closedCount + " stale sessions.");
  console.log("Remaining active sessions: " + (activeSessions.length - closedCount));
}

async function closeSession(sessionId) {
  const response = await fetch(API_BASE + "/session/close", {
    method: "POST",
    headers: authHeaders,
    body: JSON.stringify({ sessionId: sessionId })
  });
  return response.json();
}

cleanupStaleSessions();

Session Utilization Report

Build a utilization report that summarizes your session usage across all statuses. This pattern fetches sessions from each status category and calculates aggregate statistics like total requests, total charges, and average requests per session. This data helps you understand your session usage patterns and optimize your session management strategy.

JavaScript
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 getSessionsByStatus(status) {
  const response = await fetch(API_BASE + "/account/sessions", {
    method: "POST",
    headers: authHeaders,
    body: JSON.stringify({ status: status, limit: 100 })
  });
  const data = await response.json();
  return { sessions: data.sessions, total: data.pagination.total };
}

async function generateUtilizationReport() {
  const active = await getSessionsByStatus("active");
  const closed = await getSessionsByStatus("closed");
  const expired = await getSessionsByStatus("expired");

  console.log("=== Session Utilization Report ===");
  console.log("Active sessions: " + active.total);
  console.log("Closed sessions: " + closed.total);
  console.log("Expired sessions: " + expired.total);

  const allSessions = [
    ...active.sessions,
    ...closed.sessions,
    ...expired.sessions
  ];

  const totalRequests = allSessions.reduce(function(sum, s) {
    return sum + s.requestCount;
  }, 0);

  const totalCharged = allSessions.reduce(function(sum, s) {
    return sum + s.totalCharged;
  }, 0);

  console.log("Total requests across all sessions: " + totalRequests);
  console.log("Total charged: $" + totalCharged.toFixed(4));

  if (allSessions.length > 0) {
    const avgRequests = totalRequests / allSessions.length;
    console.log("Average requests per session: " + avgRequests.toFixed(1));
  }
}

generateUtilizationReport();

Code Examples

The following examples demonstrate how to query your account sessions using different programming languages. 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. Each example includes the basic session listing call and demonstrates how to work with the response data.

JavaScript (fetch)

Retrieve your sessions using the native fetch API. This example demonstrates fetching all sessions without any filter, fetching only active sessions, and iterating through the results with pagination.

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

async function getSessions(options) {
  const response = await fetch(API_BASE + "/account/sessions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY
    },
    body: JSON.stringify(options || {})
  });

  const data = await response.json();

  if (!data.success) {
    console.log("Error:", data.error.code, data.error.message);
    return null;
  }

  return data;
}

async function listAllSessions() {
  const data = await getSessions();

  if (!data) return;

  console.log("Total sessions: " + data.pagination.total);

  for (const session of data.sessions) {
    console.log(
      session.id + " | " +
      session.mode + " | " +
      session.status + " | " +
      "requests: " + session.requestCount + " | " +
      "charged: $" + session.totalCharged.toFixed(4)
    );
  }
}

async function listActiveSessions() {
  const data = await getSessions({ status: "active" });

  if (!data) return;

  console.log("Active sessions: " + data.pagination.total + "/10");

  for (const session of data.sessions) {
    console.log(
      session.id + " | " +
      session.mode + " (" + session.sensibility + ") | " +
      session.requestCount + " requests | " +
      "expires: " + session.expiresAt
    );
  }
}

listAllSessions();
listActiveSessions();

JavaScript - Paginated Fetching

When you have many sessions, you need to paginate through the results. This example demonstrates how to fetch all sessions across multiple pages by incrementing the offset until all results have been retrieved.

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

async function fetchAllSessions(statusFilter) {
  const allSessions = [];
  const pageSize = 20;
  let offset = 0;
  let total = null;

  while (total === null || offset < total) {
    const body = { limit: pageSize, offset: offset };
    if (statusFilter) {
      body.status = statusFilter;
    }

    const response = await fetch(API_BASE + "/account/sessions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": API_KEY
      },
      body: JSON.stringify(body)
    });

    const data = await response.json();

    if (!data.success) {
      console.log("Error on page fetch:", data.error.code);
      break;
    }

    allSessions.push(...data.sessions);
    total = data.pagination.total;
    offset += pageSize;

    console.log("Fetched " + allSessions.length + "/" + total + " sessions");
  }

  return allSessions;
}

async function main() {
  const sessions = await fetchAllSessions("closed");
  console.log("Total closed sessions retrieved: " + sessions.length);

  const totalCharged = sessions.reduce(function(sum, s) {
    return sum + s.totalCharged;
  }, 0);
  console.log("Total charged across closed sessions: $" + totalCharged.toFixed(4));
}

main();

Python (requests library)

Retrieve and process your sessions using the Python requests library. This example shows how to list sessions with filtering and how to paginate through results.

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 + "/account/sessions",
    headers=headers,
    json={"status": "active"}
)

data = response.json()

if data["success"]:
    print(f"Active sessions: {data['pagination']['total']}/10")
    for session in data["sessions"]:
        print(
            f"  {session['id']} | "
            f"{session['mode']} ({session['sensibility']}) | "
            f"{session['requestCount']} requests | "
            f"${session['totalCharged']:.4f}"
        )
else:
    print(f"Error: {data['error']['code']}")
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
}

def fetch_all_sessions(status_filter=None):
    all_sessions = []
    page_size = 20
    offset = 0

    while True:
        body = {"limit": page_size, "offset": offset}
        if status_filter:
            body["status"] = status_filter

        response = requests.post(
            API_BASE + "/account/sessions",
            headers=headers,
            json=body
        )
        data = response.json()

        if not data["success"]:
            print(f"Error: {data['error']['code']}")
            break

        all_sessions.extend(data["sessions"])
        total = data["pagination"]["total"]
        offset += page_size

        if offset >= total:
            break

    return all_sessions

sessions = fetch_all_sessions("closed")
print(f"Retrieved {len(sessions)} closed sessions")

total_charged = sum(s["totalCharged"] for s in sessions)
print(f"Total charged: ${total_charged:.4f}")

cURL

Quick session listing from the command line using cURL. These examples show how to list all sessions, filter by status, and paginate through results.

Bash
curl -X POST https://bbre-solver-api.mydisct.com/account/sessions \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY"
Bash
curl -X POST https://bbre-solver-api.mydisct.com/account/sessions \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{"status": "active"}'
Bash
curl -X POST https://bbre-solver-api.mydisct.com/account/sessions \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{"status": "closed", "limit": 10, "offset": 0}'
Bash
curl -X POST https://bbre-solver-api.mydisct.com/account/sessions \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{"limit": 5, "offset": 20}'

Node.js SDK Usage

The mydisctsolver-bbre Node.js SDK does not currently expose a dedicated method for listing account sessions. However, you can use the SDK's underlying HTTP client capabilities or combine the SDK's session management methods with direct API calls to achieve the same result. The following examples show how to integrate session listing into your SDK-based workflow.

Combining SDK Session Management with Direct API Calls

Use the SDK for session creation and management while calling the sessions listing endpoint directly for monitoring and cleanup tasks. This hybrid approach gives you the convenience of the SDK for day-to-day operations and the flexibility of direct API calls for administrative tasks.

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

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

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

async function getActiveSessionCount() {
  const response = await fetch(API_BASE + "/account/sessions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY
    },
    body: JSON.stringify({ status: "active" })
  });
  const data = await response.json();
  return data.pagination.total;
}

async function createSessionWithCheck() {
  const activeCount = await getActiveSessionCount();

  if (activeCount >= 10) {
    console.log("Cannot create session. Active: " + activeCount + "/10");
    return null;
  }

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

  console.log("Session created via SDK: " + session.sessionId);
  return session;
}

createSessionWithCheck();

SDK Session Cleanup Workflow

Combine the sessions listing endpoint with the SDK's closeSession() method to build an automated cleanup workflow that identifies and closes unused sessions.

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

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

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

async function getActiveSessions() {
  const response = await fetch(API_BASE + "/account/sessions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY
    },
    body: JSON.stringify({ status: "active" })
  });
  const data = await response.json();
  return data.sessions;
}

async function cleanupUnusedSessions() {
  const sessions = await getActiveSessions();
  let closedCount = 0;

  for (const session of sessions) {
    if (session.requestCount === 0) {
      await client.closeSession(session.id);
      console.log("Closed unused session: " + session.id);
      closedCount++;
    }
  }

  console.log("Cleaned up " + closedCount + " unused sessions");
  return closedCount;
}

cleanupUnusedSessions();

Error Codes

The following table lists all error codes that can be returned by the account sessions endpoint, along with their HTTP status codes, descriptions, and recommended solutions. Because the sessions endpoint has no required parameters and is lenient about unrecognized filter values, the most common errors are authentication-related errors and server-side errors. Implementing proper error handling for these codes ensures your session management logic degrades gracefully when issues occur.

HTTP Status Error Code Description Solution
401 API_KEY_REQUIRED No API key was provided in the request headers. The sessions endpoint requires authentication like all other BBRE endpoints. Include your API key in the x-api-key or apikey header. Verify that your HTTP client is sending the header correctly and that it is not being stripped by a proxy or middleware.
403 INVALID_API_KEY The provided API key is not valid or does not exist in the system. Verify your API key in the MyDisct Solver dashboard. Ensure you are copying the complete key without extra spaces or line breaks. If you recently regenerated your key, update it in your application configuration.
403 ACCOUNT_SUSPENDED Your account has been suspended. Suspended accounts cannot access any BBRE API endpoints, including the sessions listing endpoint. Contact MyDisct Solver support for information about your account suspension and steps to resolve it.
403 ACCOUNT_INACTIVE Your account is inactive. Inactive accounts need to be activated before they can use the BBRE API. Activate your account through the MyDisct Solver dashboard or contact support for assistance.
500 SERVICE_ERROR An internal server error occurred while processing the sessions request. This can happen during high load periods or database connectivity issues. Retry the request after a short delay (2-5 seconds). If the error persists, contact support. Do not let a temporary sessions listing failure block your entire workflow.

Error Handling Example

The following example demonstrates robust error handling for the sessions endpoint. In production systems, your session listing logic should handle each error code appropriately and fall back to a safe default behavior when the session list cannot be retrieved.

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

async function getSessionsSafe(options) {
  try {
    const response = await fetch(API_BASE + "/account/sessions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": API_KEY
      },
      body: JSON.stringify(options || {})
    });

    const data = await response.json();

    if (data.success) {
      return {
        sessions: data.sessions,
        pagination: data.pagination,
        error: null
      };
    }

    const errorCode = data.error.code;

    if (errorCode === "API_KEY_REQUIRED" || errorCode === "INVALID_API_KEY") {
      return { sessions: [], pagination: null, error: "Authentication failed: " + errorCode };
    }

    if (errorCode === "ACCOUNT_SUSPENDED" || errorCode === "ACCOUNT_INACTIVE") {
      return { sessions: [], pagination: null, error: "Account issue: " + errorCode };
    }

    return { sessions: [], pagination: null, error: "Unexpected error: " + errorCode };

  } catch (networkError) {
    return { sessions: [], pagination: null, error: "Network error: " + networkError.message };
  }
}

async function main() {
  const result = await getSessionsSafe({ status: "active" });

  if (result.error) {
    console.log("Could not list sessions:", result.error);
    return;
  }

  console.log("Active sessions: " + result.pagination.total);
  for (const session of result.sessions) {
    console.log("  " + session.id + " (" + session.mode + ")");
  }
}

main();

Best Practices

Check Active Session Count Before Creating New Sessions

Always query the sessions endpoint with {"status": "active"} before attempting to create a new session. The BBRE API enforces a hard limit of 10 concurrent active sessions per account, and exceeding this limit results in a SESSION_LIMIT_REACHED error. By checking the active session count first, you can either reuse an existing session, close an unused session to free up a slot, or inform the user that the limit has been reached. This pre-flight check takes milliseconds and prevents frustrating errors in your session creation workflow.

Implement Automated Session Cleanup

Set up a periodic cleanup routine that lists active sessions and closes any that are no longer needed. Sessions that have zero requests or sessions that were created a long time ago without recent activity are good candidates for cleanup. Run this cleanup routine at application startup and at regular intervals (every 5-10 minutes) to ensure your session slots are not wasted on abandoned sessions. This is especially important in development environments where sessions are frequently created for testing and then forgotten when the developer moves on to other tasks.

Use Status Filters to Reduce Response Size

When you only need information about active sessions, always include the status filter in your request. Fetching all sessions without a filter returns active, closed, and expired sessions mixed together, which means larger response payloads and more data to process on the client side. If your account has hundreds of historical sessions, an unfiltered request could return a significant amount of data that you do not need. Filtering by status at the API level is more efficient than fetching everything and filtering on the client side.

Close Sessions Explicitly Instead of Waiting for Expiration

When your application is done with a session, close it immediately using the POST /session/close endpoint rather than letting it expire naturally. Explicitly closed sessions free up your session slot immediately, while expired sessions may continue to occupy a slot until the system processes the expiration. Additionally, explicitly closing sessions makes your session history cleaner and easier to analyze, because you can distinguish between sessions that were properly terminated (closed) and sessions that were abandoned (expired). A high ratio of expired to closed sessions indicates a problem with your session lifecycle management.

Monitor Session Utilization Metrics

Periodically generate session utilization reports by querying sessions across all statuses and calculating aggregate metrics like average requests per session, average session duration, total charges per session, and the ratio of active to expired sessions. These metrics help you optimize your session management strategy. For example, if your average session has very few requests, you might be creating too many sessions and should consider reusing existing ones. If your sessions frequently expire, you might need to increase the session timeout or implement better cleanup logic. Track these metrics over time to identify trends and catch issues early.

Common Issues

Issue 1: SESSION_LIMIT_REACHED When Creating a New Session

Problem

You receive a SESSION_LIMIT_REACHED error when trying to create a new session, but you believe you should have available session slots. Your application only creates a few sessions at a time, yet the limit is being hit.

Solution: Use the sessions endpoint to list all active sessions and identify which sessions are consuming your slots. It is common for sessions to accumulate when your application crashes or restarts without properly closing its sessions. These orphaned sessions remain active until they expire. Call POST /account/sessions with {"status": "active"} to see all active sessions, then close any that your application is no longer using. Implement a startup routine that checks for and closes orphaned sessions from previous application runs. You can identify orphaned sessions by comparing the session IDs in the API response against the session IDs your current application instance is tracking.

Issue 2: Empty Sessions Array Despite Having Created Sessions

Problem

The sessions endpoint returns an empty sessions array even though you have created sessions recently. The pagination.total shows 0.

Solution: First, verify that you are using the correct API key. The sessions endpoint returns only sessions that belong to the account associated with the provided API key. If you have multiple API keys or multiple accounts, make sure you are using the same key that was used to create the sessions. Second, check your status filter. If you are filtering by "active" but all your sessions have been closed or expired, the result will be empty. Try removing the status filter to see all sessions regardless of status. Third, check the offset parameter. If you accidentally set a large offset value, you might be skipping past all your sessions.

Issue 3: Sessions Show as Expired Unexpectedly

Problem

Sessions that you expected to be active are showing up with an "expired" status. Your application was still using these sessions, but they expired before you finished your workflow.

Solution: Sessions have a finite lifetime that is determined at creation time. If your workflow takes longer than the session timeout, the session will expire before you finish. Check the expiresAt field of your sessions to understand their lifetime. If your workflows consistently need more time, consider increasing the session timeout when creating sessions by setting a higher timeout value in the POST /session/create request. Also, make sure your application is actively sending requests within the session at regular intervals, as some session configurations may extend the expiration time when activity is detected. Monitor the expiresAt field of your active sessions and plan your workflow to complete before the expiration time.