• SDKS
No results for ""


Node.js SDK reference (client-side)

Read time: 8 minutes
Last edited: May 14, 2021

This reference guide documents all of the methods available in our client-side Node.js SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, read Client-Side Node.js SDK GitHub repository. The online API docs contain the programmatic definitions of every type and method. Additionally you can clone and run a sample application using this SDK.

For use in desktop or Node-enabled device applications only

This SDK is intended for use in single-user desktop or Node-enabled device applications. If you have a Node.js application and are looking to set up LaunchDarkly on the server-side, head to our Node.js SDK reference. If you are using Electron, there is an Electron SDK more specifically designed for that environment.

To learn more, read client-side and server-side SDKs.

This SDK is closely related to the browser JavaScript SDK and has almost exactly the same API, but does not have any browser-specific functionality, and adds several features specific to Node.

Getting started

Building on top of our Getting Started guide, the following steps will get you started with using the LaunchDarkly SDK in your Node.js code.

The first step is to install the LaunchDarkly SDK as a dependency in your application using your application's dependency manager.

1npm install --save launchdarkly-node-client-sdk

Next you should import the LaunchDarkly client in your application code.

1const LaunchDarkly = require('launchdarkly-node-client-sdk');

Once the SDK is installed and imported, you'll want to create a single, shared instance of the LaunchDarkly client. To create a client instance, you need your environment's client-side ID (available on your account settings page). Client-side IDs are not secret. You can expose them in your client-side code with no risk.

Feature flag targeting and rollouts are all determined by the active user. You must pass a user context to the SDK during initialization before requesting any feature flags with variation. Failure to pass a valid user context to the SDK during initialization will result in an error.

Here's a basic example showing how to initialize the client:

1const user = {
2 key: "aa0ceb"
5const ldClient = LaunchDarkly.initialize('YOUR_CLIENT_SIDE_ID', user);

The client will emit a ready event when it has been initialized (you can also use the waitForInitialization() method, which returns a Promise). Once it has been initialized, you can safely call variation to access your feature flags. (Note that the ready event is only emitted once, when the client first initializes. In a production application, your calls to ldClient.variation would normally not be inside of this event handler.)

1ldClient.on('ready', () => {
2 console.log("It's now safe to request feature flags");
4 const showFeature = ldClient.variation("YOUR_FEATURE_KEY", false);
6 if (showFeature) {
7 ...
8 } else {
9 ...
10 }
Streaming Updates

The SDK does not subscribe to streaming real-time updates automatically when it is initialized. Setting the streaming option to true in the client configuration will cause the SDK to open a streaming connection to LaunchDarkly and receive live feature flag updates; you can also specify an event handler with ldClient.on('change') to be notified immediately when a flag has changed.

Making feature flags available to the client-side SDK

Feature flags must be marked available to the client-side SDK (see your feature flag's settings page) before they can be used in variation calls on the front-end. If you request a feature flag that is not available, you'll receive the default value for that flag. If you always want flags marked as available to the client-side SDK by default, you can check the "Make new flags available to the client-side (JavaScript) SDK by default" in your project settings.

Lastly, when your application is about to terminate, shut down ldClient. This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.

1ldClient.close(() => {
2 console.log('Client has been closed');
3 process.exit(0);

Customizing your client

You can also pass custom parameters to the client by creating a custom configuration object:

1const options = {
2 flushInterval: 10000,
3 allAttributesPrivate: true
6const ldClient = LaunchDarkly.initialize('YOUR_CLIENT_SIDE_ID', user, options);

For a full guide to the available configuration options, read LDOptions in the TypeScript reference.


Personally-identifying user keys

By default, when the SDK requests feature flags from LaunchDarkly, it makes an HTTP GET request with the user properties encoded in the URL. If you do not want user keys or other properties to be in request URLs, enable the useReport option in your client configuration; this will cause user data to be sent in the body of an HTTP REPORT request instead.

Let's walk through the user JSON in more detail. The most important attribute is the user key. In this case we've used the hash "aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

Here's a more complete example of a user:

1const user = {
2 key: "aa0ceb",
3 firstName: "Ernestina",
4 lastName: "Evans",
5 email: "ernestina@example.com",
6 custom: {
7 groups: ["Google", "Microsoft"]
8 }

All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

Besides the key, LaunchDarkly supports the following attributes at the "top level". Remember, all of these are optional:

  • ip: Must be an IP address.
  • firstName: Must be a string. If you provide a first name, you can search for users on the Users page by name.
  • lastName: Must be a string. If you provide a last name, you can search for users on the Users page by name.
  • country: Must be a string representing the country associated with the user.
  • email: Must be a string representing the user's email address. If an avatar URL is not provided, we'll use Gravatar to try to display an avatar for the user on the Users page.
  • avatar: Must be an absolute URL to an avatar image for the user.
  • name: Must be a string. You can search for users on the User page by name
  • anonymous: Must be a boolean. See the section below on anonymous users for more details.

In addition to built-in attributes, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

A note on types

Most of our built-in attributes (like names and email addresses) expect string values. Custom attribute values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers. If you enter a custom value on our dashboard that looks like a number or a boolean, it'll be interpreted that way.

Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us, including organizations, groups, andaccount plans. Anything you pass to us becomes available instantly on our dashboard.

Private user attributes

You can optionally configure the JavaScript SDK to treat all user attributes as private user attributes . Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

To mark all user attributes (except the key) as private in the JavaScript SDK, you can use the allAttributesPrivate option:

1const user = {
2 key: "aa0ceb",
3 name: "Grace Hopper",
4 email: "gracehopper@example.com"
7const ldClient = LaunchDarkly.initialize('YOUR_CLIENT_SIDE_ID', user, {
8 allAttributesPrivate: true

In the above example, the name and email attributes will be removed.

You can also specify an array of which attributes should be private with the privateAttributeNames option. This option can also be configured on a per-user basis by specifying which attributes should be private in your user object.

In the example below, this option is configured in both the user object and the configuration object to demonstrate what this looks like:

1const user = {
2 key: "aa0ceb",
3 name: "Grace Hopper",
4 email: "gracehopper@example.com"
5 privateAttributeNames: ["email"]
8const ldClient = LaunchDarkly.initialize('YOUR_CLIENT_SIDE_ID', user, {
9 privateAttributeNames: ["email"]

In the example above, only the user's key and their name will be sent back to LaunchDarkly.

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

1// To create an anonymous user with an auto-generated key, you can specify
2// the "anonymous" property and omit the "key" property. The LaunchDarkly
3// client will create a unique key for this user and cache it locally.
4const user = { anonymous: true };
6// You can also specify any key you wish:
7const user2 = { key: "aa0ceb", anonymous: true };

We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. This keeps anonymous users from polluting your Users page.

You can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. If you use the same user key for every anonymous user, you also can't use percentage rollouts or Experimentation with anonymous users.

Aliased users

There are situations in which multiple LaunchDarkly users can represent one person. For example, this can happen when a person initially logs into an application. The person might be represented by an anonymous user before they log in, and a different user after they log in. In that case, that one person would be identified by two different users as denoted by different user keys.

The SDK can associate these two LaunchDarkly users by sending an alias event.

The SDK automatically sends an alias event when identify is called with a known user if the previous user was anonymous. You can disable this behavior if necessary. To learn more, read Customizing your client.

You can manually tell the SDK to send an alias event with the alias function.

1ldClient.alias(newUser, previousUser);


The variation method determines which variation of a feature flag a user receives.

1const value = ldClient.variation("your.feature.key", false);

variation calls take the feature flag key and a default value.

The default value will only be returned if an error is encountered—for example, if the feature flag key doesn't exist or the user doesn't have a key specified.


The variationDetail method allows you to evaluate a feature flag (using the same parameters as you would for variation) and receive more information about how the value was calculated.

The variation detail is returned in an object that contains both the result value and a "reason" object which will tell you, for instance, if the user was individually targeted for the flag or was matched by one of the flag's rules. It will also indicate if the flag returned the default value due to an error. You can examine the "reason" data programmatically; you can also view it with Data Export, if you are capturing detailed analytics events for this flag.

To learn more, read Evaluation reasons.


The track method allows you to record actions your users take, giving them any event name you wish. This lets you record events that take place client-side. The current user data automatically accompanies the event.

3ldClient.track("something-happened-with-custom-data", { someData: 2 });

Subscribing to feature flag changes

The client uses an event emitter pattern to allow you to subscribe to feature flag changes in real time. To subscribe to all feature flag changes, listen for the change event:

1ldClient.on('change', allChanges => {
2 console.log('flags changed:', JSON.stringify(allChanges));
The `allChanges` object will contain a map of updated feature flag keys and values. The map will only contain the keys to flags that have changed. You can also subscribe to specific flags:
1ldClient.on('change:YOUR_FLAG_KEY', (value, previous) => {
2 console.log('YOUR_FLAG_KEY changed:', value, '(was ' + previous + ')');

All flags

Creating users

The allFlags method in this SDK functions differently than our other SDKs. This method sends analytics events to LaunchDarkly as if you'd called variation for every feature flag.

You can disable this behavior by initializing the SDK with sendEventsOnlyForVariation set to true.

The allFlags method will return a key/value map of all your feature flags.

The map will contain null values for any flags that would return the fallback value (the second argument that you normally pass to variation).


Bootstrapping refers to providing the LaunchDarkly client object with an initial, immediately available set of feature flag values that will be used instead of waiting for a connection to LaunchDarkly. This feature is normally used in the browser JavaScript SDK, with the values being provided by LaunchDarkly-enabled code on the back end, but you can use it to set the feature flags to any values you wish:

1const ldClient = LaunchDarkly.initialize(
3 user,
4 {
5 bootstrap: {
6 flagKey1: flagValue1,
7 flagKey2: flagValue2
8 }
9 }

A more useful mode in a client-side Node application is to bootstrap from locally cached values. In this mode, if no values have been cached yet, the SDK will obtain flags from LaunchDarkly and then cache them in persistent storage; the next time you start up, the cached flags will be immediately available, and the SDK will also contact LaunchDarkly in the background to obtain updated values if any. To activate this mode, use the special string "localstorage":

1const ldClient = LaunchDarkly.initialize(
3 user,
4 {
5 bootstrap: 'localStorage'
6 }

Changing the user context

You may wish to change the user context dynamically and receive the new set of feature flags for that user or generate events for the new user. To do this, you can call the identify function. You may pass a callback that will be called when the new flags are in effect.

1ldClient.identify(newUser, () => {
2 console.log("New user's flags available");
5// or, with a Promise:
6ldClient.identify(newUser).then(() => {
7 console.log("New user's flags available");


Internally, the LaunchDarkly SDK keeps an analytics event buffer. These events are flushed periodically (asynchronously). In some situations, you may want to manually call flush to process events immediately.

Note that this method is asynchronous. You may pass a callback or wait for the returned Promise to determine when all events have been flushed.

3// or, with a callback:
4ldClient.flush(() => {
5 console.log('flush complete');
8// or, with a Promise:
9ldClient.flush().then(() => {
10 console.log('flush complete');


By default, the SDK uses the winston package. There are four logging levels: debug, info, warn, and error. By default, debug and info messages are hidden.

To learn more, read the TypeScript definitions for LDLogger, LDOptions, and createConsoleLogger for more details.

A custom logger may be passed to the SDK by the configurable logger property. Note that Winston's syntax for instantiating and configuring loggers changed between versions 2.x and 3.x. Be sure to declare a dependency on a specific Winston version if you run into errors using the transitive dependency.

1const logger =
2 new winston.Logger({
3 level: "debug",
4 transports: [
5 new winston.transports.Console()
7 ]
8 }
11const user = {
12 key: "aa0ceb"
15const ldClient = LaunchDarkly.initialize(
17 user,
18 {"logger": logger}