### Install Unleash Client (npm/yarn) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Installs the Unleash client library using either npm or yarn package managers. This is the first step to integrating Unleash into your Node.js project. ```bash npm install unleash-client ``` ```bash yarn add unleash-client ``` -------------------------------- ### Get Feature Toggle Definitions (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This code demonstrates how to retrieve individual and all feature toggle definitions using the Unleash Node.js SDK. It requires importing specific functions from 'unleash-client' and initializing the client. ```javascript import { initialize, getFeatureToggleDefinition, getFeatureToggleDefinitions, } from 'unleash-client'; initialize({ url: 'http://unleash.herokuapp.com/api/', customHeaders: { Authorization: '' }, appName: 'my-app-name', instanceId: 'my-unique-instance-id', }); const featureToggleX = getFeatureToggleDefinition('app.ToggleX'); const featureToggles = getFeatureToggleDefinitions(); ``` -------------------------------- ### Implement Custom Redis Storage Provider for Unleash Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This snippet demonstrates how to create a custom storage provider class for the Unleash Node SDK using Redis. It implements the required set and get methods to persist feature flag data externally, which is then passed to the initialize function. ```javascript import { initialize, InMemStorageProvider } from 'unleash-client'; import { createClient } from 'redis'; class CustomRedisStore { async set(key, data) { const client = createClient(); await client.connect(); await client.set(key, JSON.stringify(data)); } async get(key) { const client = createClient(); await client.connect(); const data = await client.get(key); return JSON.parse(data); } } const client = initialize({ appName: 'my-application', url: 'http://localhost:3000/api/', customHeaders: { Authorization: 'my-key', }, storageProvider: new CustomRedisStore(), }); ``` -------------------------------- ### Define and Update Gauge for Impact Metrics (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This code shows how to define a gauge for point-in-time values and update it with the current value using the Unleash Node.js SDK. Ensure the Unleash client is initialized and the 'unleash-client' package is installed. ```javascript unleash.impactMetrics.defineGauge( 'total_users', 'Total number of registered users' ); unleash.impactMetrics.updateGauge('total_users', userCount); ``` -------------------------------- ### Retrieve Feature Toggle Variant Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Retrieves a specific variant of a feature toggle using the `getVariant` method. If the feature is disabled or has no variants, it returns the 'disabled variant'. The example shows how to check if the returned variant's name is 'blue' and perform actions accordingly. ```javascript const variant = unleash.getVariant('demo-variant'); if (variant.name === 'blue') { // do something with the blue variant... } ``` -------------------------------- ### Initialize Unleash SDK with Bootstrap URL (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This snippet shows how to initialize the Unleash Node.js SDK by fetching bootstrap configuration from a specified URL. This enhances resilience by allowing configuration loading even if the Unleash API is unavailable. Requires 'unleash-client'. ```javascript const client = initialize({ appName: 'my-application', url: 'https://app.unleash-hosted.com/demo/api/', customHeaders: { Authorization: '' }, bootstrap: { url: 'http://localhost:3000/proxy/client/features', urlHeaders: { Authorization: 'bootstrap', }, }, }); ``` -------------------------------- ### Initialize Unleash Client and Subscribe to Events Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Demonstrates how to initialize the Unleash client with configuration options and attach listeners to various lifecycle and operational events. This allows developers to react to state changes, errors, and feature evaluation metrics. ```javascript import { initialize } from 'unleash-client'; const unleash = initialize({ appName: 'my-app-name', url: 'http://unleash.herokuapp.com/api/', customHeaders: { Authorization: 'API token', }, }); // Some useful life-cycle events unleash.on('ready', console.log); unleash.on('synchronized', console.log); unleash.on('error', console.error); unleash.on('warn', console.warn); unleash.once('registered', () => { // Do something after the client has registered with the server API. // Note: it might not have received updated feature toggles yet. }); unleash.once('changed', () => { console.log(`Demo is enabled: ${unleash.isEnabled('Demo')}`); }); unleash.on('count', (name, enabled) => console.log(`isEnabled(${name})`)); ``` -------------------------------- ### Initialize Unleash SDK with Bootstrap File Path (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This code initializes the Unleash Node.js SDK by loading bootstrap configuration from a local file path. This method provides an alternative to fetching from a URL or providing data directly, enhancing startup resilience. Requires 'unleash-client'. ```javascript const client = initialize({ appName: 'my-application', url: 'https://app.unleash-hosted.com/demo/api/', customHeaders: { Authorization: '' }, bootstrap: { filePath: '/tmp/some-bootstrap.json', }, }); ``` -------------------------------- ### Initialize Unleash SDK with Bootstrap Data (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This code initializes the Unleash Node.js SDK with feature toggle configuration provided directly as data. This is useful for offline or faster startup scenarios. It requires the 'unleash-client' package. ```javascript const client = initialize({ appName: 'my-application', url: 'https://app.unleash-hosted2.com/demo/api/', customHeaders: { Authorization: '' }, bootstrap: { data: [ { enabled: false, name: 'BootstrapDemo', description: '', project: 'default', stale: false, type: 'release', variants: [], strategies: [{ name: 'default' }], }, ], }, }); ``` -------------------------------- ### Synchronous Unleash Client Initialization Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Initializes the Unleash client synchronously using 'startUnleash' and awaits its readiness. This method guarantees that the SDK is fully synchronized with the Unleash API before proceeding, ensuring up-to-date feature flag evaluation. ```javascript import { startUnleash } from 'unleash-client'; const unleash = await startUnleash({ url: 'https://YOUR-API-URL', appName: 'my-node-name', customHeaders: { Authorization: '' }, }); // The Unleash SDK now has a fresh state from the Unleash API const isEnabled = unleash.isEnabled('Demo'); ``` -------------------------------- ### Initialize Unleash Client (Global Instance) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Initializes a global instance of the Unleash client using the 'initialize' function. This method configures the SDK to connect to your Unleash instance and requires the API URL, application name, and authorization token. ```javascript import { initialize } from 'unleash-client'; const unleash = initialize({ url: 'https://YOUR-API-URL', appName: 'my-node-name', customHeaders: { Authorization: '' }, }); ``` -------------------------------- ### Initialize Unleash SDK with In-Memory Storage (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This snippet shows how to initialize the Unleash Node.js SDK using an in-memory storage provider instead of the default file-based storage. This is useful for environments where disk persistence is not desired or available. Requires 'unleash-client'. ```javascript import { initialize, InMemStorageProvider } from 'unleash-client'; const client = initialize({ appName: 'my-application', url: 'http://localhost:3000/api/', customHeaders: { Authorization: '' }, storageProvider: new InMemStorageProvider(), }); ``` -------------------------------- ### Construct Unleash Client Directly Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Creates a new instance of the Unleash client directly using the 'Unleash' class constructor. This approach is suitable for managing a single instance and requires similar configuration parameters as the 'initialize' method. It also demonstrates how to listen for 'ready' and 'error' events. ```javascript import { Unleash } from 'unleash-client'; const unleash = new Unleash({ url: 'https://YOUR-API-URL', appName: 'my-node-name', customHeaders: { Authorization: '' }, }); unleash.on('ready', console.log.bind(console, 'ready')); // optional error handling when using unleash directly unleash.on('error', console.error); ``` -------------------------------- ### Register Custom Strategy in JavaScript Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This snippet shows how to register a custom activation strategy with the Unleash Node.js SDK during initialization. It includes setting the Unleash server URL and custom authorization headers, along with providing an instance of the custom strategy. ```javascript initialize({ url: 'http://unleash.herokuapp.com', customHeaders: { Authorization: 'API token', }, strategies: [new ActiveForUserWithEmailStrategy()], }); ``` -------------------------------- ### Define and Observe Histogram for Impact Metrics (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This snippet illustrates how to define a histogram for measuring value distribution and observe a value using the Unleash Node.js SDK. It requires an initialized Unleash client and the 'unleash-client' package. ```javascript unleash.impactMetrics.defineHistogram( 'request_time_ms', 'Time taken to process a request in milliseconds', [50, 100, 200, 500, 1000] ); unleash.impactMetrics.observeHistogram('request_time_ms', 125); ``` -------------------------------- ### Implement Custom Strategy in JavaScript Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This snippet demonstrates how to implement a custom activation strategy for the Unleash Node.js SDK. It extends the base `Strategy` class and defines an `isEnabled` method to check if a feature toggle should be active based on user email. ```javascript import { initialize, Strategy } from 'unleash-client'; class ActiveForUserWithEmailStrategy extends Strategy { constructor() { super('ActiveForUserWithEmail'); } isEnabled(parameters, context) { return parameters.emails.indexOf(context.email) !== -1; } } ``` -------------------------------- ### Provide Unleash Context for Strategy Evaluation Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Demonstrates providing an Unleash context object to the `isEnabled` method for evaluating activation strategies. The context includes `userId`, `sessionId`, and `remoteAddress`, which are essential for certain built-in strategies. ```javascript const unleashContext = { userId: '123', sessionId: 'some-session-id', remoteAddress: '127.0.0.1', }; unleash.isEnabled('someToggle', unleashContext); ``` -------------------------------- ### Define and Increment Counter for Impact Metrics (Node.js) Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md This snippet demonstrates how to define a counter for cumulative values and increment it using the Unleash Node.js SDK. It requires the 'unleash-client' package and an initialized Unleash client instance. ```javascript const unleash = initialize({ url: 'https://YOUR-API-URL', appName: 'my-node-name', customHeaders: { Authorization: '' }, }); unleash.impactMetrics.defineCounter( 'request_count', 'Total number of HTTP requests processed' ); unleash.impactMetrics.incrementCounter('request_count'); ``` -------------------------------- ### Listen for Unleash Client Synchronization Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Attaches an event listener to the Unleash client to detect when it has successfully synchronized with the Unleash server. This ensures that feature flags are evaluated using the latest configuration. ```javascript unleash.on('synchronized', () => { // the SDK has synchronized with the server // and is ready to serve }); ``` -------------------------------- ### Check Feature Toggle Status with setInterval Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Checks the status of a feature toggle ('DemoToggle') at regular intervals using `setInterval`. This ensures the application stays running if its sole purpose is to interact with the Unleash SDK. It logs whether the toggle is enabled or disabled to the console. ```javascript setInterval(() => { if (unleash.isEnabled('DemoToggle')) { console.log('Toggle enabled'); } else { console.log('Toggle disabled'); } }, 1000); ``` -------------------------------- ### Check Feature Toggle with Unleash Context Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Checks the status of a feature toggle ('someToggle') while providing an Unleash context object. This context is used by the SDK to evaluate activation strategies and constraints. The context includes properties like `userId`, `sessionId`, `remoteAddress`, and custom `properties`. ```javascript const unleashContext = { userId: '123', sessionId: 'some-session-id', remoteAddress: '127.0.0.1', properties: { region: 'EMEA', }, }; const enabled = unleash.isEnabled('someToggle', unleashContext); ``` -------------------------------- ### TypeScript: Type-Safe Feature Toggle Names Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Uses TypeScript module augmentation to define a specific set of allowed feature toggle names ('aaa', 'bbb'). This provides compile-time safety, preventing the use of incorrect feature names with methods like `isEnabled`. An attempt to use an undefined name ('ccc') will result in a TypeScript error. ```typescript import { initialize } from 'unleash-client'; declare module 'unleash-client' { interface UnleashTypes { flagNames: 'aaa' | 'bbb'; } } const client = initialize({}); client.isEnabled('aaa'); client.isEnabled('bbb'); client.isEnabled('ccc'); // Error ``` -------------------------------- ### Stop Unleash Client Source: https://github.com/unleash/unleash-node-sdk/blob/main/README.md Shuts down the Unleash client and stops its polling mechanism by calling the `destroy` method. This is typically not required for most applications but is available for explicit cleanup. ```javascript import { destroy } from 'unleash-client'; destroy(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.