### Installation Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Install the FeatBit Node.js Server-Side SDK using npm. ```APIDOC ## Installation Install the SDK from npm. ```bash npm install --save @featbit/node-server-sdk ``` ``` -------------------------------- ### Install FeatBit Node.js Server-Side SDK Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/examples/console-app/README.md Run this command to install the SDK dependencies. ```bash npm install ``` -------------------------------- ### Run CommonJS Example Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/examples/console-app/README.md Execute this command to run the example using CommonJS. ```bash npm run cjs ``` -------------------------------- ### Quick Start: Initialize and Evaluate Feature Flags Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Demonstrates basic usage of the SDK, including initialization, user creation, and evaluating boolean feature flags. Ensure the SDK is initialized before use and events are flushed on exit. ```javascript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; // setup SDK options const fbClient = new FbClientBuilder() .sdkKey("your_sdk_key") .streamingUri('ws://localhost:5100') .eventsUri("http://localhost:5100") .build(); (async () => { // wait for the SDK to be initialized try { await fbClient.waitForInitialization(); } catch(err) { // failed to initialize the SDK console.log(err); } // flag to be evaluated const flagKey = "game-runner"; // create a user const user = new UserBuilder('a-unique-key-of-user') .name('bob') .custom('sex', 'female') .custom('age', 18) .build(); // evaluate a feature flag for a given user const boolVariation = await fbClient.boolVariation(flagKey, user, false); console.log(`flag '${flagKey}' returns ${boolVariation} for user ${user.Key}`); // evaluate a boolean flag for a given user with evaluation detail const boolVariationDetail = await fbClient.boolVariationDetail(flagKey, user, false); console.log(`flag '${flagKey}' returns ${boolVariationDetail.value} for user ${user.Key}` + `Reason Kind: ${boolVariationDetail.kind}, Reason Description: ${boolVariationDetail.reason}`); // make sure the events are flushed before exit await fbClient.close(); })(); ``` -------------------------------- ### Install FeatBit Node.js SDK Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Install the latest stable version of the FeatBit Node.js Server-Side SDK using npm. ```bash npm install --save @featbit/node-server-sdk ``` -------------------------------- ### Run ES Module Example Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/examples/console-app/README.md Execute this command to run the example using ES modules and TypeScript. ```bash npm run esm ``` -------------------------------- ### Use Custom Logger Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Integrates a custom logger that implements the ILogger interface. A BasicLogger is provided as an example, which can be configured with a level and destination. ```javascript const logger = new BasicLogger({ level: 'debug', destination: console.log }); const fbClient = new FbClientBuilder() .logger(logger) ... .build(); // or const options = { ... logger: logger } const fbClient = new FbClientBuilder(options).build(); ``` -------------------------------- ### Evaluate String Feature Flags with FeatBit SDK Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Use stringVariation to get a string flag's value and stringVariationDetail for detailed evaluation results. Ensure the SDK client is initialized before use. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-456") .name("Bob") .custom("country", "FR") .build(); // Get button color variant const buttonColor = await fbClient.stringVariation("button-color", user, "blue"); console.log(`Button color: ${buttonColor}`); // Output: Button color: green // Get detailed evaluation for A/B test variant const variantDetail = await fbClient.stringVariationDetail("homepage-layout", user, "control"); console.log(`Layout variant: ${variantDetail.value}`); console.log(`Assignment reason: ${variantDetail.kind} - ${variantDetail.reason}`); // Output: // Layout variant: variant-b // Assignment reason: RuleMatch - match rule "European Users" ``` -------------------------------- ### Evaluate JSON Feature Flags with FeatBit SDK Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Use jsonVariation to get a JSON flag value and jsonVariationDetail for detailed evaluation. Provide a default JSON object for cases where the flag is not found or evaluation fails. The SDK client must be initialized. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-101") .name("Diana") .custom("subscription", "pro") .build(); // Default configuration object const defaultConfig = { maxItems: 10, enableCache: false, theme: "light" }; // Get feature configuration as JSON const config = await fbClient.jsonVariation("dashboard-config", user, defaultConfig); console.log("Dashboard configuration:", JSON.stringify(config, null, 2)); // Output: // Dashboard configuration: { // "maxItems": 50, // "enableCache": true, // "theme": "dark" // } // Use the configuration const { maxItems, enableCache, theme } = config; console.log(`Loading ${maxItems} items, cache: ${enableCache}, theme: ${theme}`) ``` -------------------------------- ### Initialize FbClient Using Streaming Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Configure and build an FbClient instance using WebSocket streaming for data synchronization. Requires setting the SDK key, streaming URI, and events URI. ```javascript import { FbClientBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your_sdk_key") .streamingUri('ws://localhost:5100') .eventsUri("http://localhost:5100") .build(); ``` -------------------------------- ### FbClientBuilder - Creating the Client Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Use `FbClientBuilder` to create and configure a FeatBit client instance. It's recommended to create a single client instance for the lifetime of your application. ```APIDOC ## FbClientBuilder - Creating the Client The `FbClientBuilder` is the primary way to create and configure a FeatBit client instance. It uses the builder pattern to set configuration options and returns an `IFbClient` when `build()` is called. Applications should create a single client instance for the lifetime of the application. ```typescript import { FbClientBuilder, DataSyncModeEnum } from "@featbit/node-server-sdk"; // Create client with WebSocket streaming (default mode) const streamingClient = new FbClientBuilder() .sdkKey("your-environment-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .startWaitTime(5000) .build(); // Create client with HTTP polling const pollingClient = new FbClientBuilder() .sdkKey("your-environment-sdk-key") .dataSyncMode(DataSyncModeEnum.POLLING) .pollingUri("http://localhost:5100") .eventsUri("http://localhost:5100") .pollingInterval(30000) .build(); // Wait for client initialization try { await streamingClient.waitForInitialization(); console.log("Client initialized successfully"); } catch (err) { console.error("Failed to initialize:", err); } ``` ``` -------------------------------- ### Initialize SDK with JSON Bootstrap Data Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Initializes the SDK in offline mode using a JSON file containing flag and segment data. This file can be obtained from the FeatBit server. ```javascript import { FbClientBuilder } from "@featbit/node-server-sdk"; import fs from 'fs'; let data: string = ''; try { data = fs.readFileSync('path_to_the_json_file', 'utf8'); } catch (err) { console.error(err); } const fbClient = new FbClientBuilder() .offline(false) .useJsonBootstrapProvider(data) .build(); ``` -------------------------------- ### Create FeatBit Client with WebSocket Streaming Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Create a FeatBit client instance using WebSocket streaming for real-time data synchronization. Ensure you replace 'your-environment-sdk-key' with your actual SDK key. ```typescript import { FbClientBuilder, DataSyncModeEnum } from "@featbit/node-server-sdk"; // Create client with WebSocket streaming (default mode) const streamingClient = new FbClientBuilder() .sdkKey("your-environment-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .startWaitTime(5000) .build(); ``` -------------------------------- ### Create Hybrid Client with Bootstrap Data Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Initialize a hybrid FeatBit client that uses bootstrap data for fast startup while connecting to the FeatBit server for real-time updates. Configure streaming and event URIs. ```typescript // Online client with bootstrap for fast startup const hybridClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .useJsonBootstrapProvider(bootstrapData) // Use bootstrap while connecting .build(); ``` -------------------------------- ### Create FeatBit Client with HTTP Polling Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Create a FeatBit client instance using HTTP polling for data synchronization. Configure the polling interval as needed. Replace 'your-environment-sdk-key' with your actual SDK key. ```typescript import { FbClientBuilder, DataSyncModeEnum } from "@featbit/node-server-sdk"; // Create client with HTTP polling const pollingClient = new FbClientBuilder() .sdkKey("your-environment-sdk-key") .dataSyncMode(DataSyncModeEnum.POLLING) .pollingUri("http://localhost:5100") .eventsUri("http://localhost:5100") .pollingInterval(30000) .build(); ``` -------------------------------- ### Configure and Manage FeatBit Client Resources Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Configure FeatBit client settings such as flush interval and maximum event queue size. Implement graceful shutdown using SIGTERM to flush events and close connections. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .flushInterval(2000) // Flush events every 2 seconds .maxEventsInQueue(10000) // Maximum events before auto-flush .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-606").name("Ivy").build(); // Evaluate flags and track events const value = await fbClient.boolVariation("my-feature", user, false); fbClient.track(user, "feature-used"); // Manually flush events with callback await fbClient.flush((success) => { if (success) { console.log("Events flushed successfully"); } else { console.error("Failed to flush events"); } }); // Graceful shutdown - flushes events and closes connections process.on("SIGTERM", async () => { console.log("Shutting down..."); await fbClient.close(); console.log("FeatBit client closed"); process.exit(0); }); ``` -------------------------------- ### Fetch Bootstrap Data Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Fetch bootstrap data from the FeatBit server to enable offline evaluation or fast startup. This data is used to initialize the client locally. ```bash curl -H "Authorization: your-env-secret" \ http://localhost:5100/api/public/sdk/server/latest-all > featbit-bootstrap.json ``` -------------------------------- ### Initialize FbClient Using Polling Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Configure and build an FbClient instance using polling for data synchronization. Specify the data sync mode, polling URI, events URI, and polling interval. ```javascript import { FbClientBuilder, DateSyncMode } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your_sdk_key") .dataSyncMode(DateSyncMode.POLLING) .pollingUri('http://localhost:5100') .eventsUri("http://localhost:5100") .pollingInterval(10000) .build(); ``` -------------------------------- ### Login to npm Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/MEMO.md Log in to your npm account before publishing. This command prompts for your username, password, and email. ```bash npm login ``` -------------------------------- ### Create Test Client with TestData Integration Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Initialize a FeatBit client for testing using the TestData integration. This allows control over flag values without connecting to a FeatBit server. Ensure TestData and FlagBuilder are imported from integrations. ```typescript import { FbClientBuilder, UserBuilder, integrations } from "@featbit/node-server-sdk"; const { TestData, FlagBuilder } = integrations; // Create a TestData instance const testData = new TestData(); // Build a test flag const testFlag = new FlagBuilder() .key("test-feature") .variationType("boolean") .variations([ { id: "true-var", value: "true" }, { id: "false-var", value: "false" } ]) .isEnabled(true) .fallthrough({ dispatchKey: "", includedInExpt: true, variations: [{ id: "true-var", rollout: [0, 1], exptRollout: 1 }] }) .build(); // Create client using test data synchronizer const testClient = new FbClientBuilder() .sdkKey("test-key") .dataSynchronizer(testData.getFactory()) .build(); await testClient.waitForInitialization(); const user = new UserBuilder("test-user").build(); // Evaluate the test flag const result = await testClient.boolVariation("test-feature", user, false); console.log(`Test feature: ${result}`); // Update the flag during test await testData.update( new FlagBuilder() .key("test-feature") .isEnabled(false) .build() ); ``` -------------------------------- ### Configure Logging with FeatBit Node.js SDK Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Configure logging using the built-in `BasicLogger` or provide a custom logger implementation. Log levels include `debug`, `info`, `warn`, `error`, and `none`. ```typescript import { FbClientBuilder, BasicLogger } from "@featbit/node-server-sdk"; import { format } from "util"; // Use built-in log level configuration const clientWithLogLevel = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .logLevel("debug") .build(); // Use custom BasicLogger with custom destination const customLogger = new BasicLogger({ level: "info", name: "MyApp-FeatBit", destination: (msg) => { // Send to your logging service console.log(`[${new Date().toISOString()}] ${msg}`); }, formatter: format }); const clientWithCustomLogger = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .logger(customLogger) .build(); // Use Winston logger (compatible with ILogger interface) // import winston from "winston"; // const winstonLogger = winston.createLogger({ level: "info", ... }); // .logger(winstonLogger) ``` -------------------------------- ### Create Offline Client with Bootstrap Data Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Initialize an offline FeatBit client using bootstrap data loaded from a JSON file. This allows for flag evaluation without network connectivity. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; import fs from "fs"; // Load bootstrap data from file const bootstrapData = fs.readFileSync("./featbit-bootstrap.json", "utf8"); // Create offline client with bootstrap data const offlineClient = new FbClientBuilder() .offline(true) .useJsonBootstrapProvider(bootstrapData) .build(); await offlineClient.waitForInitialization(); const user = new UserBuilder("user-505").name("Henry").build(); // Evaluate flags using local bootstrap data (no network calls) const feature = await offlineClient.boolVariation("my-feature", user, false); console.log(`Feature enabled: ${feature}`); ``` -------------------------------- ### Bulk Evaluate All Feature Flags with FeatBit SDK Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Use getAllVariations to retrieve all feature flag evaluations for a user. This is useful for bootstrapping front-end applications with flag values. The SDK client must be initialized. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-202") .name("Eve") .build(); // Get all flag variations for bootstrapping a frontend const allFlags = await fbClient.getAllVariations(user); // Convert to a simple key-value object for frontend const flagValues: Record = {}; allFlags.forEach(detail => { flagValues[detail.flagKey] = detail.value; console.log(`${detail.flagKey}: ${detail.value} (${detail.kind})`); }); // Output: // feature-x: true (TargetMatch) // button-color: blue (FallThrough) // max-items: 50 (RuleMatch) // Send to frontend as bootstrap data const bootstrapJson = JSON.stringify(flagValues); ``` -------------------------------- ### Wait for FeatBit Client Initialization Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Asynchronously wait for the FeatBit client to initialize. This is crucial before evaluating feature flags to ensure data is loaded. ```typescript // Wait for client initialization try { await streamingClient.waitForInitialization(); console.log("Client initialized successfully"); } catch (err) { console.error("Failed to initialize:", err); } ``` -------------------------------- ### Enable Offline Mode Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Initializes the SDK in offline mode, preventing remote calls to FeatBit. This is useful for testing or when network connectivity is not guaranteed. ```javascript import { FbClientBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .offline(true) .build(); ``` -------------------------------- ### Fetch Bootstrap Data using cURL Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Fetches the latest flag and segment data from the FeatBit evaluation server using cURL. Replace the URL and authorization header with your specific details. ```shell # replace http://localhost:5100 with your evaluation server url curl -H "Authorization: " http://localhost:5100/api/public/sdk/server/latest-all > featbit-bootstrap.json ``` -------------------------------- ### Create User with UserBuilder Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Constructs a user object with built-in and custom attributes using UserBuilder. The 'key' is mandatory and must uniquely identify the user. ```javascript import { UserBuilder } from "@featbit/node-server-sdk"; const bob = new UserBuilder("unique_key_for_bob") .name("Bob") .custom('age', 18) .custom('country', 'FR') .build(); ``` -------------------------------- ### Publish Node Module Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/MEMO.md Publish your Node.js module to npm with public access. Ensure you have logged in first. ```bash npm publish --access public ``` -------------------------------- ### Create User Object Directly Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Alternatively, create a user object directly by defining its properties, including a unique key, name, and an array of custom properties. ```typescript // Alternatively, create a user object directly const directUser: IUser = { key: "user-67890", name: "Bob", customizedProperties: [ { name: "email", value: "bob@example.com" }, { name: "plan", value: "free" }, { name: "country", value: "UK" } ] }; ``` -------------------------------- ### Set Log Level Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Configures the SDK's logging level. 'debug' will output detailed logs. This can be set either directly on the builder or within an options object. ```javascript const fbClient = new FbClientBuilder() .logLevel('debug') ... .build(); // or const options = { ... logLevel: 'debug' } const fbClient = new FbClientBuilder(options).build(); ``` -------------------------------- ### Listen for FeatBit Flag Updates in Node.js Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Register event listeners using the Node.js EventEmitter `on()` method to react to flag updates in real-time without restarting the application. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); const user = new UserBuilder("user-404").name("Grace").build(); // Listen for successful initialization fbClient.on("ready", () => { console.log("FeatBit client is ready!"); }); // Listen for initialization failure fbClient.on("failed", () => { console.error("FeatBit client failed to initialize"); }); // Listen for any errors fbClient.on("error", (err) => { console.error("FeatBit error:", err); }); // Listen for updates to any flag fbClient.on("update", async (event) => { console.log(`Flag "${event.key}" was updated`); // Re-evaluate the flag for current users }); // Listen for updates to a specific flag fbClient.on("update:checkout-enabled", async () => { const newValue = await fbClient.boolVariation("checkout-enabled", user, false); console.log(`checkout-enabled changed to: ${newValue}`); // Update application state accordingly }); await fbClient.waitForInitialization(); ``` -------------------------------- ### Track Custom Events with FeatBit Node.js SDK Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Use the `track` method to send custom events for A/B testing. Call this after evaluating a feature flag. The optional metric value defaults to 1.0. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-303") .name("Frank") .custom("segment", "power-user") .build(); // First evaluate the flag being tested const checkoutVariant = await fbClient.stringVariation("checkout-flow", user, "control"); // Track a conversion event (default metric value of 1.0) fbClient.track(user, "checkout-completed"); // Track a revenue event with custom metric value fbClient.track(user, "purchase-revenue", 99.99); // Track a page view event fbClient.track(user, "product-page-viewed"); // Track engagement time in seconds fbClient.track(user, "session-duration", 245); ``` -------------------------------- ### Evaluate Number Feature Flags with FeatBit SDK Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Use numberVariation to retrieve a numeric flag value and numberVariationDetail for detailed evaluation. The SDK client must be initialized. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-789") .name("Charlie") .custom("tier", "enterprise") .build(); // Get API rate limit for user const rateLimit = await fbClient.numberVariation("api-rate-limit", user, 100); console.log(`Rate limit: ${rateLimit} requests/minute`); // Output: Rate limit: 1000 requests/minute // Get discount percentage with evaluation details const discountDetail = await fbClient.numberVariationDetail("discount-percentage", user, 0); console.log(`Discount: ${discountDetail.value}%`); console.log(`Reason: ${discountDetail.kind}`); // Output: // Discount: 15% // Reason: FallThrough ``` -------------------------------- ### Build User with Custom Attributes Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Create a user object with a unique key, name, and custom attributes using the UserBuilder. Custom attributes are used for targeting rules. ```typescript import { UserBuilder, IUser } from "@featbit/node-server-sdk"; // Build a user with custom attributes using the builder const user = new UserBuilder("user-12345") .name("Alice") .custom("email", "alice@example.com") .custom("plan", "premium") .custom("country", "US") .custom("age", "28") .build(); ``` -------------------------------- ### UserBuilder - Creating Users Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt The `UserBuilder` is used to create user objects for feature flag evaluation. Users require a unique `key` and can optionally include a `name` and custom attributes for targeting. ```APIDOC ## UserBuilder - Creating Users The `UserBuilder` creates user objects for flag evaluation. Users must have a unique `key` identifier and can include a `name` and custom attributes. Custom attributes can be used in targeting rules to control which variation a user receives. ```typescript import { UserBuilder, IUser } from "@featbit/node-server-sdk"; // Build a user with custom attributes using the builder const user = new UserBuilder("user-12345") .name("Alice") .custom("email", "alice@example.com") .custom("plan", "premium") .custom("country", "US") .custom("age", "28") .build(); // Alternatively, create a user object directly const directUser: IUser = { key: "user-67890", name: "Bob", customizedProperties: [ { name: "email", value: "bob@example.com" }, { name: "plan", value: "free" }, { name: "country", value: "UK" } ] }; ``` ``` -------------------------------- ### Create User Object Directly Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Defines a user object directly without using UserBuilder. Ensure custom properties are in the 'customizedProperties' array with 'name' and 'value'. ```typescript import { IUser } from "@featbit/node-server-sdk"; const bob: IUser = { key: "unique_key_for_bob", name: "Bob", customizedProperties: [ { name: "age", value: "18" }, { name: "country", value: "FR" }, ], }; ``` -------------------------------- ### Evaluate Boolean Feature Flag with Detail Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Evaluates a boolean feature flag and returns detailed information about how the value was determined, including the reason kind and description. ```javascript // flag to be evaluated const flagKey = "game-runner"; // create a user const user = new UserBuilder('a-unique-key-of-user') .name('bob') .custom('sex', 'female') .custom('age', 18) .build(); // evaluate a boolean flag for a given user with evaluation detail const boolVariationDetail = await fbClient.boolVariationDetail(flagKey, user, false); console.log(`flag '${flagKey}' returns ${boolVariationDetail.value} for user ${user.Key}` + `Reason Kind: ${boolVariationDetail.kind}, Reason Description: ${boolVariationDetail.reason}`); ``` -------------------------------- ### Track Custom Events for A/B Testing in Node.js Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Send custom events for A/B testing experiments. Ensure this is called after the related feature flag is evaluated to include the event in experiment results. ```javascript fbClient.track(user, eventName, numericValue); ``` -------------------------------- ### boolVariation / boolVariationDetail - Boolean Flag Evaluation Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Evaluate a boolean feature flag for a given user. `boolVariationDetail` provides additional evaluation context. ```APIDOC ## boolVariation / boolVariationDetail - Boolean Flag Evaluation Evaluates a boolean feature flag for a given user and returns true or false. The `boolVariationDetail` variant returns additional information about why a specific value was returned, including the evaluation reason and kind. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-123") .name("Alice") .custom("plan", "premium") .build(); // Simple boolean evaluation with default value const isEnabled = await fbClient.boolVariation("new-checkout-flow", user, false); console.log(`New checkout enabled: ${isEnabled}`); // Output: New checkout enabled: true // Boolean evaluation with detailed response const detail = await fbClient.boolVariationDetail("new-checkout-flow", user, false); console.log(`Value: ${detail.value}`); console.log(`Reason Kind: ${detail.kind}`); console.log(`Reason: ${detail.reason}`); // Output: // Value: true // Reason Kind: TargetMatch // Reason: target match ``` ``` -------------------------------- ### Evaluate Boolean Feature Flag Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Evaluates a boolean feature flag for a given user and returns its variation. A default value is returned if evaluation fails. ```javascript // flag to be evaluated const flagKey = "game-runner"; // create a user const user = new UserBuilder('a-unique-key-of-user') .name('bob') .custom('sex', 'female') .custom('age', 18) .build(); // evaluate a feature flag for a given user const boolVariation = await fbClient.boolVariation(flagKey, user, false); console.log(`flag '${flagKey}' returns ${boolVariation} for user ${user.Key}`); ``` -------------------------------- ### Evaluate Boolean Flag with Detailed Results Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Evaluate a boolean feature flag and retrieve detailed evaluation results, including the reason kind and reason for the returned value. This helps in debugging flag evaluations. ```typescript // Boolean evaluation with detailed response const detail = await fbClient.boolVariationDetail("new-checkout-flow", user, false); console.log(`Value: ${detail.value}`); console.log(`Reason Kind: ${detail.kind}`); console.log(`Reason: ${detail.reason}`); // Output: // Value: true // Reason Kind: TargetMatch // Reason: target match ``` -------------------------------- ### Evaluate Boolean Flag with Default Value Source: https://context7.com/featbit/featbit-node-server-sdk/llms.txt Evaluate a boolean feature flag for a given user. Provide a default value that will be returned if the flag is not found or cannot be evaluated. ```typescript import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .sdkKey("your-sdk-key") .streamingUri("ws://localhost:5100") .eventsUri("http://localhost:5100") .build(); await fbClient.waitForInitialization(); const user = new UserBuilder("user-123") .name("Alice") .custom("plan", "premium") .build(); // Simple boolean evaluation with default value const isEnabled = await fbClient.boolVariation("new-checkout-flow", user, false); console.log(`New checkout enabled: ${isEnabled}`); // Output: New checkout enabled: true ``` -------------------------------- ### Disable Events Collection in Node.js SDK Source: https://github.com/featbit/featbit-node-server-sdk/blob/main/README.md Configure the SDK to disable automatic event collection to the FeatBit server. This is useful if you want to manage event sending manually or in offline mode. ```javascript import { FbClientBuilder } from "@featbit/node-server-sdk"; const fbClient = new FbClientBuilder() .disableEvents(true) .build(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.