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

BBREClient Constructor

The BBREClient constructor creates a new instance of the BBRE client that serves as the foundation for all API communication with the BBRE (Browser-Backed Request Engine) service. When you instantiate BBREClient, you pass a configuration object that defines how the client authenticates with the API, which default operating mode and sensibility level to use, how long to wait for responses, how frequently to poll for asynchronous results, and optionally what default fingerprint and proxy settings to apply to every request. The constructor validates the provided configuration, stores the settings internally, and prepares the client for immediate use. Every subsequent method call on the client instance uses these stored defaults unless you explicitly override them at the method level. Understanding each configuration parameter and its impact on client behavior is essential for building efficient, reliable, and stealthy BBRE integrations. This page provides a complete reference for the constructor signature, every configuration parameter with its type, default value, and detailed behavior description, along with practical code examples covering common and advanced configuration patterns.

About the BBREClient Constructor

The BBREClient constructor is synchronous and does not make any network requests. It simply stores your configuration for later use. The first network call happens when you invoke a method like request(), get(), or getBalance(). This means you can safely create client instances at module load time without worrying about async initialization or connection failures. If your API key is invalid, you will only discover this when you make your first API call, not during construction. The apiKey parameter is the only required field. All other parameters have sensible defaults that work well for most use cases.

Constructor Signature

The BBREClient constructor accepts a single configuration object as its argument. This object contains all the settings that control how the client communicates with the BBRE API. The constructor is the default export of the mydisctsolver-bbre package, so you can import it directly with a simple require statement. The configuration object is optional in the sense that it defaults to an empty object, but in practice you must always provide at least the apiKey property for the client to function. Without a valid API key, every API call will fail with an authentication error.

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

const client = new BBREClient(config);

The config parameter is a plain JavaScript object with the following structure. Each property is described in detail in the sections below.

JavaScript
const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "medium",
  timeout: 120,
  pollingInterval: 2000,
  fingerprint: {},
  proxy: null
});

You can also use destructured imports if you prefer named imports over the default export. Both import styles produce the same BBREClient class.

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

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

Configuration Parameters

The configuration object supports eight parameters that control every aspect of the client behavior. The apiKey is the only required parameter. All other parameters have default values that provide a good starting point for most integrations. The following table lists every parameter with its type, requirement status, default value, and a brief description. Detailed explanations for each parameter follow in dedicated sections below the table.

Parameter Type Required Default Description
apiKey string required - Your BBRE API authentication key. Included automatically in the x-api-key header of every request sent by the client.
mode string optional "passive" Default operating mode for requests. Accepts "passive" for lightweight HTTP requests or "adaptive" for full browser automation.
sensibility string optional "medium" Default detection evasion sensitivity level. Accepts "low", "medium", or "high". Higher levels apply more evasion techniques but increase request latency.
timeout number optional 120 Default request timeout in seconds. Controls how long the client waits for a response before throwing a timeout error.
pollingInterval number optional 2000 Polling interval in milliseconds for asynchronous request result checking. Controls how frequently the client calls /request/result to check task completion.
fingerprint object optional {} Default browser fingerprint configuration applied to all requests. Includes attributes like userAgent, platform, screen, timezone, and language.
proxy object optional null Default proxy configuration for routing requests through a proxy server. Requires host and port. Optionally includes username and password for authenticated proxies.

Default Values Summary

When you create a BBREClient instance without specifying certain parameters, the constructor applies default values that are designed to work well for the majority of use cases. The following table provides a quick reference of all default values in one place. These defaults prioritize a balance between performance and stealth. Passive mode is the default because it is faster and cheaper than adaptive mode. Medium sensibility provides a good balance between speed and detection evasion. The 120-second timeout accommodates most request processing times, and the 2-second polling interval provides responsive result detection without excessive API calls.

