No results for ""
EXPAND ALL
  • Home
  • API docs

GIVE DOCS FEEDBACK

JavaScript SDK reference

Read time: 11 minutes
Last edited: May 21, 2024
Version 3 of the JavaScript SDK replaces users with contexts

A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. Contexts replace another data object in LaunchDarkly: "users."

Code samples on this page are from the two most recent SDK versions where they differ. To learn more about upgrading, read JavaScript SDK 2.x to 3.0 migration guide and Best practices for upgrading users to contexts.

Overview

This topic documents how to get started with the client-side JavaScript SDK, and links to reference information on all of the supported features.

SDK quick links

LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and a sample application:

ResourceLocation
SDK API documentationSDK API docs
GitHub repositoryjs-client-sdk
Sample applicationJavaScript
Published modulenpm
For use in mobile, desktop, and embedded client applications only

This SDK is intended for use in single-user mobile, desktop, and embedded applications. It is intended for client-side (browser) feature flags only. If you have a Node.js application and want to set up LaunchDarkly on the server-side, read the server-side Node.js SDK reference.

To learn more about LaunchDarkly's different SDK types, read Client-side, server-side, and edge SDKs.

Do you need information about Svelte, Angular, or other frameworks?

LaunchDarkly does not offer SDKs for all languages or frameworks. If you're searching for information about using Svelte, Preact, or Angular with LaunchDarkly, you may be able to use the JavaScript SDK instead.

To request support for a specific language or framework, contact Support.

This SDK does two things:

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

The sample code snippets for this SDK are available in both JavaScript and TypeScript, where the sample code differs. To learn more, read Using LaunchDarkly with TypeScript.

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. The SDK always requires Promise, but 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.

Additionally, the JavaScript SDK versions 3.0.0 and 3.1.0 use optional chaining. If you encounter an error related to optional chaining during transpiling, bundling, or running tests, updating to version 3.1.1 should resolve the error.

Do Not Track and ad blocking software

The JavaScript SDK respects the Do Not Track events header. If an end user has Do Not Track enabled in their browser, the SDK does not send analytics events for flag evaluations or metrics to events.launchdarkly.com. To learn more, read Browser privacy settings block analytic events to LaunchDarkly.


In addition, ad-blocking software may block analytics events from being sent. This does not impact feature flag evaluations. To learn more about the events SDKs send to LaunchDarkly, read Analytics events.

Get started

After you complete the Getting started process, follow these instructions to start using the LaunchDarkly JavaScript SDK in your JavaScript code.

You'll need to:

Install the SDK

The first step is to make the JavaScript SDK available as a dependency.

In most cases, making the JavaScript SDK available to your application or site requires running one of the following in your project:

npm install launchdarkly-js-client-sdk

If you are using a package manager, and combining dependencies with your code using a tool such as Webpack, there are various ways to import the JavaScript SDK into your code.

Here are some examples in commonly used frameworks:

// Using require()
const LDClient = require('launchdarkly-js-client-sdk');
// Using ES2015 imports
import * as LDClient from 'launchdarkly-js-client-sdk';
// Using TypeScript imports
import * as LDClient from 'launchdarkly-js-client-sdk';

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

A less common method to make the JavaScript SDK available is with a script tag.

Expand Make the SDK available with a script tag

Make the SDK available with a script tag

To load the 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 metrics for Experimentation.

Do not use script tags from unpkg or jsDelivr in production

The script tag in the self-hosted example below references a script which is deployed alongside other JavaScript resources in your application. We recommend that you use this method in production.

Do not use script tags with sources from unpkg and jsDelivr in production environments. 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, we strongly recommend that you self-host the JavaScript SDK alongside your other JavaScript resources.

If you are working in a development environment, you can load the SDK from unpkg or jsDelivr using the example code below. Replace the <EXAMPLE-VERSION> with your desired version. To learn more, read Releases in the JavaScript SDK GitHub repository. We recommend pinning to an exact SDK version if you are using a third-party hosting service.

Here is an example of code to include in the <head> tag of your site:

<!-- recommended for production environments -->
<script src="path/to/ldclient.min.js"></script>

Initialize the client and evaluate a context

To create a client instance, you need your LaunchDarkly environment's client-side ID. This authorizes your application to connect to a particular environment within LaunchDarkly.

Never embed a server-side SDK key into a client-side application

Client-side IDs are not secret and you can expose them in your client-side code without risk. However, never embed a server-side SDK key into a client-side application.

The JavaScript SDK uses a client-side ID

The JavaScript SDK uses a client-side ID. Your environment's client-side ID is available in the Projects tab of your Account settings page. To learn more about key types, read Keys.

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 determined by the end user viewing the page. You must pass a context to the SDK during initialization before requesting any feature flags with variation. If you fail to pass a valid context to the SDK during initialization, you will receive a 400 error.

Making feature flags available to this SDK

