The LaunchDarkly SDK client object.

Create this object with init. Applications should configure the client at startup time and continue to use it throughout the lifetime of the application, rather than creating instances on the fly.

Note that LDClient inherits from EventEmitter, so you can use the standard on(), once(), and off() methods to receive events. The standard EventEmitter methods are not documented here; see the API documentation. For a description of events you can listen for, see on.

Hierarchy

  • LDClient
  • EventEmitter
    • LDClient

Properties

bigSegmentStoreStatusProvider: BigSegmentStoreStatusProvider

A mechanism for tracking the status of a Big Segment store.

This object has methods for checking whether the Big Segment store is (as far as the SDK knows) currently operational and tracking changes in this status. See interfaces.BigSegmentStoreStatusProvider for more about this functionality.

Accessors

  • get logger(): undefined | LDLogger
  • Get the logger used by this LDClient instance.

    For all platforms that support logging the logger should be present.

    Returns undefined | LDLogger

Methods

  • Type Parameters

    • K

    Parameters

    • error: Error
    • event: string | symbol
    • Rest ...args: AnyRest
      Rest

    Returns void

  • Add a hook to the client. In order to register a hook before the client starts, please use the hooks property of LDOptions.

    Hooks provide entrypoints which allow for observation of SDK functions.

    Parameters

    Returns void

  • Alias for emitter.on(eventName, listener).

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    Returns LDClient

    Since

    v0.1.26

  • Builds an object that encapsulates the state of all feature flags for a given context. This includes the flag values and also metadata that can be used on the front end. This method does not send analytics events back to LaunchDarkly.

    The most common use case for this method is to bootstrap a set of client-side feature flags from a back-end service. Call the toJSON() method of the returned object to convert it to the data structure used by the client-side SDK.

    Parameters

    • context: LDContext

      The context requesting the feature flags.

    • Optional options: LDFlagsStateOptions

      Optional LDFlagsStateOptions to determine how the state is computed.

      Optional
    • Optional callback: ((err, res) => void)

      A Node-style callback to receive the result (as an LDFlagsState). If omitted, you will receive a Promise instead.

      Optional
        • (err, res): void
        • Parameters

          Returns void

    Returns Promise<LDFlagsState>

    If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with the result as an LDFlagsState.

  • Determines the boolean variation of a feature flag for a context.

    If the flag variation does not have a boolean value, defaultValue is returned.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: boolean

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<boolean>

    A Promise which will be resolved with the result value.

  • Determines the boolean variation of a feature flag for a context, along with information about how it was calculated.

    The reason property of the result will also be included in analytics events, if you are capturing detailed event data for this flag.

    If the flag variation does not have a boolean value, defaultValue is returned. The reason will indicate an error of the type WRONG_KIND in this case.

    For more information, see the SDK reference guide.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: boolean

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<LDEvaluationDetailTyped<boolean>>

    A Promise which will be resolved with the result (as an ).

  • Discards all network connections, background tasks, and other resources held by the client.

    Do not attempt to use the client after calling this method.

    Returns void

  • Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    import { EventEmitter } from 'node:events';
    const myEmitter = new EventEmitter();

    // First listener
    myEmitter.on('event', function firstListener() {
    console.log('Helloooo! first listener');
    });
    // Second listener
    myEmitter.on('event', function secondListener(arg1, arg2) {
    console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
    });
    // Third listener
    myEmitter.on('event', function thirdListener(...args) {
    const parameters = args.join(', ');
    console.log(`event with parameters ${parameters} in third listener`);
    });

    console.log(myEmitter.listeners('event'));

    myEmitter.emit('event', 1, 2, 3, 4, 5);

    // Prints:
    // [
    // [Function: firstListener],
    // [Function: secondListener],
    // [Function: thirdListener]
    // ]
    // Helloooo! first listener
    // event with parameters 1, 2 in second listener
    // event with parameters 1, 2, 3, 4, 5 in third listener

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • Rest ...args: AnyRest
      Rest

    Returns boolean

    Since

    v0.1.26

  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    import { EventEmitter } from 'node:events';

    const myEE = new EventEmitter();
    myEE.on('foo', () => {});
    myEE.on('bar', () => {});

    const sym = Symbol('symbol');
    myEE.on(sym, () => {});

    console.log(myEE.eventNames());
    // Prints: [ 'foo', 'bar', Symbol(symbol) ]

    Returns (string | symbol)[]

    Since

    v6.0.0

  • Flushes all pending analytics events.

    Normally, batches of events are delivered in the background at intervals determined by the flushInterval property of LDOptions. Calling flush() triggers an immediate delivery. However, like Node I/O in general, this is still an asynchronous operation so you must still use Promise chaining, a callback, or async/await to detect when it has finished or failed.

    Parameters

    • Optional callback: ((err, res) => void)

      A function which will be called when the flush completes (meaning that all pending events have been delivered to LaunchDarkly). If omitted, you will receive a Promise instead.

      Optional
        • (err, res): void
        • Parameters

          • err: null | Error
          • res: boolean

          Returns void

    Returns Promise<void>

    If you provided a callback, then nothing. Otherwise, a Promise which resolves once flushing is finished. Note that the Promise will be rejected if the HTTP request fails, so be sure to attach a rejection handler to it.

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.

    Returns number

    Since

    v1.0.0

  • Identifies a context to LaunchDarkly.

    This simply creates an analytics event that will transmit the given user properties to LaunchDarkly, so that the context will be visible on your dashboard even if you have not evaluated any flags for that user. It has no other effect.

    If the context is omitted or has no key, the client will log a warning and will not send an event.

    Parameters

    • context: LDContext

      The context properties. Must contain at least the key property.

    Returns void

  • Tests whether the client has completed initialization.

    If this returns false, it means that the client has not yet successfully connected to LaunchDarkly. It might still be in the process of starting up, or it might be attempting to reconnect after an unsuccessful attempt, or it might have received an unrecoverable error (such as an invalid SDK key) and given up.

    Returns boolean

    True if the client has successfully initialized.

  • Tests whether the client is configured in offline mode.

    Returns boolean

    True if the offline property is true in your LDOptions.

  • Determines the variation of a feature flag for a context.

    This version may be favored in TypeScript versus variation because it returns an unknown type instead of any. unknown will require a cast before usage.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: unknown

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<unknown>

    A Promise which will be resolved with the result value.

  • Determines the variation of a feature flag for a context, along with information about how it was calculated.

    The reason property of the result will also be included in analytics events, if you are capturing detailed event data for this flag.

    This version may be favored in TypeScript versus variation because it returns an unknown type instead of any. unknown will require a cast before usage.

    For more information, see the SDK reference guide.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: unknown

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<LDEvaluationDetailTyped<unknown>>

    If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with the result (as an).

  • Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

    • Optional listener: Function

      The event handler function

      Optional

    Returns number

    Since

    v3.2.0

  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    Since

    v0.1.26

  • Returns the migration stage of the migration feature flag for the given evaluation context.

    If the evaluated value of the flag cannot be converted to an LDMigrationStage, then the default value will be returned and error will be logged.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: LDMigrationStage

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<LDMigrationVariation>

    A Promise which will be resolved with the result (as anLDMigrationVariation).

  • Determines the numeric variation of a feature flag for a context.

    If the flag variation does not have a numeric value, defaultValue is returned.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: number

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<number>

    A Promise which will be resolved with the result value.

  • Determines the numeric variation of a feature flag for a context, along with information about how it was calculated.

    The reason property of the result will also be included in analytics events, if you are capturing detailed event data for this flag.

    If the flag variation does not have a numeric value, defaultValue is returned. The reason will indicate an error of the type WRONG_KIND in this case.

    For more information, see the SDK reference guide.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: number

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<LDEvaluationDetailTyped<number>>

    A Promise which will be resolved with the result (as an ).

  • Alias for emitter.removeListener().

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    Returns LDClient

    Since

    v10.0.0

  • Registers an event listener that will be called when the client triggers some type of event.

    This is the standard on method inherited from Node's EventEmitter; see the API docs for more details on how to manage event listeners. Here is a description of the event types defined by LDClient.

    • "ready": Sent only once, when the client has successfully connected to LaunchDarkly. Alternately, you can detect this with [[waitForInitialization]].
    • "failed": Sent only once, if the client has permanently failed to connect to LaunchDarkly. Alternately, you can detect this with [[waitForInitialization]].
    • "error": Contains an error object describing some abnormal condition that the client has detected (such as a network error).
    • "update": The client has received a change to a feature flag. The event parameter is an object containing a single property, key, the flag key. Note that this does not necessarily mean the flag's value has changed for any particular context, only that some part of the flag configuration was changed.
    • "update:KEY": The client has received a change to the feature flag whose key is KEY. This is the same as "update" but allows you to listen for a specific flag.

    Parameters

    • event: string | symbol

      the name of the event to listen for

    • listener: ((...args) => void)

      the function to call when the event happens

        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    Returns LDClient

  • Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

    server.once('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

    import { EventEmitter } from 'node:events';
    const myEE = new EventEmitter();
    myEE.once('foo', () => console.log('a'));
    myEE.prependOnceListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    Returns LDClient

    Since

    v0.3.0

  • Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    Returns LDClient

    Since

    v6.0.0

  • Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    Returns LDClient

    Since

    v6.0.0

  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    import { EventEmitter } from 'node:events';
    const emitter = new EventEmitter();
    emitter.once('log', () => console.log('log once'));

    // Returns a new Array with a function `onceWrapper` which has a property
    // `listener` which contains the original listener bound above
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    logFnWrapper.listener();

    // Logs "log once" to the console and removes the listener
    logFnWrapper();

    emitter.on('log', () => console.log('log persistently'));
    // Will return a new Array with a single function bound by `.on()` above
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    Since

    v9.4.0

  • Removes all listeners, or those of the specified eventName.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • Optional eventName: string | symbol
      Optional

    Returns LDClient

    Since

    v0.1.26

  • Removes the specified listener from the listener array for the event named eventName.

    const callback = (stream) => {
    console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

    removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

    Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

    import { EventEmitter } from 'node:events';
    class MyEmitter extends EventEmitter {}
    const myEmitter = new MyEmitter();

    const callbackA = () => {
    console.log('A');
    myEmitter.removeListener('event', callbackB);
    };

    const callbackB = () => {
    console.log('B');
    };

    myEmitter.on('event', callbackA);

    myEmitter.on('event', callbackB);

    // callbackA removes listener callbackB but it will still be called.
    // Internal listener array at time of emit [callbackA, callbackB]
    myEmitter.emit('event');
    // Prints:
    // A
    // B

    // callbackB is now removed.
    // Internal listener array [callbackA]
    myEmitter.emit('event');
    // Prints:
    // A

    Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

    When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

    import { EventEmitter } from 'node:events';
    const ee = new EventEmitter();

    function pong() {
    console.log('pong');
    }

    ee.on('ping', pong);
    ee.once('ping', pong);
    ee.removeListener('ping', pong);

    ee.emit('ping');
    ee.emit('ping');

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    Returns LDClient

    Since

    v0.1.26

  • Computes an HMAC signature of a context signed with the client's SDK key.

    For more information, see the JavaScript SDK Reference Guide on Secure mode.

    Parameters

    Returns string

    The hash string.

  • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • n: number

    Returns LDClient

    Since

    v0.3.5

  • Determines the string variation of a feature flag for a context.

    If the flag variation does not have a string value, defaultValue is returned.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: string

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<string>

    A Promise which will be resolved with the result value.

  • Determines the string variation of a feature flag for a context, along with information about how it was calculated.

    The reason property of the result will also be included in analytics events, if you are capturing detailed event data for this flag.

    If the flag variation does not have a string value, defaultValue is returned. The reason will indicate an error of the type WRONG_KIND in this case.

    For more information, see the SDK reference guide.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: string

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    Returns Promise<LDEvaluationDetailTyped<string>>

    A Promise which will be resolved with the result (as an ).

  • Tracks that a context performed an event.

    LaunchDarkly automatically tracks pageviews and clicks that are specified in the Metrics section of the dashboard. This can be used to track custom metrics (goals) or other events that do not currently have metrics.

    Note that event delivery is asynchronous, so the event may not actually be sent until later; see flush.

    If the context is omitted or has no key, the client will log a warning and will not send an event.

    Parameters

    • key: string

      The name of the event, which may correspond to a metric in Experimentation.

    • context: LDContext

      The context to track.

    • Optional data: any

      Optional additional information to associate with the event.

      Optional
    • Optional metricValue: number

      A numeric value used by the LaunchDarkly experimentation feature in numeric custom metrics. Can be omitted if this event is used by only non-numeric metrics. This field will also be returned as part of the custom event for Data Export.

      Optional

    Returns void

  • Track the details of a migration.

    Parameters

    Returns void

  • Determines the variation of a feature flag for a context.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: any

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    • Optional callback: ((err, res) => void)

      A Node-style callback to receive the result value. If omitted, you will receive a Promise instead.

      Optional
        • (err, res): void
        • Parameters

          • err: any
          • res: any

          Returns void

    Returns Promise<any>

    If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with the result value.

  • Determines the variation of a feature flag for a context, along with information about how it was calculated.

    The reason property of the result will also be included in analytics events, if you are capturing detailed event data for this flag.

    For more information, see the SDK reference guide.

    Parameters

    • key: string

      The unique key of the feature flag.

    • context: LDContext

      The context requesting the flag. The client will generate an analytics event to register this context with LaunchDarkly if the context does not already exist.

    • defaultValue: any

      The default value of the flag, to be used if the value is not available from LaunchDarkly.

    • Optional callback: ((err, res) => void)

      A Node-style callback to receive the result (as an LDEvaluationDetail). If omitted, you will receive a Promise instead.

      Optional

    Returns Promise<LDEvaluationDetail>

    If you provided a callback, then nothing. Otherwise, a Promise which will be resolved with the result (as anLDEvaluationDetail).

  • Returns a Promise that tracks the client's initialization state.

    The Promise will be resolved if the client successfully initializes, or rejected if client initialization has failed unrecoverably (for instance, if it detects that the SDK key is invalid). Keep in mind that unhandled Promise rejections can be fatal in Node, so if you call this method, be sure to attach a rejection handler to it (or, if using async/await, a catch block).

    Note that you can also use event listeners (on) for the same purpose: the event "ready" indicates success, and "failed" indicates failure.

    This method takes an optional parameters which include a timeout. The timeout controls how long a specific call to waitForInitialization will wait before rejecting its promise. If a subsequent call is made to waitForInitialization with a timeout, then it will again wait up to that maximum time.

    Regardless of whether you continue to wait, the SDK will still retry all connection failures indefinitely unless it gets an unrecoverable error as described above.

    Waiting indefinitely, or depending only on the "ready" or "failed" events can result in an application waiting indefinitely. It is recommended to use a timeout which is reasonable for your application.

    Parameters

    Returns Promise<LDClient>

    A Promise that will be resolved if the client initializes successfully, or rejected if it fails. If successful, the result is the same client object. It is not recommended to use the returned client object. It will be removed in a future version.

    Example

    This example shows use of Promise chaining methods for specifying handlers:

      client.waitForInitialization({timeoutSeconds: 10}).then(() => {
    // do whatever is appropriate if initialization has succeeded
    }).catch(err => {
    // do whatever is appropriate if initialization has failed or timed out
    })

    Example

    This example shows use of async/await syntax for specifying handlers:

      try {
    await client.waitForInitialization({timeoutSeconds: 10});
    // do whatever is appropriate if initialization has succeeded
    } catch (err) {
    // do whatever is appropriate if initialization has failed or timed out
    }

Generated using TypeDoc