• SDKS
No results for ""


Node.js SDK reference (server-side)

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

This reference guide documents all of the methods available in our 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 Node.js SDK repository on GitHub. The online API docs contain the programmatic definitions of every type and method. Additionally you can clone and run sample applications using this SDK with vanilla JavaScript, TypeScript, and server-side bootstrapping.

For use in server-side applications only

This SDK is intended for use in multi-user Node.js server applications. If you're looking to set up LaunchDarkly in JavaScript in a browser environment, read JavaScript SDK. If you're creating a client-side Node application, read Node SDK. Alternatively if you're creating a desktop application in Electron, read Electron SDK.

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

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 application.

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

1npm install launchdarkly-node-server-sdk --save
3# Note that in earlier versions, the package name was ldclient-node

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

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

Once the SDK is installed and imported, you'll want to create a single, shared instance of the LaunchDarkly client. You should specify your SDK key here so that your application will be authorized to connect to LaunchDarkly and for your application and environment.

1ldClient = LaunchDarkly.init("YOUR_SDK_KEY");
LDClient must be a singleton
It's important to make this a singleton. The client instance maintains internal state that allows us to serve feature flags without making any remote requests. **Be sure that you're not instantiating a new client with every request.**

The client will emit a ready event when it has been initialized and can serve feature flags.

Using ldClient, you can check which variation a particular user should receive for a given feature flag. Note that the ready event is only emitted once - when the client first initializes. In a production application you should place your ldClient.variation code so that it is invoked as desired.