Parameter Default Value Rationale
apiKey null No default. Must be provided by the developer. Without an API key, all requests will fail with API_KEY_REQUIRED error.
mode "passive" Passive mode is faster, uses fewer resources, and costs less per request. Most simple scraping and API proxy tasks work well in passive mode.
sensibility "medium" Medium sensibility balances request speed with detection evasion quality. Suitable for most websites without aggressive bot detection.
timeout 120 seconds Two minutes is sufficient for most passive and adaptive mode requests. Increase for complex adaptive workflows or slow target websites.
pollingInterval 2000 milliseconds Polling every 2 seconds provides responsive result detection. Most requests complete within 5-30 seconds, so 2-second polling catches results quickly.
fingerprint {} (empty object) When empty, the BBRE engine generates a random, consistent fingerprint for each request. Provide a fingerprint object to control specific browser identity attributes.
proxy null When null, requests use the BBRE engine default network routing. Provide a proxy object to route requests through your own proxy infrastructure.
JavaScript
const BBREClient = require("mydisctsolver-bbre");

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

const fullyConfiguredClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "medium",
  timeout: 120,
  pollingInterval: 2000,
  fingerprint: {},
  proxy: null
});

Both client instances above behave identically because the fully configured version explicitly sets every parameter to its default value. In practice, you only need to specify the parameters you want to change from their defaults.

apiKey Parameter

The apiKey parameter is the only required configuration option. It is a string that contains your BBRE API authentication key, which you can find in the MyDisct Solver dashboard under the API Keys section. The client stores this key internally and automatically includes it in the x-api-key header of every HTTP request sent to the BBRE API. You never need to manage authentication headers manually when using the SDK. If you do not provide an API key, the constructor will still succeed (it does not validate the key at construction time), but every subsequent API call will fail with an API_KEY_REQUIRED or INVALID_API_KEY error response.

Your API key is a sensitive credential that grants access to your BBRE account and its associated balance. Treat it like a password. Do not hardcode it directly in your source files that are committed to version control. Instead, use environment variables, a configuration file that is excluded from version control, or a secrets management service to store and retrieve your API key at runtime.

Using Environment Variables

The recommended approach for managing your API key is to store it in an environment variable and read it at runtime. This keeps the key out of your source code and allows you to use different keys for development, staging, and production environments without changing any code.

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

const client = new BBREClient({
  apiKey: process.env.BBRE_API_KEY
});

Using a Configuration File

For projects that use a configuration file pattern, you can load the API key from a JSON or JavaScript configuration file. Make sure to add the configuration file to your .gitignore to prevent accidental commits.

JavaScript
const BBREClient = require("mydisctsolver-bbre");
const config = require("./config.json");

const client = new BBREClient({
  apiKey: config.bbreApiKey
});

Validating the API Key at Startup

Since the constructor does not validate the API key, you may want to verify it early in your application startup by making a lightweight API call. The getBalance() method is ideal for this purpose because it is fast, inexpensive, and confirms that your key is valid and your account is active.

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

const client = new BBREClient({
  apiKey: process.env.BBRE_API_KEY
});

async function validateApiKey() {
  try {
    const balance = await client.getBalance();
    console.log("API key is valid. Current balance:", balance);
    return true;
  } catch (error) {
    console.error("API key validation failed:", error.message);
    return false;
  }
}

validateApiKey();

API Key Error Responses

When the API key is missing or invalid, the BBRE API returns specific error codes that help you diagnose the issue. The following table shows the error responses you may encounter related to API key authentication.

Error Code HTTP Status Cause Solution
API_KEY_REQUIRED 401 No API key was provided in the request headers. Ensure you pass the apiKey parameter in the constructor configuration object.
INVALID_API_KEY 403 The provided API key does not match any active account. Verify your API key in the MyDisct Solver dashboard. Check for typos or extra whitespace.
ACCOUNT_SUSPENDED 403 The account associated with the API key has been suspended. Contact MyDisct Solver support to resolve account suspension issues.
ACCOUNT_INACTIVE 403 The account associated with the API key is not active. Activate your account through the MyDisct Solver dashboard before making API calls.

Mode and Sensibility Configuration

The mode and sensibility parameters work together to control how the BBRE engine processes your requests. The mode determines the type of browser environment used, while sensibility controls the level of detection evasion techniques applied. Setting these at the constructor level establishes defaults for all requests made through the client instance. You can override both parameters on individual requests when you need different behavior for specific targets.

Mode Parameter

The mode parameter accepts two values: "passive" and "adaptive". Each mode represents a fundamentally different approach to processing requests through the BBRE engine.

