Unleash Node.js SDK

repository·main·Indexed 42 days ago

https://github.com/unleash/unleash-node-sdk

The official Node.js client for the Unleash feature management platform, allowing developers to evaluate feature flags and variants. Version 6.12.1 requires Node.js 20 or later. It provides tools for initializing the client via startUnleash, evaluating flags with isEnabled and getVariant, and tracking impact metrics using Counters, Gauges, and Histograms.

Tokens
11K
Snippets
38
Records
45
Agent score
48%

What's inside Unleash

  1. Quick start with unleash-client

    main

    To use the SDK, initialize it using startUnleash with your Unleash instance URL, an application name, and required authentication headers. Once initialized, you can evaluate feature flags using isEnabled for boolean flags or getVariant for multi-variant flags.

    import { startUnleash } from 'unleash-client';
    
    const unleash = await startUnleash({
      url: 'https://<your-unleash-instance>/api/',
      appName: 'my-node-name',
      customHeaders: { Authorization: '<your-backend-token>' },
    });
    
    const enabled = unleash.isEnabled('my-feature');
    if (enabled) {
      // new behavior
    }
    
    const variant = unleash.getVariant('checkout-experiment');
    if (variant.name === 'blue') {
      // blue variant behavior
    } else if (variant.name === 'green') {
      // green variant behavior
    }
  2. Extend flag names via module augmentation

    main

    By default, UnleashTypes['flagNames'] is a string. You can improve developer experience and type safety by augmenting the UnleashTypes interface to include specific toggle names used in your application.

    declare module 'unleash-client' {
      interface UnleashTypes {
        flagNames: 'foo' | 'bar';
      }
    }
  3. Understand Variant and Payload structures

    main

    When working with Unleash features, variants represent the different possible outcomes of a feature flag evaluation. A Variant contains the result of an evaluation, while a VariantDefinition is the configuration provided by the Unleash server.

    Payload Types

    Payloads allow you to return structured data alongside a variant. The PayloadType enum defines the supported formats:

    • STRING ('string')
    • JSON ('json')
    • CSV ('csv')
    • NUMBER ('number')

    Variant Interfaces

    • Variant: The object returned after evaluation. It includes the name, whether the feature is enabled, and an optional payload.
    • VariantDefinition: The configuration used to determine which variant to pick. It includes name, weight, an optional stickiness key, an optional payload, and optional overrides.
    export enum PayloadType {
      STRING = 'string',
      JSON = 'json',
      CSV = 'csv',
      NUMBER = 'number',
    }
    
    export interface Payload {
      type: PayloadType;
      value: string;
    }
    
    export interface Variant {
      name: string;
      enabled: boolean;
      payload?: Payload;
      feature_enabled?: boolean;
    }
    
    export interface VariantDefinition {
      name: string;
      weight: number;
      stickiness?: string;
      payload?: Payload;
      overrides?: Override[];
    }
  4. Listen to Unleash client events

    main

    The UnleashClient is an EventEmitter that emits several important events:

    • UnleashEvents.Warn: Emitted when a strategy or dependency is missing for a toggle.
    • UnleashEvents.Error: Emitted when a malformed feature is encountered.
    • UnleashEvents.Impression: Emitted when a feature evaluation occurs and impressionData is enabled for that feature.
  5. Understand the Repository lifecycle and event system

    main

    The Repository manages the lifecycle of feature toggle data through several stages:

    1. Initialization: The constructor sets up the AdaptiveFetcher and internal state.
    2. Startup (start()):
      • Loads data from the storageProvider (Backup).
      • Loads data from the bootstrapProvider (Bootstrap).
      • Starts the fetcher to connect to the Unleash server.
    3. Ready State: Once data is loaded (from backup, bootstrap, or the first API response), the Ready event is emitted.
    4. Updates: As the server sends updates (via full response or delta events), the repository updates its internal map and emits the Changed event.

    Emitted Events:

    • Ready: Emitted when the repository has successfully loaded initial data.
    • Changed: Emitted whenever the feature toggles are updated.
    • Error: Emitted when a critical error occurs (e.g., fetching errors).
    • Warn: Emitted when non-critical issues occur (e.g., bootstrap loading failures).
    • Unchanged: Emitted when a fetch results in no changes.
    • Mode: Emitted when the connection mode changes.
  6. How flagContext affects metric labels

    main

    When you provide a flagContext to a metric recording method, the MetricsAPI resolves the state of the specified flags using the current Unleash client.

    For each flag name provided in flagContext.flagNames, a label is added to the metric with the following logic:

    • If the variant is enabled: the label value is the variant name.
    • If the variant is not enabled but the feature is enabled: the label value is 'enabled'.
    • Otherwise: the label value is 'disabled'.

    These flag labels are merged with the staticContext (which includes appName and environment) to form the final set of labels sent to the metric registry.

  7. Configure the Repository with RepositoryOptions

    main

    To initialize the Repository class, you must provide a RepositoryOptions object. This object defines how the SDK connects to the Unleash server, how it handles data persistence, and how it bootstraps initial state.

    Key configuration options include:

    • url: The Unleash server URL.
    • appName: The name of your application.
    • instanceId: A unique identifier for this specific instance.
    • connectionId: A unique identifier for the connection.
    • refreshInterval: How often to poll for updates (defaults to 15_000 ms).
    • bootstrapProvider: A provider used to load initial feature toggle data (e.g., from a local file or environment).
    • storageProvider: A provider used to persist feature toggle data for offline/backup use.
    • mode: The connection mode, either 'polling' or 'streaming'.
    • headers / customHeadersFunction: Used to pass custom HTTP headers to the server.
    • tags: An array of TagFilter to filter which toggles are fetched.
    const options: RepositoryOptions = {
      url: 'https://your-unleash-server.com/api',
      appName: 'my-app',
      instanceId: 'instance-1',
      connectionId: 'conn-1',
      refreshInterval: 15000,
      mode: 'polling',
      bootstrapProvider: myBootstrapProvider,
      storageProvider: myStorageProvider,
    };
    
    const repository = new Repository(options);
  8. Configure bootstrap options for initial feature flag state

    main

    When initializing the Unleash client, you can provide BootstrapOptions to supply an initial state of feature flags. This prevents the client from starting with zero flags before its first synchronization with the Unleash server.

    Supported bootstrap methods via DefaultBootstrapProvider:

    • Inline Data: Provide data (an array of FeatureInterface) and optional segments to use directly.
    • URL: Provide a url to fetch the bootstrap JSON from a remote endpoint. You can also provide urlHeaders for custom headers.
    • File: Provide a filePath to read a local JSON file containing the bootstrap data.
    • Custom Provider: Provide a custom implementation of the BootstrapProvider interface.
    import { BootstrapOptions } from 'unleash-client';
    
    const options: BootstrapOptions = {
      // Option 1: Load from a local file
      filePath: './bootstrap-data.json',
    
      // Option 2: Load from a remote URL
      // url: 'https://api.example.com/bootstrap',
      // urlHeaders: { 'Authorization': 'Bearer token' },
    
      // Option 3: Use inline data
      // data: [{ name: 'my-feature', enabled: true, ... }],
      // segments: [{ name: 'my-segment', ... }],
    };
  9. Record metric values with incrementCounter, updateGauge, and observeHistogram

    main

    Once defined, you can record data points using the following methods:

    incrementCounter

    Increments a counter by a specific value (defaults to 1 if undefined). incrementCounter(name: string, value?: number, flagContext?: MetricFlagContext): void

    updateGauge

    Sets a gauge to a specific value. updateGauge(name: string, value: number, flagContext?: MetricFlagContext): void

    observeHistogram

    Records a value in a histogram. observeHistogram(name: string, value: number, flagContext?: MetricFlagContext): void

    Using flagContext

    You can optionally provide a flagContext to attach feature flag states to your metric labels. This allows you to see how different feature flag variants impact your metrics.

    Note: The flagContext parameter is deprecated and will be removed in a future release. You should aim to call these methods without flagContext where possible.

    If you attempt to record a metric that has not been defined, a warning is emitted via UnleashEvents.Warn.

    // Incrementing a counter
    metricsApi.incrementCounter('requests_total');
    metricsApi.incrementCounter('requests_total', 5);
    
    // Updating a gauge
    metricsApi.updateGauge('active_users', 42);
    
    // Observing a histogram
    metricsApi.observeHistogram('request_latency', 0.25);
    
    // Recording with flag context (Deprecated)
    metricsApi.incrementCounter('requests_total', 1, { flagNames: ['my-feature'], context: myContext });