• SDKS
No results for ""


JavaScript SDK reference

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

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. To learn more, read JavaScript 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 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.

Browser support

The LaunchDarkly client-side JavaScript SDK can be used in all major browsers. However, not all browsers have built-in support for the standard APIs that it uses. Those APIs are Promise, EventSource, and querySelectorAll; Promise is always required, the other two are optional depending on which SDK features you use.

The standard solution for ensuring that you will get the same functionality even in browsers that do not have native support for these features is to use polyfills. For a detailed description, and links to information about which browsers may require this, read JS SDK requirements and polyfills.

Getting started

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

The first step is to make the LaunchDarkly SDK available as a dependency. There are two ways to make our JavaScript SDK available: as a module with a package manager, or with a script tag.

Package manager

In most cases, making the LaunchDarkly SDK available to your application or site should be as simple as running one of the following in your project:

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

If you are using a package manager, and then combining dependencies with your code using a tool such as Webpack, there are various ways to import the LaunchDarkly SDK into your code. Here are two examples in commonly used frameworks:

1// using require()
2const LDClient = require('launchdarkly-js-client-sdk');
4// using ES2015 imports
5import * as LDClient from "launchdarkly-js-client-sdk";

Note that in earlier versions of the SDK, the package was named ldclient-js instead of launchdarkly-js-client-sdk.

Script tag

To load our JavaScript SDK as a script tag, include one of 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.

Note that script tags with sources from unpkg and jsdelivr are not intended to be used on production environments as these introduce a critical dependency on a third-party service. The unpkg and jsdelivr scripts are intended to be used only for ease of development and getting started. In production environments, it is highly recommended that the LaunchDarkly SDK is self-hosted alongside your other JavaScript resources.

1<!-- The script tag shown here automatically updates to the
2 newest release that has a major version of 2. A minor
3 version can be specified by including it in the url.
4 See https://unpkg.com for additional examples and information.
6 This method is not recommended for production use. -->
7<script crossorigin="anonymous" src="https://unpkg.com/launchdarkly-js-client-sdk@2"></script>

Initializing the Client

Once the SDK dependency is available, you'll want to initialize 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 without risk.

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.

Code Sample

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

1var user = {
2 "key": "aa0ceb"
4var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user);
Initialization delay

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. To learn more, read Bootstrapping. If the client is bootstrapped, it will emit the ready event immediately.

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:

