JavaScript SDK reference
Read time: 11 minutes
Last edited: Feb 24, 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.
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 install the LaunchDarkly SDK as a dependency. 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.
In most cases, it 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');34// using ES2015 imports5import * 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 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:
Integrating with the LaunchDarkly JavaScript SDK as a script tag is only intended for development environments and getting started with using LaunchDarkly. It is not intended to be used in production environments as this introduces a critical dependency on a third-party service, unpkg. Previously it was suggested to use the JS SDK hosted on LaunchDarkly's servers in script tags. This URL would point to the most recently released SDK version. To give more control over SDK updates unpkg is now suggested, and the version hosted at "https://app.launchdarkly.com/snippet/ldclient.min.js" is frozen at release 2.10.1.
1<!-- The snippet shown here will automatically update to the2 newest release that has a major version of 2. A minor3 version can be specified by including it in the url. -->4<script crossorigin="anonymous" src="https://unpkg.com/launchdarkly-js-client-sdk@2"></script>
Initializing the Client
Once the dependency is installed, 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"3};4var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user);
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);45 if (showFeature) {6 ...7 } else {8 ...9 }10});
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.
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 pass custom parameters to the client by creating a custom configuration object:
1var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {2 allAttributesPrivate: true3});
To learn more about the specific configuration options that are available in this SDK, read the SDK's API docs.
Users
If the key
attribute you rely on in your user JSON contains personally identifiable information, you should enable
the useReport
option by customizing your
client . By default, flag settings are
fetched by sending the user JSON as a JSON base64 URL-encoded path parameter. 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 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:
1var user = {2 "key": "aa0ceb",3 "firstName": "Ernestina",4 "lastName": "Evans",5 "email": "ernestina@example.com",6 "custom": {7 "groups": ["Google", "Microsoft"]8 }9};
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 anavatar
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 nameanonymous
: 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.
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, 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"5};67var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {8 allAttributesPrivate: true9});
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"]6};78var ldclient = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user, options = {9 privateAttributeNames: ["email"]10});
In the example above, only the user's key and their name will be sent back to LaunchDarkly.
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 create2// an anonymous user you can specify the "anonymous" property and3// omit the "key" property. In doing so, the LaunchDarkly client4// will auto-generate a unique identifier for this user, and the5// identifier will remain constant across browser sessions.6var user = {"anonymous": true};78// If you are using earlier SDK versions, you will need to specify9// the "key" property as earlier versions do not auto-generate the10// property.11//12// Here you will need to generate a unique key for anonymous13// users. The session ID or a UUID should work.14//15// We suggest storing the user's key in a cookie, otherwise you16// run the risk of creating a new user for each page request.17var user2 = {"key":"aa0ceb", "anonymous": true};
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.
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);
Variation
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.
VariationDetail
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.
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.
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);3});
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 + ')');3});
All flags
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
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 flag keys to flag values) from your back-end using one of LaunchDarkly's server-side SDKs. All of the server-side SDKs have a function to evaluate flags on behalf of a specified user. It is named along the lines of "allFlagsState" -- although, the exact name varies depending on the back-end technology's conventions (for example, camel-case versus snake-case). This function can provide the initial set of bootstrap values to your front-end.
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 function3// on pageload and pass the results as a parameter to your4// front-end initialization code.5function onPageLoad(flags) {6 ...78 var ldclient = LDClient.initialize(9 'YOUR_CLIENT_SIDE_ID',10 user,11 options = {12 bootstrap: flags13 }14 );1516 ...17}
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'3});
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 = {2 hash: "SERVER_GENERATED_HASH"3});
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 client3});
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');3hmac.update('YOUR_USER_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");3});
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.
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 (float
or int
are accepted) as a third argument in the call.
1ldclient.track("your-event-name", null, 5);
Flush
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.
1ldclient.flush();