Mode Description Best For Cost
"passive" Uses a lightweight HTTP client with browser-like headers and fingerprinting. Does not launch a full browser instance. Faster and more resource-efficient than adaptive mode. API proxying, simple page fetching, data extraction from server-rendered pages, high-volume scraping where speed matters more than JavaScript rendering. Lower cost per request
"adaptive" Launches a full browser instance with JavaScript execution, DOM rendering, and complete browser API support. Required for browser automation actions like clicking, filling forms, and taking screenshots. JavaScript-heavy websites, single-page applications, sites with bot detection that checks JavaScript execution, browser automation workflows, form submissions. Higher cost per request
JavaScript
const BBREClient = require("mydisctsolver-bbre");

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

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

Sensibility Parameter

The sensibility parameter controls the intensity of detection evasion techniques applied to each request. Higher sensibility levels make requests appear more like genuine human browser traffic but increase processing time and latency. The three available levels provide a spectrum from fast-but-basic to slow-but-thorough evasion.

Level Description Latency Impact Best For
"low" Applies basic evasion techniques including standard browser headers and basic fingerprint consistency. Minimal processing overhead. Minimal added latency Websites with no bot detection, internal APIs, development and testing environments.
"medium" Applies moderate evasion including realistic header ordering, consistent fingerprint attributes, and standard timing patterns. Good balance between speed and stealth. Moderate added latency Most public websites, e-commerce sites, content platforms, general-purpose scraping.
"high" Applies maximum evasion including human-like timing variations, advanced fingerprint consistency across all browser APIs, TLS fingerprint matching, and behavioral analysis resistance. Significant added latency Websites with aggressive bot detection (Cloudflare, PerimeterX, DataDome), financial services, social media platforms.
JavaScript
const BBREClient = require("mydisctsolver-bbre");

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

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

Combining Mode and Sensibility

The mode and sensibility parameters are independent of each other. You can use any sensibility level with either mode. However, certain combinations are more practical than others. The following table shows recommended combinations for common use cases.

Use Case Mode Sensibility Rationale
High-volume data collection "passive" "low" Maximum throughput with basic evasion. Suitable for targets without bot detection.
General web scraping "passive" "medium" Good balance of speed and stealth for most websites.
Protected website scraping "passive" "high" Maximum evasion without full browser overhead. Works for many protected sites.
JavaScript-rendered pages "adaptive" "medium" Full browser rendering with moderate evasion. Good for SPAs and dynamic content.
Browser automation on protected sites "adaptive" "high" Full browser with maximum evasion. Required for heavily protected targets with browser automation needs.

Overriding Defaults Per Request

The mode and sensibility set in the constructor serve as defaults. You can override them on any individual request by passing the mode or sensibility properties in the request options. This is useful when most of your requests use one configuration but a few specific targets need different settings.

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

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

async function mixedRequests() {
  const simpleResult = await client.get("https://api.example.com/data");

  const protectedResult = await client.get("https://protected-site.com/page", {
    mode: "adaptive",
    sensibility: "high"
  });

  console.log("Simple:", simpleResult.statusCode);
  console.log("Protected:", protectedResult.statusCode);
}

mixedRequests();

Changing Defaults After Construction

If you need to change the default mode or sensibility after creating the client, use the setDefaultMode() and setDefaultSensibility() methods. These methods update the stored defaults so that all subsequent requests use the new values.

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

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

client.setDefaultMode("adaptive");
client.setDefaultSensibility("high");

Timeout and Polling Configuration

The timeout and pollingInterval parameters control the timing behavior of the client when waiting for API responses and polling for asynchronous task results. Proper configuration of these values is important for balancing responsiveness with resource efficiency. Setting the timeout too low causes premature failures on legitimate requests that take longer to process. Setting the polling interval too low generates unnecessary API calls that consume bandwidth and may trigger rate limiting.

Timeout Parameter

The timeout parameter specifies the maximum number of seconds the client will wait for a request to complete before throwing a timeout error. This timeout applies to the entire request lifecycle, including the initial task creation, all polling attempts, and the final result retrieval. The default value of 120 seconds (2 minutes) is sufficient for most passive mode requests, which typically complete within 5 to 30 seconds. Adaptive mode requests may take longer, especially when the target website has complex JavaScript rendering or when high sensibility is enabled. For these cases, consider increasing the timeout to 180 or 240 seconds.