1ldClient.once("ready", () => {
2 ldClient.variation("your.flag.key", {"key": "user@test.com"}, false,
3 (err, showFeature) => {
4 if (showFeature) {
5 // application code to show the feature
6 } else {
7 // the code to run if the feature is off
8 }
9 });

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.

1// This example repeats the code from the previous example because in Node, the client methods are
2// asynchronous, so in order to add another step that happens after the previous steps are finished,
3// we need to add code *inside* the existing block. In other words, do not type the whole thing over
4// again, just modify the last part you added as shown.
6// Again, in a real application, this step is something you would only do when the application is
7// about to quit, not after every call to variation().
9ldClient.once("ready", () => {
10 ldClient.variation("your.flag.key", {"key": "user@test.com"}, false,
11 (err, showFeature) => {
12 if (showFeature) {
13 // application code to show the feature
14 } else {
15 // the code to run if the feature is off
16 }
18 // ADDED: shut down the client, since we're about to quit
19 ldClient.close();
20 });

Customizing your client

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

1var config = {"timeout": 3};
2ldClient = LaunchDarkly.init("YOUR_SDK_KEY", config);

To learn more about the specific configuration options that are available in this SDK, read the SDK's API docs.


Feature flag targeting and rollouts are all determined by the user you pass to your variation calls. In our Node.JS SDK, users are simply JSON objects. Here's an example:

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

Let's walk through this snippet. 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.

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, and account plans. Anything you pass to us becomes available instantly on our dashboard.

Private user attributes

You can optionally configure the Node SDK to treat some or 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.

In the Node SDK there are two ways to define private attributes for the entire LaunchDarkly client:

  • In the LaunchDarkly config, you can set allAttributesPrivate to true. If this is enabled, all user attributes (except the key) for all users are removed before the user is sent to LaunchDarkly.
  • In the LaunchDarkly config object, you can define a list of privateAttributeNames. If any user has a custom or built-in attribute named in this list, it will be removed before the user is sent to LaunchDarkly.

You can also define a set of privateAttributeNames on the user object itself. For example:

1var user = {
2 "key": "aa0ceb",
3 "email": "test@example.com",
4 "privateAttributeNames": ["email"]

When this user is sent back to LaunchDarkly, the email attribute will be removed.

Anonymous users

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

1var user = {"key":"aa0ceb", "anonymous": true};

You will still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. You also can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. This is actually a good thing, because it keeps anonymous users from polluting your Users page!

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. 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.

1ldClient.variation("your.feature.key", user, false,
2 (err, show_feature) => {
3 if (show_feature) {
4 // application code to show the feature
5 }
6 else {
7 // the code to run if the feature is off
8 }
9 });

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

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

The variation call will automatically create a user in LaunchDarkly if a user with that user key doesn't exist already. There's no need to create users ahead of time (but if you do need to, take a look at Identify).


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 on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. Here's a simple example:

1ldClient.track("your-goal-key", user);


The identify method creates or updates users on LaunchDarkly, making them available for targeting and autocomplete on the dashboard. In most cases, you won't need to call identify. The variation call automatically creates users on the dashboard for you. identify can be useful if you want to pre-populate your dashboard before launching any features.


All flags

Creating user
Unlike variation and identify calls, allFlagsState does not send events to LaunchDarkly. Instead, users are not created or updated in the LaunchDarkly dashboard and your flags' last requested date is not updated.

The allFlagsState method captures the state of all feature flag keys with regard to a specific user. This includes their values, as well as other metadata.

This method can be useful for passing feature flags to your front-end. In particular, you can use it to provide bootstrap flag settings for our JavaScript SDK.

1ldClient.allFlagsState(user, (err, flagsState) => {
2 // this object can be converted to JSON or can be queried for flag values

Subscribing to feature flag changes

This feature is not available in all SDKs
Most of LaunchDarkly's server-side SDKs do not support subscribing to feature flag changes. All of the client-side SDKs do support this feature.

The SDK provides an event-based mechanism to notify you when flag configurations change.

For example, imagine you have a feature flag named EXAMPLE_FLAG_KEY. If the SDK detects a change in EXAMPLE_FLAG_KEY's configuration, or in anything else that could indirectly affect the flag value, such as a prerequisite flag or a user segment that EXAMPLE_FLAG_KEY uses, it emits two events.

These events are:

  • "update" and
  • "update:EXAMPLE_FLAG_KEY".

You can listen for "update:EXAMPLE_FLAG_KEY" if you only want to know about updates affecting that flag specifically, or "update" if you want to know about all updates.

For both of these event types, an extra parameter is sent to event listeners. This object has the single property key, with its value set to the flag key. If you listened for the general "update" event, this lets you see which flag changed.

The event parameter does not contain the flag value. In server-side SDKs, there is no such thing as a flag value except when it is evaluated for a specific set of user properties.

To find out what the effect, if any, of the configuration change was, call variation() after receiving an update event.

1ldClient.on('update', (param) => {
2 console.log('a flag was changed: ' + param.key);
5ldClient.on('update:EXAMPLE_FLAG_KEY', () => {
6 console.log('the EXAMPLE_FLAG_KEY flag was changed');

The full list of events the SDK emits is:

  • error: This contains an error describing an abnormal condition that the client detects, such as a network error
  • ready: This is sent only once, when the client successfully connects to LaunchDarkly
  • failed: This is sent only once, if the client fails to connect to LaunchDarkly
  • update: This is sent when the client receives a change to a feature flag
  • update:EXAMPLE_FLAG_KEY: This is sent when the client receives a change to a feature flag with a specific key

Secure mode hash

The secureModeHash method computes an HMAC signature of a user signed with the client's SDK key. If you're using our JavaScript SDK for client-side flags, this method generates the signature you need for secure mode.



Internally, the LaunchDarkly SDK keeps an event buffer for track and identify calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a REPL), you may want to manually call flush to process events immediately.


The flush interval is configurable. If you need to change the interval, you can do so when configuring your client instance.

Offline mode

In some situations, you might want to stop making remote calls to LaunchDarkly and fall back to default values for your feature flags. For example, if your software is both cloud-hosted and distributed to customers to run on premise, it might make sense to fall back to defaults when running on premise. You can do this by setting offline mode in the client's config object.

1var config = {"offline": true};
2ldClient = LaunchDarkly.init("YOUR_SDK_KEY", config);
3ldClient.variation("any.feature.flag", user, false, cb) // cb will always be invoked with the default value (false)

Note that the default value you set in the variation method will be returned in offline mode, this does not refer to the default rule set in your flag configuration.


Close safely shuts down the client instance and releases all resources associated with the client. In most long-running applications, you should not have to call close.



The Node.js SDK uses Winston by default. All loggers are namespaced under [LaunchDarkly].

You can pass a custom logger to the SDK with the configurable logger property. To learn more about the logger's requirements and methods, read LDLogger.

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.

1logger = new winston.Logger({
2 level: "debug",
3 transports: [
4 new winston.transports.Console()
5 ]
7ldClient = LaunchDarkly.init("YOUR_SDK_KEY", {"logger": logger});

Be aware of two considerations when enabling the DEBUG log level:

  1. Debug-level logs can be very verbose. It is not recommended that you turn on debug logging in high-volume environments.
  2. Potentially sensitive information is logged including LaunchDarkly users created by you in your usage of this SDK.

Database integrations

Feature flag data can be cached with Redis, DynamoDB, or Consul.

To learn more, read Using a persistent feature store.

Promises and async

All asynchronous SDK methods which accept a callback also return a Promise. This means that if your application uses promises to manage asynchronous operations, interacting with the SDK should be convenient. Since the async/await syntax is based on Promises, these methods will also work with await.

1// Using the .then() method to add a continuation handler for a Promise
2ldClient.variation("any.feature.flag", user, false).then((value) => {
3 // application code
6// Using "await" instead, within an async function
7var value = await ldClient.variation("any.feature.flag", user, false);

There is also an alternative to the ready event:

1// Using .then() and .catch() to add success and error handlers to a Promise
2ldClient.waitForInitialization().then((client) => {
3 // initialization complete
4}).catch((err) => {
5 // initialization failed
8// Using "await" instead, within an async function
9try {
10 await ldClient.waitForInitialization();
11 // initialization complete
12} catch (err) {
13 // initialization failed

allFlagsState and flush also return a Promise.