1ldclient.on('ready', function() {
2 console.log("It's now safe to request feature flags");
3 var showFeature = ldclient.variation("YOUR_FEATURE_KEY", false);
5 if (showFeature) {
6 ...
7 } else {
8 ...
9 }
Streaming Updates

The SDK does not subscribe to streaming real-time updates automatically when it is initialized. As a side effect, subscribing to the SDK's change event by calling .on('change'). 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 before they can be used in variation calls on the front-end. Configure this option on your feature flag's Settings page.

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 pass custom parameters to the client by creating a custom configuration object:

1var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
2 allAttributesPrivate: true

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


Personally-identifying user keys

If the key attribute you rely on in your user JSON contains personally identifiable information, enable the useReport option by customizing your client.

By default, flag settings are fetched by sending the user JSON as base64-encoded using a URL-safe algorithm. When useReport is enabled, flag settings will be fetched by sending the user JSON in the body of a REPORT request instead, thereby hiding that information from request logs.

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:

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

1var user = {
2 "key": "aa0ceb",
3 "name": "Grace Hopper",
4 "email": "gracehopper@example.com"
7var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
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:

1var user = {
2 "key": "aa0ceb",
3 "name": "Grace Hopper",
4 "email": "gracehopper@example.com"
5 "privateAttributeNames": ["email"]
8var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {
9 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:

1// Starting with version 2.10.0 of the JavaScript SDK, to create
2// an anonymous user you can specify the "anonymous" property and
3// omit the "key" property. In doing so, the LaunchDarkly client
4// auto-generates a unique identifier for this user, and the
5// identifier is saved in local storage. This identifier ensures that
6// subsequent browser sessions are consistent.
8// If you do not specify a unique key for each anonymous user,
9// and the user has disabled local storage in their browser, LaunchDarkly
10// will create a new user for each request. The number of people
11// who have disabled local storage in their browsers is likely small
12// but bots and crawlers almost never utilize local storage.
13// but bots and crawlers almost never utilize local storage.
14var user = {"anonymous": true};
16// If you are using earlier SDK versions, you will need to specify
17// the "key" property as earlier versions do not auto-generate the
18// property.
20// Here you will need to generate a unique key for anonymous
21// users. The session ID or a UUID should work.
23// We suggest storing the user's key in a cookie, otherwise you
24// run the risk of creating a new user for each page request.
25var 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. Both alias parameters must have key attributes. If the LaunchDarkly client auto-generated a unique identifier for one of your users, you can access the user's complete object with the getUser method.

1var previousUser = ldclient.getUser();
2ldclient.alias(newUser, previousUser);


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

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

You must enable the `evaluationReasons` option
You must enable the `evaluationReasons` option when you initialize the LaunchDarkly client. If you do not do this, the `reason` object returned by this method is always null.

To learn more, read Customizing your client.

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.

Analytics events

Evaluating flags, either with variation() or with allFlags(), produces analytics events which you can observe on your LaunchDarkly Debugger page. Specifying a user with identify() (and also the initial user specified in the client constructor) also produces an analytics event, which is how LaunchDarkly receives your user data.

You can also explicitly send an event with any data you like using the track function. The second argument is optional.

1ldclient.track("your-event-name", { customProperty: someValue });

If you've defined click or pageview goals 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. The SDK will generate pageview events correctly regardless of how the URL is changed (by the HTML5 history API, by changing the URL hash fragment, etc.).

You can completely disable event sending by setting sendEvents to false in the client options, but be aware that this means you will not have user data on your LaunchDarkly dashboard.

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 events.launchdarkly.com. In addition, ad blocking software may block analytics events from being sent. This will not impact feature flag evaluations.

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', function(settings) {
2 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:

1ldclient.on('change:YOUR_FLAG_KEY', function(value, previous) {
2 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 provides the LaunchDarkly client object an initial, immediately available set of feature flag values that calls variation on page load with no delay. We recommend using one of LaunchDarkly's server-side SDKs to populate a map of flag keys to flag values, called bootstrap values, from your back end.

All of the server-side SDKs have a function to evaluate flags on behalf of a specified user. This function provides the initial set of bootstrap values to your front end. The function is called some variation of "allFlagsState". The exact name varies depending on the back-end technology's naming conventions, such as using camel case or snake case.

Below are two examples of how to bootstrap flags into the JavaScript client:

1// If your back end passes values to your front end on pageload,
2// you can call your server-side SDK's allFlagsState function
3// on pageload and pass the results as a parameter to your
4// front-end initialization code.
5function onPageLoad(flags) {
6 ...
8 var ldclient = LDClient.initialize(
10 user,
11 options = {
12 bootstrap: flags
13 }
14 );
16 ...

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

Alternatively, you can bootstrap feature flags from local storage:

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

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

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

1var crypto = require('crypto');
2var hmac = crypto.createHmac('sha256', 'YOUR_SDK_KEY');
4hash = 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:

1ldclient.identify(newUser, hash, function() {
2 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.

If you provide a callback function, it will be called (with a map of flag keys and values) once the flag values for the new user are available; after that point, variation() will be using the new values. You can also use a Promise for the same purpose.

Note that the SDK always has one current user. The client-side SDKs are not designed for evaluating flags for different users at the same time.

Tracking click and pageview events

If you've defined click or pageview goals 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.

To learn more about click and pageview goals, read Experimentation.

Single-page apps

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

Tracking custom events

You can record custom events using the track function. In LaunchDarkly, you can tie these events to metrics in experiments.

To learn more, read Experimentation.

Call track with the event name to record custom conversion metrics.

The second argument is optional. It assists with observational analytics for Data Export destinations. With Data Export, the second argument gives additional context without saving the data to the LaunchDarkly user.

1ldclient.track("your-event-name", { customProperty: someValue });

For numeric metrics, include a numeric value as a third argument in the call.

1ldclient.track("your-event-name", null, 5);


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.

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