JavaScript SDK reference
Read time: 10 minutes
Last edited: Oct 02, 2024
A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. 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.
LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and a sample application:
Resource | Location |
---|---|
SDK API documentation | SDK API docs |
GitHub repository | js-client-sdk |
Sample application | JavaScript |
Published module | npm |
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.
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, start a Support ticket.
This SDK does two things:
- Makes feature flags available to your client-side (front-end) JavaScript code.
- Sends
click
,page view
, andcustom
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. 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.
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 Get started process, follow these instructions to start using the LaunchDarkly JavaScript SDK in your JavaScript code:
- Install the SDK
- Initialize the client
- Determine when the client is ready, using an event or promise
- Subscribe to flag changes
- Shut down the client when your application terminates
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 importsimport * as LDClient from 'launchdarkly-js-client-sdk';// Using TypeScript importsimport * 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.
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
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.
The JavaScript SDK uses a client-side ID. Client-side IDs are specific to each project and environment. They are available from the Environments list for each project. To learn more about key types, read Keys.
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.
We recommend that you 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, which describes this end user, to the SDK during initialization before you can request any feature flags. If you fail to pass a valid context to the SDK during initialization, you will receive a 400 error.
To initialize the client:
const context = {kind: 'user',key: 'context-key-123abc'};const client = LDClient.initialize('client-side-id-123abc', context);
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
.
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.
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.
Determine when the client is ready
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 availableconst 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
You can use the waitForInitialization()
method to determine when the client is ready. This method rejects the promise if initialization fails. The waitForInitialization()
method takes a timeout, which we recommend setting to five seconds or fewer. If you use a large timeout and await it, then any network delays will cause your application to wait a long time before continuing execution.
Here is an example:
try {await client.waitForInitialization(5);// initialization succeeded, flag values are now available} catch (err) {// initialization failed or did not complete before timeout}
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.
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.
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 totrue
, the client will always attempt to maintain a streaming connection. - Register a change listener: If you subscribe to
change
orchange: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
.
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 end user 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 page. To make all of a project's flags available to this SDK by default, check the SDKs using Client-side ID checkbox on your project's Flag settings page.
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:
- Anonymous contexts and users
- Bootstrapping
- Configuration, including
- Context configuration
- Evaluating flags
- Flag evaluation reasons
- Flushing events
- Getting all flags
- Identifying and changing contexts
- Inspectors
- Logging
- Private attributes
- Relay Proxy configuration, using proxy mode
- Secure mode
- Sending custom events
- Service endpoint configuration
- Shutting down
- Subscribing to flag changes