Scenario Recommended Timeout Rationale
Passive mode, simple pages 60 seconds Simple HTTP requests complete quickly. A shorter timeout catches failures faster.
Passive mode, complex pages 120 seconds (default) Some pages require additional processing time for header analysis and response formatting.
Adaptive mode, standard pages 120 seconds (default) Browser rendering adds overhead but most pages load within this window.
Adaptive mode, heavy JavaScript 180 seconds Single-page applications with extensive JavaScript may need extra time for full rendering.
Adaptive mode, high sensibility 240 seconds High sensibility adds human-like delays that extend total processing time significantly.
JavaScript
const BBREClient = require("mydisctsolver-bbre");

const fastClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  timeout: 60
});

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

Polling Interval Parameter

The pollingInterval parameter controls how frequently the client checks for the completion of asynchronous requests. When you call client.request() or any HTTP method like client.get(), the SDK first creates a task via POST /request/create, then repeatedly calls POST /request/result at the specified interval until the task completes, fails, or the timeout is reached. The interval is specified in milliseconds. The default value of 2000 milliseconds (2 seconds) provides a good balance between result detection speed and API call efficiency.

Polling Interval Behavior Best For
1000 (1 second) Checks every second. Detects results faster but doubles the number of polling API calls compared to the default. Time-sensitive applications where every second of latency matters.
2000 (2 seconds, default) Checks every 2 seconds. Good balance between responsiveness and API call efficiency. Most applications. Recommended for general use.
5000 (5 seconds) Checks every 5 seconds. Reduces API call volume significantly but adds up to 5 seconds of latency to result detection. Batch processing where individual request latency is less important than overall throughput and API call efficiency.
JavaScript
const BBREClient = require("mydisctsolver-bbre");

const responsiveClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  pollingInterval: 1000
});

const efficientClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  pollingInterval: 5000
});

Timeout and Polling Interaction

The timeout and polling interval work together to determine the maximum number of polling attempts the client will make before giving up. For example, with a 120-second timeout and a 2000-millisecond polling interval, the client will make approximately 60 polling attempts before timing out. If you increase the polling interval to 5000 milliseconds with the same timeout, the client will make approximately 24 polling attempts. Consider both values together when tuning your client for specific workloads.

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

const batchClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  timeout: 300,
  pollingInterval: 5000
});

async function batchProcess(urls) {
  const results = [];
  for (const url of urls) {
    try {
      const result = await batchClient.get(url);
      results.push({ url, status: result.statusCode });
    } catch (error) {
      results.push({ url, error: error.message });
    }
  }
  return results;
}

batchProcess([
  "https://example.com/page1",
  "https://example.com/page2",
  "https://example.com/page3"
]);

Fingerprint Configuration

The fingerprint parameter allows you to define a default browser fingerprint that is applied to all requests made through the client. A browser fingerprint is a collection of attributes that identify the browser environment, including the user agent string, operating system platform, screen resolution, timezone, language preferences, and WebGL renderer information. When you provide a fingerprint configuration, the BBRE engine uses these values to construct a consistent browser identity for your requests. This is important for websites that track and correlate fingerprint attributes across multiple requests to detect automated traffic.

When the fingerprint parameter is set to an empty object (the default), the BBRE engine generates a random but internally consistent fingerprint for each request. This means each request appears to come from a different browser, which is suitable for independent, stateless requests. When you provide specific fingerprint attributes, those attributes remain consistent across all requests, which is important for session-based workflows where the target website expects the same browser identity throughout the session.

Fingerprint Object Structure

The fingerprint object supports the following attributes. All attributes are optional. Any attribute you do not specify will be generated automatically by the BBRE engine to maintain internal consistency with the attributes you do provide.