You must make feature flags available to client-side SDKs before the SDK can evaluate those flags. If an SDK tries to evaluate a feature flag that is not available, the context will receive the fallback value for that flag.

To make a flag available to this SDK, check the SDKs using Client-side ID checkbox during flag creation, or on the flag's Settings tab. To make all of a project's flags available to this SDK by default, check the SDKs using Client-side ID checkbox in your project Settings.

Here is an example showing how to initialize the client:

const context = {
kind: 'user',
key: 'context-key-123abc'
};
const client = LDClient.initialize('client-side-id-123abc', context);
Initialization delay

Initializing the client makes a remote request to LaunchDarkly. Depending on your network conditions, it may take a couple hundred milliseconds before the SDK emits the ready event. If you require feature flag values before rendering the page, we recommend bootstrapping the client. If you bootstrap the client, it will emit the ready event immediately. To learn more, read Bootstrapping.

To learn about best practices when using other default flag value methods, read Eliminating flicker when using default flag values.

When you initialize the client, you can optionally provide configuration options. To learn how, read Configuration. To learn more about the specific configuration options available in this SDK, read LDOptions.

LDClient must be a singleton

It's important to make LDClient a singleton for each LaunchDarkly project. The client instance maintains internal state that allows LaunchDarkly to serve feature flags without making any remote requests. Do not instantiate a new client with every request.

If you have multiple LaunchDarkly projects, you can create one LDClient for each. In this situation, the clients operate independently. For example, they do not share a single connection to LaunchDarkly.

To find out when the client is ready, you can use one of two mechanisms:

  • events
  • promises
Expand Use events to determine when the client is ready

Use events to determine when the client is ready

The client object can emit JavaScript events. It emits a ready event when it receives initial flag values from LaunchDarkly. You can listen for this event to determine when the client is ready to evaluate flags.

Here's how:

client.on('ready', () => {
// initialization succeeded, flag values are now available
const flagValue = client.variation('flag-key-123abc', false);
// etc.
});

The client emits the ready event only once, when it finishes initializing. If you receive an error message about the ldclient.on('ready') callback not firing, this means that the SDK began listening for the ready event too late, after the client already emitted it. To fix this, move the ready listener to immediately after you call initialize, or use a promise instead. To learn more, read Error "ldclient.on('ready')" not firing.

Expand Use promises to determine when the client is ready

Use promises to determine when the client is ready

The SDK has two methods that return a promise for initialization:

  • waitUntilReady()
  • waitForInitialization()

waitUntilReady()


The behavior of waitUntilReady() is equivalent to the ready event. The promise resolves when the client receives its initial flag data. As with all promises, you can either use .then() to provide a callback, or use await if you are writing asynchronous code.

Here is an example:

client.waitUntilReady().then(() => {
// initialization succeeded,
// flag values are now available through the client
});
// or, with await:
await client.waitUntilReady();
// initialization succeeded,
// flag values are now available through the client

waitForInitialization()


The other method that returns a promise, waitForInitialization(), is similar to waitUntilReady() except that it also tells you if initialization fails by rejecting the promise. This method never rejects the waitUntilReady() promise.

Always include a timeout parameter

Do not configure your SDK to initialize without a timeout parameter. Doing so will cause your app never to load if there is a connectivity problem. We recommend setting a timeout for no more than 1-5 seconds.

Here is an example:

client.waitForInitialization(5).then(() => {
// initialization succeeded, flag values are now available
}).catch(err => {
// initialization failed
});
// or, with await:
try {
await client.waitForInitialization(5);
// initialization succeeded, flag values are now available
} catch (err) {
// initialization failed
}

The SDK only decides initialization has failed if it receives an error response indicating that the client-side ID is invalid. If it has trouble connecting to LaunchDarkly, it will keep retrying until it succeeds.

Subscribe to flag changes

The SDK does not subscribe to streaming real-time updates automatically when you initialize it.

In some cases, streaming may not be necessary. For example, if you reload your entire application on each update, you will get all the flag values again when the client is re-initialized. If this is your use case, you should leave the streaming value undefined, which is the default.

In other cases, streaming may be required. Subscribing to streaming is the only way to receive real-time updates. If you determine that streaming is necessary for your application, there are two ways to subscribe to streaming:

  • Explicitly subscribe to streaming: If you set the streaming configuration option to true, the client will always attempt to maintain a streaming connection.
  • Register a change listener: If you subscribe to change or change:flag-key events, the client will open a streaming connection. It will close this streaming connection when you unsubscribe from the event, for example by calling .off('change:flag-key'). Because opening and closing streaming connections can be expensive, you should explicitly enable streaming if your application frequently starts and stops listening to changes.

If you do enable streaming through either of these methods, you will also need EventSource. If you also enable the SDK's useReport configuration option, you will need LaunchDarkly's EventSource polyfill. To learn more, read EventSource.

To learn more, read streaming.

Shut down the client

Shut down the client when your application terminates. To learn more, read Shutting down.

Supported features

This SDK supports the following features: