LaunchDarkly Developer Documentation

Get started in under 30 minutes.
LaunchDarkly provides feature flags as a service for Java · Python · Ruby · Go · Node.js · PHP · .NET. Control feature launches -- who sees what and when -- without multiple code deploys. Easy dashboard for phased rollouts, targeting and segmenting.
Need more help? write us at support@launchdarkly.com

Get Started    Guides

Node.js SDK Reference

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-- head to our Node.js SDK repository on GitHub to look under the hood.

Client-side feature flags?

Our Node.js SDK is designed specifically for server-side Node.js.

If you're looking to use feature flags in your client-side JavaScript, see our JavaScript SDK Reference.

Getting started

If you haven't taken a look at our Quickstart guide yet, we recommend starting there to see how install our SDK into your Node.js application.

Once the SDK is installed, you'll want to create a single, shared instance of the LaunchDarkly client:

ld_client = LaunchDarkly.init("YOUR_SDK_KEY");

LDClient must be a singleton

It's important to make this a singleton-- internally, 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:

ld_client.once(`ready`, function() {
	ld_client.variation(...);
})

Customizing your client

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

var config = {"timeout": 3};
ld_client = LaunchDarkly.init("YOUR_SDK_KEY", config);
Parameters
Type
Description
Default

timeout

int

Must be a number, in seconds, and controls the request timeout to LaunchDarkly.

5 seconds

capacity

int

Must be a number, and controls the maximum size of the event buffer. LaunchDarkly sends events asynchronously, and buffers them for efficiency.

1000 events

logger

object

Configures a logger for warnings and errors generated by the SDK.

See Logging

flushInterval

int

Controls how long the SDK buffers events before sending them back to our server. If your server generates many events per second, we suggest decreasing the flush_interval and / or increasing capacity to meet your needs.

5 seconds

proxyHost

string

Allows you to specify a host for an optional HTTP proxy.

null

proxyPort

int

Allows you to specify a port for an optional HTTP proxy. Both the host and port must be specified to enable proxy support.

null

proxyAuth

string

Allows you to specify basic authentication parameters for an optional HTTP proxy. Usually of the form username:password

null

offline

bool

Whether the client should be initialized in offline mode. In offline mode, default values are returned for all flags and no remote network requests are made.

false

stream

bool

Whether streaming or polling should be used to receive flag updates.

true

useLdd

bool

If true, the SDK will rely on LDD for feature updates. See Deployment options for more details.

false

baseUri

Uri or string

Set the base URL of the LaunchDarkly server for this configuration.

streamUri

Uri or string

Set the stream URL of the LaunchDarkly server for this configuration.

eventsUri

Uri or string

Set the events URL of the LaunchDarkly server for this configuration.

featureStore

InMemoryFeatureStore or RedisFeatureStore

Sets the feature flag store to be used by the client.

flags are stored in memory, with an option to use a redis feature store.

allAttributesPrivate

bool

Whether all user attributes (except the user key) should be marked as private, and not sent to LaunchDarkly.

false

privateAttributeNames

An array of strings

Must be a list of strings. The names of user attributes that should be marked as private, and not sent to LaunchDarkly.

[]

userKeysCapacity

integer

The number of user keys that the event processor can remember at any one time, so that duplicate user details will not be sent in analytics events.

1000

userKeysFlushInterval

integer

The interval (in seconds) at which the event processor will reset its set of known user keys.

300

inlineUsersInEvents

bool

Whether to include full user details in every analytics event. By default, events will only include the user key, except for one "index" event that provides*
the full details for the user.

false

Users

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:

var user = {
  "key": "aa0ceb",
  "firstName": "Ernestina",
  "lastName": "Evans",
  "email": "ernestina@example.com",
  "custom": {
    "groups": ["Google", "Microsoft"]
  }
};

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 e-mail 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. If you provide an IP, LaunchDarkly will use a geolocation service to automatically infer a country for the user (unless you've already specified one).
  • 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 e-mail 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 e-mail 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-- organizations, groups, 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:

var user = {
  "key": "aa0ceb",
  "email": "test@example.com",
  "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:

var 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-- it keeps anonymous users from polluting your Users page!

Variation

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

ld_client.variation("your.feature.key", user, false, function(err, show_feature) {
  if (show_feature) {
      # application code to show the feature
  }
  else {
      # the code to run if the feature is off 
  } 
});

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

Track

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:

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

Identify

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 will automatically create users on the dashboard for you. identify can be useful if you want to pre-populate your dashboard before launching any features.

ld_client.identify(user);

All flags

Creating users

Note that unlike variation and identify calls, allFlagsState does not send events to LaunchDarkly. Thus, users are not created or updated in the LaunchDarkly dashboard and your flags' last requested date will not be 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, it can be used to provide bootstrap flag settings for our JavaScript SDK.

ld_client.allFlagsState(user, function(err, flagsState) {
  // this object can be converted to JSON or can be queried for flag values
});

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.

ld_client.secureModeHash(user);

Flush

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.

ld_client.flush();

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

var config = {"offline": true};
ld_client = LaunchDarkly.init("YOUR_SDK_KEY", config);
ld_client.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

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.

ld_client.close();

Logging

The Node.js SDK uses Winston by default. All loggers are namespaced under [LaunchDarkly]. A custom logger may be passed to the SDK via the configurable logger property:

logger =
  new winston.Logger({
    level: "debug",
    transports: [
      new(winston.transports.Console)(),
    ]
  }
);
ldclient = 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.

Redis

The Node SDK provides an option to use Redis as a persistent store of feature flag configurations. Here's an example client configuration hooked up to a Redis instance:

var LaunchDarkly = require("ldclient-node");

var redisOptions = {port: process.env.REDIS_PORT, host: process.env.REDIS_ENDPOINT}
var store = new LaunchDarkly.RedisFeatureStore(redisOptions)
var config = {feature_store: store, offline: true}

var ldClient = LaunchDarkly.init("YOUR_SDK_KEY", config)

Configuration options (passed in as parameters to RedisFeatureStore):

Parameter
Description

redisOpts

A JSON object containing configurable options for the Redis connection. Full configuration details can be found in the (NodeRedis)[https://github.com/NodeRedis/node_redis#rediscreateclient] documentation.

cacheTTL

Specifies an expiry time for cached feature flag configurations. Defaults to 0.

prefix

Configures the namespace prefix for all keys stored in Redis. Defaults to launchdarkly.

logger

Configures a logger for warnings and errors generated by RedisFeatureStore

Promises

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.

There is also an alternative to the ready event:

ld_client.waitForInitialization().then(function(client) {
	// initialization complete
}).catch(function(err) {
  // initialization failed
});

Then, retrieving a flag setting for a given user can be done this way:

ld_client.variation("any.feature.flag", user, false).then(function(value) {
  // application code
});

allFlags and flush also return a Promise.

Node.js SDK Reference