SDK quick linksLaunchDarkly’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 |
| Supported SDK Versions | JavaScript client SDK |
| GitHub repository | browser |
| Sample application | JavaScript |
| Published module | npm |
For use in mobile, desktop, and embedded client applications onlyThis 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 Choosing an SDK type.
- Makes feature flags available to your client-side (front-end) JavaScript code.
- Sends
click,page view, andcustomevents 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.Do Not Track and ad blocking softwareIn v4.x of the JavaScript SDK, you can disable sending events by setting the
sendEvents configuration to false.Version 3.x of the JavaScript SDK respects the Do Not Track events header. If an end user has Do Not Track enabled in their browser, v3.x of the SDK does not send analytics events for flag evaluations or metrics to
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.events.launchdarkly.com. 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. We recommend making the LaunchDarkly observability plugins available as well. These plugins collect and send observability data to LaunchDarkly, including metrics autogenerated from observability events. This means you can review session replay, error monitoring, logs, and traces from within the LaunchDarkly UI. They require the JavaScript SDK version 3.7 or later. In most cases, making the JavaScript SDK available to your application or site requires running one of the following in your project:require), ES modules (import), or TypeScript (import with type support):
@launchdarkly/js-client-sdk. In earlier versions of the SDK, the package was named ldclient-js or 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
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.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:Initialize the client
To create a client instance, you need your LaunchDarkly environment’s client-side ID and the context for which you want to evaluate flags. This authorizes your application to connect to a particular environment within LaunchDarkly. 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, first create an instance. The client begins attempting to connect to LaunchDarkly as soon as it is created. 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 evaluate flags before the client has finished connecting to LaunchDarkly, the evaluation returns the fallback values. This may be acceptable depending on how reactive your application is and what you are using flags for in your application. If you require feature flag values before rendering the page, we recommend using one of the following options:- Bootstrap the client by providing an initial set of flag values that are immediately available during client initialization. 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.
- Use
waitForInitialization()to determine when the client has finished connecting to LaunchDarkly. This method takes a timeout, which we recommend setting to five seconds or fewer. It can also return an error, which you must handle in your application. To learn more, read Determine when the client is ready, below.
handleInitializedClient is not provided by the SDK
handleInitializedClient is not provided by the SDK. It represents your application logic that should run once the LaunchDarkly client is initialized.LDOptions.
We recommend making the LaunchDarkly observability plugins available as well, as shown in the configuration options above.
Determine when the client is ready
The client begins attempting to connect to LaunchDarkly as soon as it is created. Then, you must check that it is ready to use. If you do not confirm this, your application may wait indefinitely if LaunchDarkly is unavailable. 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
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 aready 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: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
Expand Use promises to determine when the client is ready
Use promises to determine when the client is ready
You can use thewaitForInitialization() 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. The waitForInitialization() method can also return an error, which you must handle in your application.Here are some examples:waitForInitialization.handleInitializedClient is not provided by the SDKhandleInitializedClient is not provided by the SDK. In all examples, it represents your application logic that should run once the LaunchDarkly client is initialized.
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 thestreaming 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
streamingconfiguration option totrue, the client will always attempt to maintain a streaming connection. - Register a change listener: If you subscribe to
changeorchange:flag-keyevents, 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.
streaming.
Older versions of the JavaScript SDK require the LaunchDarkly EventSource polyfillIn the JavaScript SDK, v3.x and earlier, if you use
REPORT, enable the useReport configuration option, and want to use streaming, then you must use the LaunchDarkly EventSource polyfill. This is true whether or not your browser already supports EventSource. To learn more, read Requirements and polyfills.The JavaScript SDK v4.x supports REPORT directly. If you enable the useReport configuration option, no polyfill or additional configuration is required.Shut down the client
Shut down the client when your application terminates. To learn more, read Shutting down.Troubleshooting
This section describes common issues you might encounter when using the JavaScript SDK and how to resolve them.Network error
If your application logs show the errorLaunchDarklyFlagFetchError: network error, there may be a problem with network connectivity between your SDK and LaunchDarkly.
For steps to resolve this issue, read the LaunchDarkly Knowledge Base article Error “LaunchDarklyFlagFetchError: network error”.
CORS errors in local development
If you see CORS errors in the browser while using the ldcli dev-server, check your SDK configuration. The JavaScript SDK must use your project key as the credential and all service endpoints must point tohttp://localhost:8765.
If you use a client-side ID instead of the project key, the SDK connects to LaunchDarkly rather than the dev-server. This prevents the SDK from retrieving local flag values and can produce CORS errors.
Supported features
This SDK supports the following features:- Anonymous contexts and users
- Bootstrapping
- Caching contexts to local storage
- SDK configuration, including
- Context configuration
- Data saving mode
- Experimentation
- Flag variation evaluation
- Flag variation evaluation details
- Flushing events
- Getting all flags
- Hooks
- Identifying and changing contexts
- Inspectors
- Logging
- Observability
- OpenTelemetry in client-side SDKs
- Private attributes
- Relay Proxy configuration, using proxy mode
- Secure mode
- Tracking custom events
- Service endpoint configuration
- Shutting down
- Subscribing to flag changes