Attribute Type Description
userAgent string The browser user agent string. Should match a real browser version for consistency with other fingerprint attributes.
platform string The operating system platform identifier. Common values: "Win32", "MacIntel", "Linux x86_64".
screen object Screen resolution object with width and height properties (both numbers). Common values: { width: 1920, height: 1080 }.
timezone string IANA timezone identifier. Examples: "America/New_York", "Europe/London", "Asia/Tokyo".
language string Browser language preference. Examples: "en-US", "de-DE", "ja-JP".
webgl object WebGL renderer information with vendor and renderer string properties. Used by advanced fingerprinting scripts.
JavaScript
const BBREClient = require("mydisctsolver-bbre");

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  fingerprint: {
    platform: "Win32",
    timezone: "America/New_York",
    language: "en-US",
    screen: { width: 1920, height: 1080 }
  }
});

Full Fingerprint Example

The following example shows a complete fingerprint configuration with all available attributes specified. This level of detail is useful when targeting websites with sophisticated fingerprinting that checks multiple browser attributes for consistency.

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

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  sensibility: "high",
  fingerprint: {
    userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    platform: "Win32",
    screen: { width: 1920, height: 1080 },
    timezone: "America/Chicago",
    language: "en-US",
    webgl: {
      vendor: "Google Inc. (NVIDIA)",
      renderer: "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 Direct3D11 vs_5_0 ps_5_0)"
    }
  }
});

Updating Fingerprint After Construction

You can change the default fingerprint at any time using the setDefaultFingerprint() method. This is useful for rotating fingerprints between batches of requests or adapting to different target website requirements.

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

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

client.setDefaultFingerprint({
  platform: "MacIntel",
  timezone: "Europe/London",
  language: "en-GB",
  screen: { width: 2560, height: 1440 }
});

async function fetchWithFingerprint() {
  const result = await client.get("https://example.com/data");
  console.log("Status:", result.statusCode);
}

fetchWithFingerprint();

Proxy Configuration

The proxy parameter configures a default proxy server that the BBRE engine uses to route all requests. When a proxy is configured, the BBRE engine sends your requests through the specified proxy server instead of using its default network routing. This is useful for geo-targeting (accessing content from specific geographic locations), IP rotation (distributing requests across multiple IP addresses), and bypassing IP-based rate limiting or blocking. The proxy configuration is applied to every request made through the client unless overridden at the request level.

Proxy Object Structure

The proxy object requires host and port properties. For authenticated proxies, include username and password properties. The BBRE engine supports HTTP, HTTPS, and SOCKS5 proxy protocols.

Property Type Required Description
host string required The proxy server hostname or IP address. Examples: "proxy.example.com", "192.168.1.100".
port number required The proxy server port number. Common values: 8080, 3128, 1080.
username string optional Username for proxy authentication. Required only for authenticated proxy servers.
password string optional Password for proxy authentication. Required only for authenticated proxy servers.

Basic Proxy Configuration

The simplest proxy configuration requires only the host and port. This works for proxy servers that do not require authentication.

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

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  proxy: {
    host: "proxy.example.com",
    port: 8080
  }
});

Authenticated Proxy Configuration

For proxy servers that require authentication, include the username and password in the proxy configuration object. The BBRE engine sends these credentials to the proxy server using the appropriate authentication mechanism.

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

const client = new BBREClient({
  apiKey: "YOUR_API_KEY",
  proxy: {
    host: "us-residential.proxy.com",
    port: 8080,
    username: "proxyuser",
    password: "proxypass"
  }
});

Proxy with Environment Variables

For production deployments, store proxy credentials in environment variables alongside your API key. This keeps sensitive information out of your source code.

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

const client = new BBREClient({
  apiKey: process.env.BBRE_API_KEY,
  proxy: {
    host: process.env.PROXY_HOST,
    port: parseInt(process.env.PROXY_PORT),
    username: process.env.PROXY_USER,
    password: process.env.PROXY_PASS
  }
});

Updating Proxy After Construction

Use the setDefaultProxy() method to change the proxy configuration after creating the client. Pass null to remove the proxy and revert to the BBRE engine default network routing.

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

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

client.setDefaultProxy({
  host: "eu-datacenter.proxy.com",
  port: 3128,
  username: "dcuser",
  password: "dcpass"
});

async function fetchWithProxy() {
  const result = await client.get("https://eu-only-site.com/data");
  console.log("Status:", result.statusCode);
}

client.setDefaultProxy(null);

