Session Status
The POST /session/status endpoint retrieves the current status and detailed
metadata of an existing BBRE (Browser-Backed Request Engine) session. This endpoint is your
primary tool for monitoring session health, tracking usage metrics, and making informed
decisions about session lifecycle management. When you call this endpoint with a valid
session ID, the BBRE engine returns comprehensive information about the session including
its current status (active, expired, or closed), the operating mode (passive or adaptive),
the sensibility level, the number of requests processed through the session, the total
amount charged for those requests, the expiration timestamp, and the creation timestamp.
One of the most important behaviors of this endpoint is its automatic expiration detection.
If a session has passed its expiration time but its status has not yet been updated in the
database, the status endpoint automatically transitions the session from active
to expired before returning the response. This means you can always trust the
status value returned by this endpoint to accurately reflect the current state of the
session, even if the background expiration process has not yet run. This automatic
reconciliation eliminates race conditions where your application might attempt to use a
session that has technically expired but still shows as active in the database. Session
status checking is essential for building robust integrations that need to verify session
availability before sending requests, monitor session usage for billing and analytics
purposes, implement session renewal logic based on remaining time, track request counts
for rate limiting or quota management, and debug issues with session-based workflows by
inspecting the session state at any point during execution. This page provides complete
documentation for the session status endpoint, including the request format, authentication
requirements, all response fields with detailed explanations, session status values and
their meanings, working code examples in JavaScript, Python, and cURL, monitoring patterns,
error handling, SDK integration, and best practices for effective session monitoring.
The session status endpoint performs automatic expiration detection every time it is called.
If the session's expiresAt timestamp has passed but the session status is still
recorded as active in the database, the endpoint automatically updates the
status to expired before returning the response. This means the status value
you receive is always accurate and reflects the true current state of the session. You do
not need to implement your own expiration checking logic on the client side. Simply call
this endpoint and trust the returned status value. This behavior is particularly useful
when you need to verify that a session is still usable before sending a request through it,
as it eliminates the possibility of getting a stale active status for a session
that has actually expired.
Endpoint
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 status checks. The API accepts
the key through either the x-api-key header or the apikey header.
Both header names are supported and functionally identical. The API key used to check a
session's status must belong to the same account that created the session. You cannot check
the status of sessions that belong to other accounts. 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 session ID of the session whose status
you want to check. The sessionId parameter is the only parameter accepted by
this endpoint and it is required. The session ID is the unique identifier that was returned
when you created the session using the POST /session/create endpoint. If you
do not provide a session ID, the endpoint returns a 400 SESSION_ID_REQUIRED
error. The session ID format is a string that typically starts with session_
followed by an alphanumeric identifier, but you should treat it as an opaque string and
always use the exact value returned by the session creation endpoint. Unlike the close
endpoint, the status endpoint does not modify the session in any way except for the
automatic expiration detection described above. You can call this endpoint as many times
as you need without any side effects on the session itself.
| Parameter | Type | Required | Description |
|---|---|---|---|
sessionId |
string | required | The unique session identifier returned by the POST /session/create endpoint. This is the session.id field from the creation response. The session must belong to the authenticated user. If the session does not exist or belongs to a different account, the API returns a 404 SESSION_NOT_FOUND error. |
Response Format
The session status endpoint returns a JSON response containing detailed information about
the requested session. On success, the response includes the session ID, current status,
operating mode, sensibility level, request count, total charged amount, expiration timestamp,
and creation timestamp. This comprehensive set of fields gives you complete visibility into
the session's configuration, usage, and lifecycle state. On failure, the response includes
an error code, a human-readable message, and additional details where applicable. The
response always includes the "service": "MyDisct Solver BBRE" field to
identify which service processed the request.
Success Response (200)
A successful status check returns the following structure. The session object
contains all the metadata fields for the session. The status field reflects
the true current state of the session after automatic expiration detection has been applied.
The requestCount and totalCharged fields provide real-time usage
metrics that are updated after each request processed through the session.
{
"success": true,
"service": "MyDisct Solver BBRE",
"session": {
"id": "session_abc123def456",
"status": "active",
"mode": "adaptive",
"sensibility": "high",
"requestCount": 5,
"totalCharged": 0.025,
"expiresAt": 1706789012345,
"createdAt": 1706788712345
}
}
Response Field Descriptions
| 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. This matches the sessionId you sent in the request body and the session.id value returned when the session was created. |
session.status |
string | The current session status after automatic expiration detection. Possible values are "active", "expired", and "closed". If the session was active but its expiration time has passed, this field will show "expired" because the endpoint automatically updates the status before returning the response. See the Session Status Values section below for detailed descriptions of each status. |
session.mode |
string | The operating mode of the session, either "passive" or "adaptive". This is the mode that was specified (or defaulted) when the session was created. Passive mode uses a lightweight HTTP client with cookie persistence. Adaptive mode uses a full browser instance with JavaScript execution and DOM rendering. The mode cannot be changed after session creation. |
session.sensibility |
string | The detection evasion sensitivity level of the session. Possible values are "low", "medium", and "high". This is the sensibility that was specified (or defaulted to "medium") when the session was created. Higher sensibility levels apply more aggressive evasion techniques but result in slower request processing. The sensibility cannot be changed after session creation. |
session.requestCount |
number | The total number of requests that have been processed through this session. This counter increments each time a request is successfully executed via the POST /session/request endpoint. Use this field to track session utilization, implement request-based quotas, or monitor workflow progress. A newly created session that has not processed any requests will have a requestCount of 0. |
session.totalCharged |
number | The total amount charged for all requests processed through this session, expressed as a decimal number in USD. This value accumulates as requests are processed and reflects the sum of individual request charges. Use this field for cost tracking, budget monitoring, and billing reconciliation. A newly created session will have a totalCharged of 0. Note that the session creation cost itself is not included in this field; it only tracks request-level charges. |
session.expiresAt |
number | Unix timestamp in milliseconds representing when the session will expire (or has already expired). This value is calculated at session creation time as the creation timestamp plus the timeout value in seconds multiplied by 1000. Compare this value against the current time to determine how much time remains before the session expires. For example, if expiresAt is 1706789012345 and the current time is 1706788912345, the session has approximately 100 seconds remaining. |
session.createdAt |
number | Unix timestamp in milliseconds representing when the session was created. Use this field in combination with expiresAt to calculate the original timeout duration, or to determine how long the session has been alive. The difference between expiresAt and createdAt gives you the original timeout value in milliseconds. |
Error Response Examples
When the session status check fails, the API returns an error response with the appropriate HTTP status code, error code, and a descriptive message. The following examples show the most common error responses you may encounter when checking session status.
400 - Session ID Required
{
"success": false,
"service": "MyDisct Solver BBRE",
"error": {
"code": "SESSION_ID_REQUIRED",
"message": "Session ID is required.",
"details": {
"hint": "Session ID is returned when you create a session"
}
}
}
404 - Session Not Found
{
"success": false,
"service": "MyDisct Solver BBRE",
"error": {
"code": "SESSION_NOT_FOUND",
"message": "Session not found."
}
}
500 - Service Error
{
"success": false,
"service": "MyDisct Solver BBRE",
"error": {
"code": "SERVICE_ERROR",
"message": "An internal error occurred. Please try again later."
}
}
Session Status Values
The session.status field in the response can have one of three possible values.
Each value represents a distinct phase in the session lifecycle and determines what
operations can be performed on the session. Understanding these status values is critical
for implementing correct session management logic in your application, especially when
deciding whether to send requests through a session, renew it, or create a new one.
| Status | Description | Can Send Requests | Next Possible States |
|---|---|---|---|
active |
The session is currently active and ready to accept requests. The browser context is allocated and maintaining state (cookies, fingerprint, and in adaptive mode, the full browser instance). All session operations including /session/request and /browser/action are available. The session will remain active until it either expires (when the current time exceeds expiresAt) or is explicitly closed via /session/close. |
Yes | expired, closed |
expired |
The session has exceeded its expiration time. The expiresAt timestamp has passed and the session is no longer usable. Any attempt to send requests through an expired session returns a 400 SESSION_EXPIRED error. The browser context associated with the session has been released. Expired sessions cannot be reactivated, extended, or renewed. You must create a new session to continue your workflow. The status endpoint automatically detects expiration and updates the status from active to expired when you check it. |
No | Terminal state |
closed |
The session was explicitly closed by the user via the POST /session/close endpoint. The browser context has been immediately released and all associated state (cookies, fingerprint, navigation history) has been permanently discarded. Closed sessions cannot be reopened or reused. Like expired sessions, any attempt to send requests through a closed session returns an error. The difference between expired and closed is that expiration happens automatically based on the timeout, while closure is an explicit action taken by the user. |
No | Terminal state |
Request Examples
The following examples demonstrate how to check the status of a BBRE session 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 and session_abc123def456 with the session ID returned by
the session creation endpoint.
Basic Status Check
The simplest way to check a session's status. This sends the session ID to the status endpoint and logs all the returned fields. Use this pattern when you need a quick snapshot of the session state, for example before deciding whether to send another request through the session or whether to create a new one.
const axios = require("axios");
const API_BASE = "https://bbre-solver-api.mydisct.com";
const API_KEY = "YOUR_API_KEY";
async function checkSessionStatus(sessionId) {
const response = await axios.post(
API_BASE + "/session/status",
{ sessionId: sessionId },
{
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("Mode:", session.mode);
console.log("Sensibility:", session.sensibility);
console.log("Request Count:", session.requestCount);
console.log("Total Charged:", session.totalCharged);
console.log("Expires At:", new Date(session.expiresAt).toISOString());
console.log("Created At:", new Date(session.createdAt).toISOString());
return session;
}
checkSessionStatus("session_abc123def456");
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/status",
headers=headers,
json={"sessionId": "session_abc123def456"}
)
data = response.json()
session = data["session"]
print("Session ID:", session["id"])
print("Status:", session["status"])
print("Mode:", session["mode"])
print("Sensibility:", session["sensibility"])
print("Request Count:", session["requestCount"])
print("Total Charged:", session["totalCharged"])
expires = datetime.fromtimestamp(session["expiresAt"] / 1000)
print("Expires At:", expires.isoformat())
created = datetime.fromtimestamp(session["createdAt"] / 1000)
print("Created At:", created.isoformat())
curl -X POST https://bbre-solver-api.mydisct.com/session/status \
-H "Content-Type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{"sessionId": "session_abc123def456"}'
Check Expiration Before Sending Requests
A common pattern is to check the session status before sending a request through it,
especially when some time has passed since the session was created or since the last
request was sent. This prevents wasted API calls that would fail with a
SESSION_EXPIRED error. The following example demonstrates how to verify
session availability and calculate the remaining time before expiration, then decide
whether to proceed with the request or create a new session.
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 isSessionUsable(sessionId) {
const response = await axios.post(
API_BASE + "/session/status",
{ sessionId: sessionId },
{ headers: authHeaders }
);
const session = response.data.session;
if (session.status !== "active") {
console.log("Session is", session.status, "- cannot send requests");
return false;
}
const remainingMs = session.expiresAt - Date.now();
const remainingSec = Math.floor(remainingMs / 1000);
console.log("Session is active, expires in", remainingSec, "seconds");
if (remainingSec < 10) {
console.log("Session expiring too soon, create a new one");
return false;
}
return true;
}
async function sendRequestIfSessionActive(sessionId, url) {
const usable = await isSessionUsable(sessionId);
if (!usable) {
console.log("Creating a new session...");
const createResponse = await axios.post(
API_BASE + "/session/create",
{ mode: "passive", sensibility: "medium", timeout: 300 },
{ headers: authHeaders }
);
sessionId = createResponse.data.session.id;
console.log("New session created:", sessionId);
}
const response = await axios.post(
API_BASE + "/session/request",
{ sessionId: sessionId, url: url, method: "GET" },
{ headers: authHeaders }
);
console.log("Request completed:", response.data.data.task.status);
return response.data;
}
sendRequestIfSessionActive("session_abc123def456", "https://example.com/data");
import requests
import time
API_BASE = "https://bbre-solver-api.mydisct.com"
API_KEY = "YOUR_API_KEY"
headers = {
"Content-Type": "application/json",
"x-api-key": API_KEY
}
def is_session_usable(session_id):
response = requests.post(
API_BASE + "/session/status",
headers=headers,
json={"sessionId": session_id}
)
session = response.json()["session"]
if session["status"] != "active":
print(f"Session is {session['status']} - cannot send requests")
return False
remaining_ms = session["expiresAt"] - int(time.time() * 1000)
remaining_sec = remaining_ms // 1000
print(f"Session is active, expires in {remaining_sec} seconds")
if remaining_sec < 10:
print("Session expiring too soon, create a new one")
return False
return True
def send_request_if_active(session_id, url):
if not is_session_usable(session_id):
print("Creating a new session...")
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("New session created:", session_id)
response = requests.post(
API_BASE + "/session/request",
headers=headers,
json={"sessionId": session_id, "url": url, "method": "GET"}
)
print("Request completed:", response.json()["data"]["task"]["status"])
return response.json()
send_request_if_active("session_abc123def456", "https://example.com/data")
Track Usage and Costs
The session status endpoint is valuable for monitoring usage metrics during long-running
workflows. The requestCount and totalCharged fields let you
track how many requests have been processed and how much they have cost in real time. This
is useful for implementing budget limits, logging workflow progress, and generating usage
reports. The following example demonstrates a monitoring function that checks session
metrics periodically and enforces a maximum request count and cost threshold.
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 monitorSession(sessionId, maxRequests, maxCost) {
const response = await axios.post(
API_BASE + "/session/status",
{ sessionId: sessionId },
{ headers: authHeaders }
);
const session = response.data.session;
const remainingSec = Math.floor((session.expiresAt - Date.now()) / 1000);
console.log("Session Monitor Report:");
console.log(" Status:", session.status);
console.log(" Mode:", session.mode);
console.log(" Requests:", session.requestCount, "/", maxRequests);
console.log(" Cost: $" + session.totalCharged.toFixed(4), "/ $" + maxCost.toFixed(4));
console.log(" Time Remaining:", remainingSec, "seconds");
if (session.status !== "active") {
return { shouldContinue: false, reason: "session_" + session.status };
}
if (session.requestCount >= maxRequests) {
return { shouldContinue: false, reason: "max_requests_reached" };
}
if (session.totalCharged >= maxCost) {
return { shouldContinue: false, reason: "max_cost_reached" };
}
if (remainingSec < 15) {
return { shouldContinue: false, reason: "expiring_soon" };
}
return { shouldContinue: true, session: session };
}
monitorSession("session_abc123def456", 50, 0.50);
import requests
import time
API_BASE = "https://bbre-solver-api.mydisct.com"
API_KEY = "YOUR_API_KEY"
headers = {
"Content-Type": "application/json",
"x-api-key": API_KEY
}
def monitor_session(session_id, max_requests, max_cost):
response = requests.post(
API_BASE + "/session/status",
headers=headers,
json={"sessionId": session_id}
)
session = response.json()["session"]
remaining_ms = session["expiresAt"] - int(time.time() * 1000)
remaining_sec = remaining_ms // 1000
print("Session Monitor Report:")
print(f" Status: {session['status']}")
print(f" Mode: {session['mode']}")
print(f" Requests: {session['requestCount']} / {max_requests}")
print(f" Cost: ${session['totalCharged']:.4f} / ${max_cost:.4f}")
print(f" Time Remaining: {remaining_sec} seconds")
if session["status"] != "active":
return {"should_continue": False, "reason": f"session_{session['status']}"}
if session["requestCount"] >= max_requests:
return {"should_continue": False, "reason": "max_requests_reached"}
if session["totalCharged"] >= max_cost:
return {"should_continue": False, "reason": "max_cost_reached"}
if remaining_sec < 15:
return {"should_continue": False, "reason": "expiring_soon"}
return {"should_continue": True, "session": session}
monitor_session("session_abc123def456", 50, 0.50)
Error Codes
The following table lists all error codes that can be returned by the session status endpoint, along with their HTTP status codes, descriptions, and recommended solutions. The session status endpoint has a relatively small set of possible errors compared to other endpoints because it is a read-only operation that does not modify session state (except for the automatic expiration detection). Implementing proper error handling for each of these codes ensures your monitoring and status-checking logic can handle every scenario gracefully.
| HTTP Status | Error Code | Description | Solution |
|---|---|---|---|
400 |
SESSION_ID_REQUIRED |
The sessionId field is missing from the request body. The endpoint requires a session ID to look up the session record. |
Include the sessionId field in your JSON request body. The session ID is the session.id value returned by the POST /session/create endpoint. Ensure your request body is valid JSON and the field name is exactly sessionId (camelCase). |
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. |
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. |
404 |
SESSION_NOT_FOUND |
No session with the provided ID exists for the authenticated user. This can happen if the session ID is incorrect, if the session was created by a different account, or if the session record has been removed from the system after expiration cleanup. | Verify the session ID is correct and matches the value returned by POST /session/create. Ensure you are using the same API key that was used to create the session. If the session has expired and been cleaned up, you will need to create a new session. |
500 |
SERVICE_ERROR |
An internal server error occurred while processing the session status request. | Retry the request after a short delay (2-5 seconds). If the error persists, contact support. The session itself is not affected by this error; it is a transient server-side issue. |
Monitoring Patterns
The session status endpoint enables several powerful monitoring patterns that help you build more reliable and cost-effective integrations. The following patterns demonstrate common real-world scenarios where session status checking plays a critical role in workflow management.
Expiration Countdown Timer
For applications with a user interface or logging system, you can implement an expiration
countdown that shows how much time remains before the session expires. This is particularly
useful for dashboard applications, monitoring tools, or any system where operators need
visibility into session health. Calculate the remaining time by subtracting the current
timestamp from the expiresAt value. If the remaining time drops below a
threshold (for example, 30 seconds), trigger a warning or automatically create a new
session to ensure continuity.
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 getSessionTimeRemaining(sessionId) {
const response = await axios.post(
API_BASE + "/session/status",
{ sessionId: sessionId },
{ headers: authHeaders }
);
const session = response.data.session;
if (session.status !== "active") {
return { active: false, status: session.status, remainingSeconds: 0 };
}
const remainingMs = session.expiresAt - Date.now();
const remainingSec = Math.max(0, Math.floor(remainingMs / 1000));
return {
active: true,
status: session.status,
remainingSeconds: remainingSec,
expiresAt: new Date(session.expiresAt).toISOString()
};
}
getSessionTimeRemaining("session_abc123def456").then(info => {
if (info.active) {
console.log("Session expires in", info.remainingSeconds, "seconds");
} else {
console.log("Session is", info.status);
}
});
Usage Tracking for Billing
The requestCount and totalCharged fields provide real-time
billing data for each session. You can use these fields to implement per-session cost
tracking, generate usage reports, enforce budget limits, or reconcile charges against your
account balance. For applications that process many sessions, periodically checking the
status of active sessions and aggregating the totalCharged values gives you
a running total of your current spending. This is more granular than checking your account
balance because it breaks down costs by individual session and workflow.
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 getSessionUsageReport(sessionId) {
const response = await axios.post(
API_BASE + "/session/status",
{ sessionId: sessionId },
{ headers: authHeaders }
);
const session = response.data.session;
const durationMs = Date.now() - session.createdAt;
const durationSec = Math.floor(durationMs / 1000);
const costPerRequest = session.requestCount > 0
? session.totalCharged / session.requestCount
: 0;
return {
sessionId: session.id,
status: session.status,
mode: session.mode,
sensibility: session.sensibility,
totalRequests: session.requestCount,
totalCost: session.totalCharged,
averageCostPerRequest: parseFloat(costPerRequest.toFixed(6)),
sessionDurationSeconds: durationSec
};
}
getSessionUsageReport("session_abc123def456").then(report => {
console.log("Usage Report:", JSON.stringify(report, null, 2));
});
Node.js SDK Usage
The mydisctsolver-bbre Node.js SDK provides two convenient ways to check
session status. The BBREClient class has a getSessionStatus()
method that accepts a session ID and returns the session status directly. Additionally,
if you are using the BBRESession class for session-based workflows, the
session object itself has a status() method that checks the status of the
session it represents without requiring you to pass the session ID manually. Both methods
wrap the POST /session/status endpoint and handle authentication headers,
request formatting, and response parsing automatically.
Check Status via BBREClient
Use the client.getSessionStatus() method when you have a session ID stored
as a string and want to check its status directly through the client instance. This is
useful when you are managing session IDs manually or when you need to check the status
of a session from a different part of your application than where it was created.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({
apiKey: "YOUR_API_KEY"
});
async function checkWithClient() {
const sessionId = "session_abc123def456";
const result = await client.getSessionStatus(sessionId);
console.log("Status:", result.status);
console.log("Expires At:", new Date(result.expiresAt).toISOString());
if (result.status === "active") {
console.log("Session is ready for requests");
} else {
console.log("Session is no longer active:", result.status);
}
return result;
}
checkWithClient();
Check Status via BBRESession Object
When you create a session using the SDK's session management features, the returned
BBRESession object has a built-in status() method. This is the
most natural way to check session status in SDK-based workflows because the session object
already knows its own session ID and the client configuration needed to make the API call.
The status() method internally calls getSessionStatus() with the
session's own ID.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({
apiKey: "YOUR_API_KEY",
mode: "passive",
sensibility: "medium"
});
async function workflowWithStatusCheck() {
const session = await client.createSession({ timeout: 300 });
console.log("Session created:", session.sessionId);
try {
const loginResult = await session.request({
url: "https://example.com/api/login",
method: "POST",
body: { username: "myuser", password: "mypassword" }
});
console.log("Login status:", loginResult.statusCode);
const statusInfo = await session.status();
console.log("Session status:", statusInfo.status);
console.log("Expires at:", new Date(statusInfo.expiresAt).toISOString());
if (statusInfo.status !== "active") {
console.log("Session is no longer active, stopping workflow");
return null;
}
const dataResult = await session.request({
url: "https://example.com/api/data",
method: "GET"
});
console.log("Data fetched:", dataResult.statusCode);
return dataResult.body;
} finally {
await session.close();
console.log("Session closed");
}
}
workflowWithStatusCheck();
Conditional Session Renewal with SDK
The following example demonstrates a pattern where you check the session status before each request and automatically create a new session if the current one is no longer usable. This pattern is useful for long-running applications that need to maintain continuous session availability without manual intervention.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({
apiKey: "YOUR_API_KEY",
mode: "passive",
sensibility: "medium"
});
let currentSession = null;
async function ensureActiveSession() {
if (currentSession) {
try {
const statusInfo = await currentSession.status();
if (statusInfo.status === "active") {
const remainingMs = statusInfo.expiresAt - Date.now();
if (remainingMs > 15000) {
return currentSession;
}
}
} catch (err) {
console.log("Status check failed, creating new session");
}
try {
await currentSession.close();
} catch (err) {
console.log("Close failed (session may have expired)");
}
}
currentSession = await client.createSession({ timeout: 300 });
console.log("New session created:", currentSession.sessionId);
return currentSession;
}
async function fetchWithAutoRenewal(url) {
const session = await ensureActiveSession();
const result = await session.request({ url: url, method: "GET" });
return result;
}
fetchWithAutoRenewal("https://example.com/data");
Best Practices
Before sending requests through a session that has been idle for any period of time,
call the status endpoint to verify the session is still active. This is especially
important before critical operations like form submissions, payment processing, or
any action that cannot be easily retried. The status check adds minimal latency
(typically under 100ms) but prevents wasted API calls and potential data loss from
attempting to use an expired session. Compare the expiresAt value against
the current time and ensure there is enough remaining time for your operation to
complete. A good rule of thumb is to require at least 15-30 seconds of remaining
session time before starting a new request, depending on the expected processing time
of your request.
Implement periodic status checks during long-running workflows to monitor the
totalCharged and requestCount fields. Set budget thresholds
in your application and stop the workflow if the session cost exceeds your limit. This
prevents runaway costs from infinite loops, unexpected redirects, or other scenarios
where your application might send more requests than intended. For example, if you
expect a workflow to make 10 requests at approximately $0.005 each, set a cost
threshold of $0.10 and a request count threshold of 20 to catch anomalies early. Log
the usage metrics at the end of each workflow for billing reconciliation and capacity
planning.
If your application needs to check session status very frequently (more than once per
second), consider caching the status response locally and refreshing it at a reasonable
interval such as every 5-10 seconds. The session status does not change between
requests, so checking it multiple times per second provides no additional value and
adds unnecessary API calls. Cache the expiresAt value locally and use
client-side time comparison for expiration checks between API calls. Only call the
status endpoint when you need fresh data about requestCount,
totalCharged, or when you suspect the session state may have changed
due to external factors like another part of your application closing the session.
Rather than waiting for a session to expire and then reacting to the error, implement proactive session renewal by checking the remaining time and creating a new session before the current one expires. When the status check shows that the session has less than 30 seconds remaining, create a new session in the background and switch your workflow to use the new session for subsequent requests. This eliminates downtime between sessions and ensures your workflow can continue without interruption. For workflows that require cookie continuity, extract the cookies from the current session before it expires and inject them into the new session's first request.
Common Issues
Issue 1: Session Shows "expired" Even Though Timeout Has Not Passed
You check the status of a session and it shows expired, but based on your
calculations, the timeout period should not have elapsed yet. For example, you created
a session with a 300-second timeout 200 seconds ago, but the status already shows
expired.
Solution: This discrepancy is almost always caused by a mismatch between
the timeout value you specified and the timeout value actually applied by the server. The
session creation endpoint accepts timeout values between 60 and 3600 seconds in the
validator, but the controller internally clamps the value to a minimum of 10 and a maximum
of 300 seconds. If you specified a timeout of 600 seconds, the actual timeout applied was
300 seconds. Always check the expiresAt value in the session creation response
to determine the actual expiration time, rather than relying on the timeout value you sent.
The expiresAt field is the authoritative source for when the session will
expire. Additionally, ensure your server's clock is synchronized, as timestamp comparisons
depend on accurate system time on both the client and server sides.
Issue 2: SESSION_NOT_FOUND for a Recently Created Session
You receive a 404 SESSION_NOT_FOUND error when checking the status of a
session that you just created moments ago. The session creation was successful and
returned a valid session ID, but the status endpoint cannot find it.
Solution: There are three common causes for this error. First, verify that
you are using the exact session ID returned by the creation endpoint. A common mistake is
using a truncated or modified session ID due to string handling errors in your code. Print
or log the session ID immediately after creation and compare it character by character with
the ID you are sending to the status endpoint. Second, ensure you are using the same API
key for both the creation and status requests. Sessions are scoped to the account that
created them, so using a different API key (even if it belongs to the same organization)
will result in a SESSION_NOT_FOUND error. Third, if you are running multiple
instances of your application against different environments (development, staging,
production), make sure both the creation and status requests are going to the same API
endpoint.
Issue 3: Stale Status Data in High-Frequency Polling
You are polling the session status endpoint frequently and notice that the
requestCount or totalCharged values do not update immediately
after sending a request through the session. There appears to be a delay between when
the request completes and when the status reflects the updated metrics.
Solution: The requestCount and totalCharged
fields are updated in the database after each request is fully processed. If you check the
session status while a request is still being processed (before it completes), the metrics
will not yet reflect that in-progress request. This is expected behavior, not a bug. To get
accurate metrics, wait for the session request to return a response before checking the
status. If you need real-time request tracking, maintain a local counter in your application
that increments when you send a request and use the status endpoint periodically to
reconcile your local count with the server-side count. For most use cases, checking the
status after each batch of requests rather than after each individual request provides
sufficient accuracy with fewer API calls.