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

Get Started    Guides

JavaScript SDK Reference

This reference guide documents all of the methods available in our client-side JavaScript SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source-- head to our JavaScript SDK GitHub repository to look under the hood.

For client-side JavaScript only

Our JavaScript SDK is intended for client-side (browser) feature flags only.

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.

This SDK does two things:

  • Makes feature flags available to your client-side (front-end) JavaScript code.
  • Sends click, pageview, and custom events from your front-end for A/B tests and analytics.

Getting started

There are two ways to install our JavaScript SDK-- as an npm, yarn or bower module, or as a JavaScript snippet served from LaunchDarkly's CDN.

If you haven't taken a look at our Quickstart guide yet, we recommend starting there to see how install our SDK into your client-side JavaScript as a module. In most cases, it should be as simple as running the following in your project:

npm install --save ldclient-js

If you're using yarn, the following should work:

yarn add ldclient-js

If you're using bower:

bower install

To load our JavaScript SDK as a script tag, include the following in the <head> tag of your site on any pages where you need feature flags or want to track A/B testing goals:

<script crossorigin="anonymous" src=""></script>

Browser support

The LaunchDarkly client-side JavaScript SDK supports all major browsers.

Streaming support for real-time feature flag updates requires a browser with support for the EventSource API. EventSource is a technology where a browser receives automatic updates from a server through a HTTP connection. The Server-Sent Events EventSource API is a standardized as part of HTML5 by the W3C.

If you need streaming support, and you wish to support browsers that do not support EventSource natively, you can install a polyfill.

You can load the polyfill via a script tag in the <head> before the script where you initialize LDClient:

<script src="/public/eventsource-polyfill.js"></script>

If you use webpack or browserify, make sure to require the polyfill before LDClient is initialized.

You can find a list of EventSource polyfills here.
You can also find a list of browsers that have native support for EventSource here.

A note on Do Not Track and ad blocking software

The JavaScript SDK respects the Do Not Track header. If an end-user has Do Not Track enabled in their browser, the SDK will not send analytics events for flag evaluations or goals to In addition, ad blocking software may block analytics events from being sent. This will not impact feature flag evaluations.

Initializing the 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-- they can be safely exposed in your client-side code.

In practice, you will probably want to templatize your client-side ID, so that you can use the same initialization code when you switch between development, QA, and production environments.

Feature flag targeting and rollouts are all determined by the user viewing the page. 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 a 400 error.

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

var user = {
  "key": "aa0ceb"
var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user);

The client will emit a ready event when it has been initialized. Once it has been initialized, you can safely call variation to access your feature flags:

ldclient.on('ready', function() {
  console.log("It's now safe to request feature flags");
  var showFeature = ldclient.variation("YOUR_FEATURE_KEY", false);

  if (showFeature) {
  } else {

Out of the box, initializing the client will make a remote request to LaunchDarkly, so it may take 100 milliseconds or more before the ready event is emitted. If you require feature flag values before rendering the page, we recommend bootstrapping the client (see the Bootstrapping section). If the client is bootstrapped, it will emit the ready event immediately.

Streaming Updates

The SDK does not subscribe to streaming real-time updates automatically when it is initialized. As a side effect, calling the SDK's on will cause the SDK to open a streaming connection to LaunchDarkly. This is the only way to receive realtime updates.

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.

Customizing your client

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

var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
  hideUserData: true

hash: See Secure Mode
bootstrap:See Bootstrapping
baseUrl: Sets the base URL of the LaunchDarkly server for this configuration. Defaults to
eventsUrl: Sets the events URL of the LaunchDarkly server for this configuration. Defaults to
streamUrl: Set the stream URL of the LaunchDarkly server for this configuration.
Defaults to


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 e-mail 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:

var user = {
  "key": "aa0ceb",
  "firstName": "Ernestina",
  "lastName": "Evans",
  "email": "",
  "custom": {
    "groups": ["Google", "Microsoft"]

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

var user = {
  "key": "aa0ceb",
  "name": "Bob Loblaw",
  "email": ""

var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
  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:

var user = {
  "key": "aa0ceb",
  "name": "Bob Loblaw",
  "email": "",
  "privateAttributeNames": ["email"]

var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
  privateAttributeNames: ["email"]

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

Parameters for JS SDK < 2.0

SDK versions earlier than 2.0 use snake case rather than camel case in the options object. private_attribute_names and all_attributes_private are the parameter names that should be used. privateAttributeNames is still valid when specified in the user object.

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!


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

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


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:

ldclient.on('change', function(settings) {
  console.log('flags changed:', settings);

The settings 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:

ldclient.on('change:YOUR_FLAG_KEY', function(value, previous) {
  console.log('YOUR_FLAG_KEY changed:', value, '(' + previous + ')');

All flags

Creating users

Note that the allFlags method in the JavaScript SDK functions differently than our other SDKs.

This method will send 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 so that on page load variation can be called with no delay.

The preferred approach to bootstrapping is to populate the bootstrap values (a map of feature flag keys to flag values) from your backend. LaunchDarkly's server-side SDKs have a function called all_flags_state-- this function provides the initial set of bootstrap values. (In earlier versions of the SDKs, this function was called all_flags).You can then provide these values to your front-end as a template. Depending on your templating language and the language you are using on the back end (this example is for Ruby), this might look something like this:

var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
    {{ ldclient.all_flags_state(user, {client_side_only: true}) }} // this is a template directive

If you bootstrap from the server-side, feature flags will be ready immediately, and clients will always receive the latest feature flag values. An demonstration of server-side bootstrapping can be found in this github repo.

Alternatively, you can bootstrap feature flags from local storage:

var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
  bootstrap: 'localStorage'

When using local storage, the client will store the latest flag settings in local storage. On page load, the previous settings will be used and the 'ready' event will be emitted immediately. This means that on page load, the user may see cached flag values until the next page load.

You can still subscribe to flag changes if you're using local storage.

Secure mode

Secure mode ensures that feature flag settings for a user are kept private, and that one user cannot inspect the settings for another user. Secure mode works by having you include a server-generated HMAC SHA256 hash of your user key, signed with the SDK key for your environment.

You can enable secure mode for each environment on your account settings page.

You should send the computed hash for your user in the options array during client initialization:

var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {

Each of our server-side SDKs includes a method to compute the secure mode hash for a user. You can pass this to your front-end code in a template. For example:

var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
  hash: {{ ldclient.secure_mode_hash(user) }} // this is a template directive, and the ldclient instance here is your server-side SDK client

To compute the hash yourself, locate the SDK key for your environment on your account settings page. Then, compute an HMAC SHA256 hash of your user key, using your SDK key as a secret. Here's what this would look like in Node.js:

var crypto = require('crypto');
var hmac = crypto.createHmac('sha256', 'YOUR_SDK_KEY');
hash = hmac.digest('hex');

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. For example, on a sign-in page in a single-page app, you might initialize the client with an anonymous user. When the user logs in, you'd want the feature flag settings for the authenticated user. To do this, you can call the identify function:

ldclient.identify(newUser, hash, function() {
  console.log("New user's flags available");

The hash parameter is the hash for the new user, assuming that the user's key has changed. It is only required in secure mode-- if secure mode is not enabled, you can pass in null for the hash.

Tracking click and pageview events

If you've defined click or pageview goals (see Running A/B tests) in LaunchDarkly, they'll be sent automatically once the client has been initialized. You do not have to do anything else with the client to send click or pageview goals.

Single-page apps

The SDK automatically handles URL changes (made via the HTML5 history API or by changing the URL hash fragment), and will trigger pageview and click events correctly.


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.