fetchWithProxy();

Multiple Client Instances

You can create multiple BBREClient instances with different configurations and use them simultaneously in the same application. This pattern is useful when you need to interact with different types of targets that require different mode, sensibility, proxy, or fingerprint settings. Each client instance maintains its own independent configuration and does not share state with other instances. Creating multiple clients does not consume additional server resources because the constructor does not establish any persistent connections. Server resources are only consumed when you make actual API calls.

Separate Clients for Different Targets

A common pattern is to create one client for fast, high-volume scraping of unprotected targets and another client for careful, stealthy access to protected targets. This allows you to optimize each client for its specific workload without compromising on either speed or stealth.

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

const fastClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "passive",
  sensibility: "low",
  timeout: 60,
  pollingInterval: 1000
});

const stealthClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  mode: "adaptive",
  sensibility: "high",
  timeout: 240,
  pollingInterval: 3000,
  fingerprint: {
    platform: "Win32",
    timezone: "America/New_York",
    language: "en-US",
    screen: { width: 1920, height: 1080 }
  }
});

async function scrapeMultipleTargets() {
  const publicData = await fastClient.get("https://public-api.example.com/data");
  console.log("Public data:", publicData.statusCode);

  const protectedData = await stealthClient.get("https://protected-site.com/data");
  console.log("Protected data:", protectedData.statusCode);
}

scrapeMultipleTargets();

Separate Clients for Different Regions

When you need to access content from different geographic regions, create separate clients with region-specific proxy configurations. Each client routes its requests through a proxy in the target region, ensuring you receive localized content.

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

const usClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  proxy: {
    host: "us-residential.proxy.com",
    port: 8080,
    username: "proxyuser",
    password: "proxypass"
  },
  fingerprint: {
    timezone: "America/New_York",
    language: "en-US"
  }
});

const euClient = new BBREClient({
  apiKey: "YOUR_API_KEY",
  proxy: {
    host: "eu-residential.proxy.com",
    port: 8080,
    username: "proxyuser",
    password: "proxypass"
  },
  fingerprint: {
    timezone: "Europe/Berlin",
    language: "de-DE"
  }
});

async function compareRegionalPricing() {
  const usPrice = await usClient.get("https://shop.example.com/product/123");
  const euPrice = await euClient.get("https://shop.example.com/product/123");

  console.log("US response:", usPrice.statusCode);
  console.log("EU response:", euPrice.statusCode);
}

compareRegionalPricing();

Client Factory Pattern

For applications that create many client instances with shared base configuration, use a factory function to reduce code duplication. The factory function accepts override parameters and merges them with your base configuration.

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

function createClient(overrides) {
  const baseConfig = {
    apiKey: process.env.BBRE_API_KEY,
    mode: "passive",
    sensibility: "medium",
    timeout: 120
  };

  return new BBREClient(Object.assign({}, baseConfig, overrides));
}

const defaultClient = createClient({});
const adaptiveClient = createClient({ mode: "adaptive", sensibility: "high" });
const fastClient = createClient({ sensibility: "low", timeout: 60 });

async function useFactoryClients() {
  const result1 = await defaultClient.get("https://example.com/page1");
  const result2 = await adaptiveClient.get("https://protected.example.com/page2");
  const result3 = await fastClient.get("https://simple-api.example.com/data");

  console.log("Default:", result1.statusCode);
  console.log("Adaptive:", result2.statusCode);
  console.log("Fast:", result3.statusCode);
}

useFactoryClients();

Code Examples

The following examples demonstrate various constructor configurations for real-world scenarios. Each example shows a complete, runnable code snippet that creates a client with a specific configuration and makes a request to verify the setup works correctly.

Minimal Configuration

The simplest possible configuration. Only the API key is provided, and all other parameters use their default values. This is the recommended starting point for new integrations.

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

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

async function minimalExample() {
  const result = await client.get("https://httpbin.org/get");
  console.log("Status:", result.statusCode);
  console.log("Body:", result.body);
}

minimalExample();

Web Scraping Configuration

A configuration optimized for web scraping with moderate stealth, a custom fingerprint for consistency, and a proxy for IP rotation.

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

const scraper = new BBREClient({
  apiKey: process.env.BBRE_API_KEY,
  mode: "passive",
  sensibility: "medium",
  timeout: 90,
  pollingInterval: 2000,
  fingerprint: {
    platform: "Win32",
    language: "en-US",
    screen: { width: 1920, height: 1080 }
  },
  proxy: {
    host: "rotating.proxy.com",
    port: 8080,
    username: "scraper",
    password: "scraperpass"
  }
});

async function scrapeProducts() {
  const result = await scraper.get("https://shop.example.com/products");
  console.log("Products page status:", result.statusCode);
  console.log("Content length:", result.body.length);
}

scrapeProducts();

High-Security Target Configuration

A configuration designed for accessing websites with aggressive bot detection. Uses adaptive mode with high sensibility, extended timeout, and a complete fingerprint profile.

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

const secureClient = new BBREClient({
  apiKey: process.env.BBRE_API_KEY,
  mode: "adaptive",
  sensibility: "high",
  timeout: 240,
  pollingInterval: 3000,
  fingerprint: {
    userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    platform: "Win32",
    screen: { width: 1920, height: 1080 },
    timezone: "America/Los_Angeles",
    language: "en-US",
    webgl: {
      vendor: "Google Inc. (NVIDIA)",
      renderer: "ANGLE (NVIDIA, NVIDIA GeForce RTX 3070 Direct3D11 vs_5_0 ps_5_0)"
    }
  },
  proxy: {
    host: "us-residential.proxy.com",
    port: 8080,
    username: "premium",
    password: "premiumpass"
  }
});

async function accessProtectedSite() {
  const result = await secureClient.get("https://heavily-protected-site.com/data");
  console.log("Status:", result.statusCode);
  console.log("Response received successfully");
}

accessProtectedSite();

API Monitoring Configuration

A lightweight configuration for monitoring API endpoints. Uses low sensibility for speed and a short timeout to detect failures quickly.

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

const monitor = new BBREClient({
  apiKey: process.env.BBRE_API_KEY,
  mode: "passive",
  sensibility: "low",
  timeout: 30,
  pollingInterval: 1000
});

async function checkEndpointHealth(endpoints) {
  const results = [];

  for (const endpoint of endpoints) {
    const startTime = Date.now();
    try {
      const result = await monitor.get(endpoint);
      const duration = Date.now() - startTime;
      results.push({
        url: endpoint,
        status: result.statusCode,
        responseTime: duration,
        healthy: result.statusCode >= 200 && result.statusCode < 400
      });
    } catch (error) {
      const duration = Date.now() - startTime;
      results.push({
        url: endpoint,
        error: error.message,
        responseTime: duration,
        healthy: false
      });
    }
  }

  return results;
}

checkEndpointHealth([
  "https://api.example.com/health",
  "https://api.example.com/status",
  "https://api.example.com/version"
]).then(results => {
  console.log("Health check results:", JSON.stringify(results, null, 2));
});

Batch Processing Configuration

A configuration optimized for processing large batches of URLs. Uses a longer timeout and wider polling interval to reduce API call overhead during batch operations.

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

const batchClient = new BBREClient({
  apiKey: process.env.BBRE_API_KEY,
  mode: "passive",
  sensibility: "medium",
  timeout: 300,
  pollingInterval: 5000
});

async function processBatch(urls, concurrency) {
  const results = [];
  const queue = [...urls];

  async function worker() {
    while (queue.length > 0) {
      const url = queue.shift();
      try {
        const result = await batchClient.get(url);
        results.push({ url, status: result.statusCode, bodyLength: result.body.length });
      } catch (error) {
        results.push({ url, error: error.message });
      }
    }
  }

  const workers = [];
  for (let i = 0; i < concurrency; i++) {
    workers.push(worker());
  }
  await Promise.all(workers);

  return results;
}

processBatch([
  "https://example.com/page1",
  "https://example.com/page2",
  "https://example.com/page3",
  "https://example.com/page4",
  "https://example.com/page5"
], 3).then(results => {
  console.log("Batch complete:", results.length, "results");
});

Best Practices

Store API Keys in Environment Variables

