• Home
  • Integrations
  • SDKs
  • Guides
  • API docs
No results for ""
EXPAND ALL

EDIT ON GITHUB

JavaScript SDK reference

Read time: 5 minutes
Last edited: May 20, 2022

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 applicationhello-js
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 and server-side 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, VueJS, 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.

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 goals. 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.

Getting started

After you complete the Getting started process, follow these instructions to start 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.

Making the SDK available with a package manager

In most cases, making the LaunchDarkly 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 LaunchDarkly SDK into your code.

Here are two 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.

Making the SDK available with a 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.

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

Initializing the client

After you install the dependency, initialize the LaunchDarkly client. To create a client instance, you need your environment's client-side ID, available in the Projects tab of your Account settings page. Client-side IDs are not secret and you can expose them in your client-side code without risk. Never embed a server-side SDK key into a client-side application.

LDClient must be a singleton

It's important to make LDClient a singleton. 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.

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

Here is an example showing how to initialize the client:

const user = {
key: 'aa0ceb'
};
const client = LDClient.initialize('YOUR_CLIENT_SIDE_ID', user);
Initialization delay

Initializing the client makes a remote request to LaunchDarkly, so it may take 100 milliseconds or more 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 find out when the client is ready, you can use one of two mechanisms: events or promises.

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('YOUR_FEATURE_KEY', false);
// etc.
});
Streaming Updates

The SDK does not subscribe to streaming real-time updates automatically when you initialize it. This means subscribing to the SDK's change event by calling .on('change'). causes the SDK to open a streaming connection to LaunchDarkly. This is the only way to receive realtime updates.

Or, you can use a promise instead of an event. The SDK has two methods that return a promise for initialization: waitUntilReady() and waitForInitialization(). 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
});
// or, with await:
await client.waitUntilReady();
// initialization succeeded, flag values are now available

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.

Here is an example:

client.waitForInitialization().then(() => {
// initialization succeeded, flag values are now available
}).catch(err => {
// initialization failed
});
// or, with await:
try {
await client.waitForInitialization();
// 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 environment ID is invalid. If it has trouble connecting to LaunchDarkly, it will keep retrying until it succeeds.

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 user will receive the default 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.

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

Supported features

This SDK supports the following features: