JavaScript Browser SDK

View as Markdown

The Unleash JavaScript SDK is a lightweight client with no external dependencies (beyond browser APIs) that lets you evaluate feature flags in any JavaScript application. It is not tied to any framework, so you can use it with React, Vue, Angular, or plain JavaScript.

The SDK stores flag configuration in localStorage and synchronizes with Unleash or Unleash Edge in the background. Because flags are stored in the browser, the SDK can bootstrap itself the next time the user visits the same page.

You can use this SDK with Unleash Enterprise or Unleash Open Source.

For an overview of how Unleash SDKs work, including offline behavior, feature compatibility across SDKs, and default refresh and metrics intervals, refer to the SDK overview.

Installation

1npm install unleash-proxy-client

Initialization

Configure the client according to your needs. The following example provides only the required options. Refer to configuration options for the full list.

Set url to the /api/frontend endpoint of your Unleash instance or your Unleash Edge instance. Set clientKey to a frontend API token.

1import { UnleashClient } from 'unleash-proxy-client';
2
3const unleash = new UnleashClient({
4 url: 'https://<your-unleash-instance>/api/frontend',
5 clientKey: '<your-frontend-token>',
6 appName: 'my-webapp',
7});
8
9// Start the background polling
10unleash.start();

Check if the SDK is ready

You should wait for the client’s ready or initialized events before you start working with it. Before it’s ready, the client might not report the correct state for your features.

1unleash.on('ready', () => {
2 if (unleash.isEnabled('js.demo')) {
3 console.log('js.demo is enabled');
4 } else {
5 console.log('js.demo is disabled');
6 }
7});

The difference between the events is described in the section on available events.

Check flags

Once the client is ready, you can start checking features in your application. Use the isEnabled method to check the state of any feature you want:

1unleash.isEnabled('js.demo');

You can use the getVariant method to get the variant of an enabled feature that has variants. If the feature is disabled or if it has no variants, then you will get back the disabled variant

1const variant = unleash.getVariant('proxy.demo');
2if (variant.name === 'blue') {
3 // something with variant blue...
4}

Unleash context

The Unleash context holds properties such as user ID, session ID, and custom fields that drive flag evaluation, including strategy targeting, constraints, and stickiness. To update and configure the Unleash context in this SDK, use the updateContext, setContextField, and removeContextField methods.

The context you set in your app will be passed along to the Unleash Edge or the Frontend API as query parameters for feature evaluation.

The updateContext method will replace the entire (mutable part) of the Unleash context with the data that you pass in.

The setContextField method only acts on the property that you choose. It does not affect any other properties of the Unleash context.

1unleash.updateContext({ userId: '1233' });
2
3unleash.setContextField('userId', '4141');

The removeContextField method only acts on the property that you choose. It does not affect any other properties of the Unleash context.

1unleash.updateContext({ userId: '1233', sessionId: 'sessionNotAffected' });
2
3unleash.removeContextField('userId');

Configuration options

The Unleash SDK takes the following options:

optionrequireddefaultdescription
urlyesn/aThe Unleash URL to connect to. E.g.: https://examples.com/api/frontend
clientKeyyesn/aThe Unleash API Secret to be used
appNameyesn/aThe name of the application using this SDK. Will be used as part of the metrics sent to Unleash. Will also be part of the Unleash Context.
contextno{}The initial Unleash context. This will be used as the initial context for all feature toggle evaluations. The appName and environment options will automatically be populated with the values you pass for those options.
refreshIntervalno30How often, in seconds, the SDK should check for updated toggle configuration. If set to 0 will disable checking for updates
disableRefreshnofalseIf set to true, the client will not check for updated toggle configuration
metricsIntervalno60How often, in seconds, the SDK should send usage metrics back to Unleash. It will be started after the initial metrics report, which is sent after the configured metricsIntervalInitial
metricsIntervalInitialno2How long the SDK should wait for the first metrics report back to the Unleash API. If you want to disable the initial metrics call you can set it to 0.
disableMetricsnofalseSet this option to true if you want to disable usage metrics
storageProvidernoLocalStorageProvider in browser, InMemoryStorageProvider otherwiseAllows you to inject a custom storeProvider
fetchnowindow.fetch or global fetchAllows you to override the fetch implementation to use. Useful in Node.js environments where you can inject node-fetch
createAbortControllerno() => new AbortController()Allows you to override the default AbortController creation. Used to cancel requests with outdated context. Set it to () => null if you don’t want to handle it.
bootstrapno[]Allows you to bootstrap the cached feature toggle configuration.
bootstrapOverridenotrueShould the bootstrap automatically override cached data in the local-storage. Will only be used if bootstrap is not an empty array.
headerNamenoAuthorizationWhich header the SDK should use to authorize with Unleash / Unleash Edge. The header will be given the clientKey as its value.
customHeadersno{}Additional headers to use when making HTTP requests to Unleash. In case of name collisions with the default headers, the customHeaders value will be used if it is not null or undefined. customHeaders values that are null or undefined will be ignored.
impressionDataAllnofalseAllows you to trigger “impression” events for all getToggle and getVariant invocations. This is particularly useful for “disabled” feature flags that are not visible to frontend SDKs.
environmentnodefaultSets the environment option of the Unleash context. This does not affect the SDK’s Unleash environment.
usePOSTrequestsnofalseConfigures the client to use POST requests instead of GET when requesting enabled features. This is helpful when sensitive information (like user email, when used as a user ID) is passed in the context to avoid leaking it in the URL. NOTE: Post requests are not supported by the frontend api built into Unleash.
experimentalno{}Enabling optional experimentation. togglesStorageTTL : How long (Time To Live), in seconds, the toggles in storage are considered valid and should not be fetched on start. If set to 0 will disable expiration checking and will be considered always expired.

Events

The client is also an event emitter. This means that your code can subscribe to updates from the client. This is a neat way to update a single page app when toggle state updates.

1unleash.on('update', () => {
2 const myToggle = unleash.isEnabled('js.demo');
3 //do something useful
4});

The SDK emits the following events:

  • error - emitted when an error occurs on init, or when fetch function fails, or when fetch receives a non-ok response object. The error object is sent as payload.
  • initialized - emitted after the SDK has read local cached data in the storageProvider.
  • ready - emitted after the SDK has successfully started and performed the initial fetch of flags via the network (Edge, or Frontend API). When bootstrapping, the client can emit this event twice: once when the bootstrapped flags are loaded, and once on first successful connection to Unleash.
  • update - emitted every time Unleash returns a new feature toggle configuration. The SDK will emit this event as part of the initial fetch from the SDK.
  • recovered - emitted when the SDK has recovered from an error. This event will only be emitted if the SDK has previously emitted an error.
  • sent - emitted when the SDK has successfully sent metrics to Unleash.
Please remember that you should always register your event listeners before your call unleash.start(). If you register them after you have started the SDK you risk losing important events.

Session ID

You may provide a custom session id via the “context”. If you do not provide a sessionId this SDK will create a random session id, which will also be stored in the provided storage (local storage). By always having a consistent sessionId available ensures that even “anonymous” users will get a consistent experience when feature flags are evaluated, in combination with a gradual (percentage based) rollout.

Stop the client

You can stop the Unleash client by calling the stop method. Once the client has been stopped, it will no longer check for updates or send metrics to the server.

A stopped client can be restarted.

1unleash.stop()

Custom store

This SDK can work with React Native storage @react-native-async-storage/async-storage or react-native-shared-preferences and many more to backup feature flags locally. This is useful for bootstrapping the SDK the next time the user comes back to your application.

You can provide your own storage implementation.

Examples:

1import SharedPreferences from 'react-native-shared-preferences';
2import { UnleashClient } from 'unleash-proxy-client';
3
4const unleash = new UnleashClient({
5 url: 'https://eu.unleash-hosted.com/demo/api/frontend',
6 clientKey: 'your-frontend-key',
7 appName: 'my-webapp',
8 storageProvider: {
9 save: (name: string, data: any) => SharedPreferences.setItem(name, data),
10 get: (name: string) => SharedPreferences.getItem(name, (val) => val)
11 },
12});
1import AsyncStorage from '@react-native-async-storage/async-storage';
2import { UnleashClient } from 'unleash-proxy-client';
3
4const PREFIX = 'unleash:repository';
5
6const unleash = new UnleashClient({
7 url: 'https://eu.unleash-hosted.com/demo/api/frontend',
8 clientKey: 'your-frontend-key',
9 appName: 'my-webapp',
10 storageProvider: {
11 save: (name: string, data: any) => {
12 const repo = JSON.stringify(data);
13 const key = `${PREFIX}:${name}`;
14 return AsyncStorage.setItem(key, repo);
15 },
16 get: (name: string) => {
17 const key = `${PREFIX}:${name}`;
18 const data = await AsyncStorage.getItem(key);
19 return data ? JSON.parse(data) : undefined;
20 }
21 },
22});

Node.js usage

This SDK can also be used in node.js applications (from v1.4.0). Please note that you will need to provide a valid “fetch” implementation. Only ECMAScript modules is exported from this package.

1import fetch from 'node-fetch';
2import { UnleashClient, InMemoryStorageProvider } from 'unleash-proxy-client';
3
4const unleash = new UnleashClient({
5 url: 'https://app.unleash-hosted.com/demo/api/frontend',
6 clientKey: '<your-frontend-token>',
7 appName: 'nodejs-proxy',
8 storageProvider: new InMemoryStorageProvider(),
9 fetch,
10});
11
12await unleash.start();
13const isEnabled = unleash.isEnabled('proxy.demo');
14console.log(isEnabled);

index.mjs

Developer toolbar

The Developer Toolbar wraps your Unleash client to provide runtime flag overrides during development. Install @unleash/toolbar and wrap your client:

1import { initUnleashToolbar } from '@unleash/toolbar';
2import { UnleashClient } from 'unleash-proxy-client';
3import '@unleash/toolbar/toolbar.css';
4
5const client = initUnleashToolbar(new UnleashClient({
6 url: 'https://your-unleash.com/api/frontend',
7 clientKey: 'your-frontend-token',
8 appName: 'my-app'
9}));
10
11await client.start();
12
13// Use the wrapped client for all flag checks
14const isEnabled = client.isEnabled('my-feature');

The wrapped client has the same API as the original. Refer to the Developer Toolbar documentation for configuration options and framework guides.

CDN usage

1<html>
2<head>
3 <script src="https://unpkg.com/unleash-proxy-client@latest/build/main.min.js" type="text/javascript"></script>
4 <script type="text/javascript">
5 var config = {url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: '<your-frontend-token>', appName: 'web'};
6 var client = new unleash.UnleashClient(config);
7 client.updateContext({userId: '1233'})
8
9 client.on('update', () => {
10 console.log(client.isEnabled('proxy.demo'));
11 });
12 client.start();
13 </script>
14</head>
15</html>

Bootstrap

You can bootstrap the SDK with your own feature flag configuration to make flags available immediately, without waiting for an API call. This is useful when you need flags in a specific state right after initialization.

Pass a bootstrap array and an optional bootstrapOverride flag when you create the client:

1import { UnleashClient } from 'unleash-proxy-client';
2
3const unleash = new UnleashClient({
4 url: 'https://<your-unleash-instance>/api/frontend',
5 clientKey: '<your-frontend-token>',
6 appName: 'my-webapp',
7 bootstrap: [{
8 enabled: true,
9 name: 'demoApp.step4',
10 variant: {
11 enabled: true,
12 name: 'blue',
13 feature_enabled: true,
14 }
15 }],
16 bootstrapOverride: false
17});

When bootstrapOverride is true (the default), the bootstrap data replaces any locally cached data. When bootstrapOverride is false, the bootstrap data is only used if the local cache is empty.

Manage your own refresh mechanism

You can opt out of the Unleash feature flag auto-refresh mechanism and metrics update by settings the refreshInterval and/or metricsInterval options to 0. In this case, it becomes your responsibility to call updateToggles and/or sendMetrics methods. This approach is useful in environments that do not support the setInterval API, such as service workers.