Never hardcode your API key directly in source files. Use environment variables (process.env.BBRE_API_KEY) or a secrets management service to keep your credentials secure. Add any configuration files containing API keys to your .gitignore to prevent accidental commits to version control.

Start with Default Settings

Begin with the minimal configuration (just apiKey) and only add additional parameters when you have a specific reason to change the defaults. The default values of passive mode, medium sensibility, 120-second timeout, and 2-second polling interval work well for the majority of use cases. Adjust individual parameters based on the specific requirements of your target websites and workflows.

Reuse Client Instances

Create your BBREClient instance once and reuse it across your application. There is no benefit to creating a new client for every request. The client is stateless (it does not maintain connections or sessions), so a single instance can safely handle concurrent requests from multiple parts of your application. Create multiple instances only when you need fundamentally different configurations for different target types.

Match Timeout to Your Workload

Set the timeout based on the expected processing time of your requests. For passive mode with low sensibility, 60 seconds is usually sufficient. For adaptive mode with high sensibility, increase the timeout to 180-240 seconds to avoid premature timeout errors on legitimate requests that take longer to process due to human-like timing delays and full browser rendering.

Validate Your API Key Early

Since the constructor does not validate the API key, call client.getBalance() early in your application startup to verify that the key is valid and the account is active. This catches configuration errors before they cause failures in your main workflow. The balance check is a lightweight operation that confirms API connectivity and authentication in a single call.

Use Fingerprint Consistency for Session Workflows

When making multiple requests to the same website (especially with sessions), provide a consistent fingerprint configuration in the constructor. Websites that track browser fingerprints will flag requests that suddenly change their user agent, screen resolution, or timezone between requests. A consistent fingerprint across all requests from the same client instance helps maintain a believable browser identity.

Common Issues

API Key Not Provided or Invalid

Symptom: Every API call fails with API_KEY_REQUIRED or INVALID_API_KEY error.
Cause: The apiKey parameter was not provided in the constructor, the environment variable is not set, or the key contains extra whitespace or incorrect characters.
Solution: Verify that the apiKey value is a non-empty string. Check that your environment variable is correctly set by logging process.env.BBRE_API_KEY (redact the output after verification). Copy the API key directly from the MyDisct Solver dashboard to avoid typos.

Timeout Errors on Adaptive Mode Requests

Symptom: Requests fail with a timeout error even though the target website is accessible.
Cause: The default 120-second timeout is too short for adaptive mode requests with high sensibility. Full browser rendering combined with human-like timing delays can push processing time beyond 2 minutes.
Solution: Increase the timeout parameter to 180 or 240 seconds when using adaptive mode with high sensibility. Monitor actual request processing times to find the optimal timeout value for your specific targets.

Invalid Mode or Sensibility Value

Symptom: Requests fail with INVALID_MODE or INVALID_SENSIBILITY error.
Cause: The mode parameter contains a value other than "passive" or "adaptive", or the sensibility parameter contains a value other than "low", "medium", or "high". These values are case-sensitive.
Solution: Ensure you use the exact string values documented above. Check for capitalization errors (use "passive" not "Passive"). Verify that configuration values loaded from environment variables or config files match the expected format.

Proxy Connection Failures

Symptom: Requests fail with connection errors when a proxy is configured.
Cause: The proxy host is unreachable, the port is incorrect, or the authentication credentials are wrong. The proxy server may also be down or blocking connections from the BBRE engine IP addresses.
Solution: Test your proxy configuration independently before using it with the BBRE SDK. Verify the host, port, username, and password values. Ensure the proxy server allows connections from external sources. Try removing the proxy configuration temporarily to confirm that the issue is proxy-related and not an API or target website problem.

Inconsistent Fingerprint Causing Detection

Symptom: Requests are blocked or return CAPTCHA challenges despite using high sensibility.
Cause: The fingerprint configuration contains inconsistent attributes. For example, a Windows user agent string combined with a "MacIntel" platform value, or a mobile screen resolution with a desktop user agent.
Solution: Ensure all fingerprint attributes are internally consistent. If you specify a Windows user agent, use "Win32" as the platform. Match screen resolutions to the device type implied by the user agent. When in doubt, provide fewer fingerprint attributes and let the BBRE engine generate consistent values for the attributes you omit.