> For the complete documentation index, see [llms.txt](https://developer.harness.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.harness.io/feature-management-experimentation/new-to-fme/sdks-and-customer-deployed-components/client-side-configs-sdks/javascript-sdk.md). Agents can also search and read this documentation through its [MCP server](https://developer.harness.io/~gitbook/mcp).

# JavaScript Configs SDK

Use the Harness FME JavaScript Configs SDK to serve standalone, versioned configuration objects in browser and other client-side applications.

This guide provides detailed information about the client-side API of our JavaScript Configs SDK. The SDK serves Configs: standalone, versioned configuration objects that you manage independently from feature flags. Configs can be evaluated with or without targeting rules and are well suited for use cases such as AI prompts, model parameters, and other application configuration that benefits from governed, versioned management.

The client-side API is imported from the `@splitsoftware/configs/client-side` subpath of the same package as the server-side Configs SDK, and is built for browser and other client-side apps, where there is usually one or a few user keys. Go to our [JavaScript Configs SDK GitHub repository](https://github.com/splitio/javascript-configs-client) to learn more.

{% hint style="info" %}
The client-side JavaScript Configs SDK is in beta.
{% endhint %}

## Before you begin <a href="#before-you-begin" id="before-you-begin"></a>

The JavaScript Configs SDK runs in modern browsers and other client-side JavaScript runtimes, such as Electron and React Native. The SDK is built to ES2015 and uses the native Fetch API, so polyfill Fetch if your target runtime lacks it. In Node.js, version 22.x or later is required.

## Initialization <a href="#initialization" id="initialization"></a>

Set up the JavaScript Configs SDK in your code base with two simple steps.

### 1. Import the SDK into your project <a href="#id-1-import-the-sdk-into-your-project" id="id-1-import-the-sdk-into-your-project"></a>

You can import the SDK into your project using either NPM or the bundle hosted on our CDN.

{% tabs %}
{% tab title="NPM package (recommended)" %}

```bash
npm install --save @splitsoftware/configs
```

{% endtab %}

{% tab title="CDN bundle" %}

```html
<script src="//cdn.split.io/sdk/configs-1.0.0-beta5.min.js"></script>
```

{% endtab %}
{% endtabs %}

No bundler or TypeScript setup is needed to resolve the `@splitsoftware/configs/client-side` subpath.

### 2. Instantiate the SDK and create a new client <a href="#id-2-instantiate-the-sdk-and-create-a-new-client" id="id-2-instantiate-the-sdk-and-create-a-new-client"></a>

{% tabs %}
{% tab title="ES Modules" %}

```typescript
import { ConfigsFactory } from '@splitsoftware/configs/client-side';

const factory = ConfigsFactory({
  sdkKey: 'YOUR_CLIENT_SIDE_SDK_KEY',
  // key represents your internal user ID, or the account ID that the user belongs to.
  // This could also be a cookie you generate for anonymous users.
  key: 'user-123'
});

// The default client, bound to the key passed in the settings
const client = factory.client();
```

{% endtab %}

{% tab title="CommonJS" %}

```javascript
const { ConfigsFactory } = require('@splitsoftware/configs/client-side');

const factory = ConfigsFactory({
  sdkKey: 'YOUR_CLIENT_SIDE_SDK_KEY',
  key: 'user-123'
});

const client = factory.client();
```

{% endtab %}

{% tab title="Script tag (UMD)" %}

```html
<script>
  // The CDN bundle exposes a global SplitioConfigs object with a reference to the ConfigsFactory
  var factory = SplitioConfigs.ConfigsFactory({
    sdkKey: 'YOUR_CLIENT_SIDE_SDK_KEY',
    key: 'user-123'
  });

  var client = factory.client();
</script>
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Notice for TypeScript**

With the SDK package on NPM, you get the `SplitIO` namespace, which contains useful types and interfaces for you to use, such as `SplitIO.ConfigsFactory`, `SplitIO.ConfigsFactoryClient`, and `SplitIO.Config`.
{% endhint %}

We recommend instantiating the factory once as a singleton and reusing it throughout your application.

Configure the SDK with the SDK key for the FME environment that you would like to access. Go to [API keys](https://developer.harness.io/feature-management-experimentation/management-and-administration/api-keys.md) to learn how to retrieve a client-side SDK key.

## Use the SDK <a href="#use-the-sdk" id="use-the-sdk"></a>

### Basic use <a href="#basic-use" id="basic-use"></a>

When the SDK is instantiated, it kicks off background jobs to update an in-memory cache with config definitions fetched from Harness servers. While the SDK is in this intermediate state, if it is asked to evaluate a config, it does not fail. Instead, it returns a fallback config or, if no fallback is configured, a `Config` with `variant` equal to `"control"` and an empty `value` (`{}`).

To make sure the SDK has loaded the latest definitions before evaluating, wait for the `SDK_READY` event before calling `getConfig`.

The `getConfig` method returns a `Config` object with two properties:

* **`variant`:** The string name of the resolved variant.
* **`value`:** The raw JSON object associated with that variant.

The key is bound to the client, so `getConfig` takes no key. The SDK evaluates the config's targeting rules for the client's key and any attributes you pass or store on the client.

{% tabs %}
{% tab title="whenReady() promise" %}

```typescript
try {
  await client.whenReady();
  // SDK_READY event has been emitted
} catch (e) {
  // SDK_READY_TIMED_OUT event has been emitted. Evaluations will return the fallback config or `"control"`.
  // Subsequent calls to `client.whenReady()` may return a new promise with a different settled state.
}

// Without attributes: evaluates targeting rules for the client's key
const config: SplitIO.Config = client.getConfig('CONFIG_NAME');
console.log(config.variant); // 'v1'
console.log(config.value);   // { prompt: 'Hello world', temperature: 0.5 }

// With attributes: merged over the ones stored on the client
const configForPlan = client.getConfig('CONFIG_NAME', { plan: 'premium' });
console.log(configForPlan.variant, configForPlan.value);
```

{% endtab %}

{% tab title="SDK\_READY event" %}

```typescript
client.on(client.Event.SDK_READY, () => {
  // Without attributes: evaluates targeting rules for the client's key
  const config: SplitIO.Config = client.getConfig('CONFIG_NAME');
  console.log(config.variant); // 'v1'
  console.log(config.value);   // { prompt: 'Hello world', temperature: 0.5 }

  // With attributes: merged over the ones stored on the client
  const configForPlan = client.getConfig('CONFIG_NAME', { plan: 'premium' });
  console.log(configForPlan.variant, configForPlan.value);
});
```

{% endtab %}
{% endtabs %}

If a config cannot be evaluated, the SDK returns the fallback config value: default `Config` with `variant` `"control"` and empty object `value`, unless overridden globally or per config. Go to [Configure fallback configs](#configure-fallback-configs) to learn more.

### Attribute syntax <a href="#attribute-syntax" id="attribute-syntax"></a>

To [target based on custom attributes](https://developer.harness.io/feature-management-experimentation/use-fme/feature-management/targeting/target-with-custom-attributes.md), pass an `attributes` map as the second argument of the `getConfig` method.

In the example below, we evaluate a config for the client's user. The provided attributes `plan_type`, `registered_date`, `permissions`, `paying_customer`, and `deal_size` are passed to the `getConfig` call. These attributes are compared and evaluated against the targeting rules defined for the config in Harness FME to decide which variant to resolve.

The supported attribute types are: strings, numbers, dates, booleans, and sets. The proper data type and syntax for each are:

* **Strings:** Use type String.
* **Numbers:** Use type Number.
* **Dates:** Express the value for these attributes in `milliseconds since epoch`.
* **Booleans:** Use type Boolean.
* **Sets:** Use type Array.

```typescript
const attributes: SplitIO.Attributes = {
  // date attributes are handled as `millis since epoch`
  registered_date: new Date('2024-01-15T00:00:00.000Z').getTime(),
  // this string will be compared against a list called `plan_type`
  plan_type: 'growth',
  // this number will be compared against a const value called `deal_size`
  deal_size: 10000,
  // this boolean will be compared against a const value called `paying_customer`
  paying_customer: true,
  // this array will be compared against a set called `permissions`
  permissions: ['read', 'write']
};
const config = client.getConfig('CONFIG_NAME', attributes);
console.log(config.variant, config.value);
```

### Bind attributes to the client <a href="#bind-attributes-to-the-client" id="bind-attributes-to-the-client"></a>

Attributes can optionally be bound to the client at any time during the SDK lifecycle. These attributes are stored in memory and used in every evaluation of that client, so you do not need to keep the attribute set accessible throughout your app. When `getConfig` is called, the attributes passed to it (if any) are merged over the ones stored on the client, with the passed attributes taking precedence. This enables stored attributes to be overridden for specific evaluations.

The SDK validates attributes before storing them. If there are invalid or missing values, the `setAttribute` and `setAttributes` methods return `false` and do not update any value.

```javascript
const attributes = {
  registered_date: new Date('2024-01-15T00:00:00.000Z').getTime(),
  plan_type: 'growth',
  deal_size: 10000,
  paying_customer: true,
  permissions: ['read', 'write']
};

// Set attributes. Returns true unless there is an issue storing them
let result = client.setAttributes(attributes);

// Set one attribute. Returns true unless there is an issue storing it
result = client.setAttribute('paying_customer', false);

// Get an attribute
const planType = client.getAttribute('plan_type');

// Get all attributes
const storedAttributes = client.getAttributes();

// Remove an attribute
result = client.removeAttribute('permissions');

// Remove all attributes
result = client.clearAttributes();
```

### Append properties to impressions <a href="#append-properties-to-impressions" id="append-properties-to-impressions"></a>

[Impressions](https://developer.harness.io/feature-management-experimentation/use-fme/feature-management/monitoring-and-analysis/impressions.md) are generated by the SDK each time a `getConfig` method is called. These impressions are periodically sent back to Harness servers for feature monitoring and experimentation.

You can append properties to an impression by passing an `evaluationOptions` object as the third argument of the `getConfig` method. These properties are then included in the impression sent by the SDK and can provide useful context to the impression data.

Three types of properties are supported: strings, numbers, and booleans.

```typescript
const evaluationOptions: SplitIO.EvaluationOptions = {
  properties: { package: 'premium', admin: true, discount: 50 }
};
const config = client.getConfig('CONFIG_NAME', undefined, evaluationOptions);
```

### Shutdown <a href="#shutdown" id="shutdown"></a>

Call the `destroy()` method before letting your app or page using the SDK exit, as this method gracefully shuts down the SDK by stopping all background sync jobs, clearing caches, closing connections, and flushing any remaining unpublished events and impressions.

* `client.destroy()` destroys that client only. Destroying the default client does not destroy the other clients created by the factory.
* `factory.destroy()` destroys the factory and every client created by it.

```javascript
// destroy() returns a promise, so if you want to, for example,
// navigate to another page without losing impressions, you
// can do that once the promise resolves.
factory.destroy().then(() => {
  document.location.replace('another_page');
});
```

After `destroy()` is called and finishes, any subsequent invocations to `getConfig` on a destroyed client return the fallback config or, if no fallback is configured, a `Config` with `variant` `"control"` and empty object `value`.

## Track <a href="#track" id="track"></a>

Use the `track` method to record any actions your customers perform. Each action is known as an `event` and corresponds to an `event type`. Calling `track` through one of our SDKs or via the API allows you to measure the impact of your configs on your users' actions and metrics.

Go to [Events](https://developer.harness.io/feature-management-experimentation/use-fme/release-monitoring/events.md) to learn more about using track events in features.

The key is bound to the client, so the event is tracked for the client's key. In the examples below, you can see that the `track` method can take up to four arguments. The proper data type and syntax for each are:

* **TRAFFIC\_TYPE:** The traffic type of the client's key. The expected data type is **String**. Go to [traffic types](https://developer.harness.io/feature-management-experimentation/management-and-administration/traffic-types.md) to learn more.
* **EVENT\_TYPE:** The event type that this event should correspond to. The expected data type is **String**. Full requirements on this argument are:
  * Contains 63 characters or fewer.
  * Starts with a letter or number.
  * Contains only letters, numbers, hyphen, underscore, or period.
  * This is the regular expression we use to validate the value: `[a-zA-Z0-9][-_\.a-zA-Z0-9]{0,62}`
* **VALUE:** (Optional) The value to be used in creating the metric. This field can be sent as null or 0 if you intend to purely use the count function when creating a metric. The expected data type is **Number**.
* **PROPERTIES:** (Optional) An object of key-value pairs that can be used to filter your metrics. Go to [Event properties](https://developer.harness.io/feature-management-experimentation/use-fme/release-monitoring/events.md#event-properties) to learn more. FME currently supports three types of properties: strings, numbers, and booleans.

The `track` method returns a boolean value of `true` or `false` to indicate whether the SDK was able to successfully queue the event to be sent back to Harness servers on the next event post. The SDK returns `false` if an incorrect input has been provided.

```typescript
// If you would like to send an event without a value
let queued = client.track('TRAFFIC_TYPE', 'EVENT_TYPE');

// Example
queued = client.track('user', 'page_load_time');

// If you would like to associate a value with an event
queued = client.track('TRAFFIC_TYPE', 'EVENT_TYPE', eventValue);

// Example
queued = client.track('user', 'page_load_time', 83.334);

// If you would like to associate a value and properties with an event
const properties = { package: 'premium', admin: true, discount: 50 };
queued = client.track('user', 'page_load_time', 83.334, properties);

// If you would like to associate only properties with an event
queued = client.track('user', 'page_load_time', null, properties);
```

## Configuration <a href="#configuration" id="configuration"></a>

The SDK has a number of knobs for configuring performance. Each knob is tuned to a reasonable default. However, you can override the value while instantiating the SDK. The parameters available for configuration are shown below.

| **Configuration**               | **Description**                                                                                                                                                                                                                                              | **Default value**            |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
| `sdkKey`                        | Client-side SDK key. **Required**.                                                                                                                                                                                                                           | NA                           |
| `key`                           | Key of the default client, returned by `factory.client()`. **Required**.                                                                                                                                                                                     | NA                           |
| `logLevel`                      | Logging level. Acceptable values are `'none'`, `'error'`, `'warn'`, `'info'`, and `'debug'`.                                                                                                                                                                 | `'none'`                     |
| `sync.pollingRate`              | How often, in seconds, the SDK polls for config and segment updates. Minimum value: `5`.                                                                                                                                                                     | `60`                         |
| `sync.pushRate`                 | How often, in seconds, the SDK flushes queued events and impressions. Minimum value: `60`.                                                                                                                                                                   | `60`                         |
| `sync.queueSize`                | Maximum number of events or impressions queued in memory before a forced flush. Minimum value: `1000`.                                                                                                                                                       | `10000`                      |
| `sync.readyTimeout`             | Time in seconds before the SDK emits `SDK_READY_TIMED_OUT` event. Use `-1` to disable the timeout.                                                                                                                                                           | `10`                         |
| `sync.serviceEndpoints.configs` | Override the base URL for config and segment requests.                                                                                                                                                                                                       | `'https://configs.split.io'` |
| `sync.serviceEndpoints.events`  | Override the base URL for events and impressions requests.                                                                                                                                                                                                   | `'https://events.split.io'`  |
| `sync.serviceEndpoints.auth`    | Override the base URL for JWT authentication requests.                                                                                                                                                                                                       | `'https://auth.split.io'`    |
| `fallbackConfigs`               | Fallback configs returned when evaluation fails or the requested config name does not exist. Go to [Configure fallback configs](#configure-fallback-configs) to learn more.                                                                                  | `undefined`                  |
| `requestOptions.agent`          | Custom Node.js HTTP(S) agent. Useful for certificate pinning or routing through a proxy. Only applies in Node.js-based runtimes; browsers ignore it. Go to the [Node.js https.Agent docs](https://nodejs.org/api/https.html#class-httpsagent) to learn more. | `undefined`                  |

To set each of the parameters defined above, use the following syntax.

```typescript
const factory = ConfigsFactory({
  sdkKey: 'YOUR_CLIENT_SIDE_SDK_KEY',
  key: 'user-123',
  logLevel: 'info',
  sync: {
    pollingRate: 60,
    pushRate: 60,
    queueSize: 10000,
    readyTimeout: 10,
    serviceEndpoints: {
      configs: 'https://configs.split.io',
      events: 'https://events.split.io',
      auth: 'https://auth.split.io'
    }
  }
});
```

### Configure fallback configs <a href="#configure-fallback-configs" id="configure-fallback-configs"></a>

Fallback configs let you define a `Config` value to be returned when a config cannot be evaluated. By default, the SDK returns a `Config` with `variant` `"control"` and an empty `value` (`{}`), but you can override this globally or for individual configs at the SDK level.

This is useful when you want to:

* Maintain a predictable user experience during outages or evaluation failures.
* Protect critical user flows by returning a safe, stable configuration.
* Customize behavior per config so each evaluation inherits appropriate safe defaults if something goes wrong.

Each fallback entry must include a `variant` (string) and a `value` (raw JSON object) matching the [Config return type](#use-the-sdk).

**Global fallback config**

Set a global fallback config when instantiating the SDK. This value is returned whenever any config cannot be evaluated.

```typescript
const factory = ConfigsFactory({
  sdkKey: 'YOUR_CLIENT_SIDE_SDK_KEY',
  key: 'user-123',
  fallbackConfigs: {
    global: {
      variant: 'v1',
      value: { prompt: 'default prompt', temperature: 0.9 }
    }
  }
});
```

**Per-config fallback**

You can also set a fallback config per config name via the `byName` sub-option. Per-config fallbacks always take precedence over the global fallback, so if both are defined, the SDK returns the per-config value when that config cannot be evaluated.

```typescript
const factory = ConfigsFactory({
  sdkKey: 'YOUR_CLIENT_SIDE_SDK_KEY',
  key: 'user-123',
  fallbackConfigs: {
    byName: {
      'chat_bot_config': {
        variant: 'v2',
        value: { prompt: 'fallback chat prompt', temperature: 0.1 }
      }
    }
  }
});
```

## Advanced use cases <a href="#advanced-use-cases" id="advanced-use-cases"></a>

This section describes advanced use cases and features provided by the SDK.

### Instantiate multiple SDK clients <a href="#instantiate-multiple-sdk-clients" id="instantiate-multiple-sdk-clients"></a>

Each client is bound to one key. To evaluate configs for another key, for example to target by a different [traffic type](https://developer.harness.io/feature-management-experimentation/management-and-administration/traffic-types.md) such as `users` and `accounts`, create another client from the same factory by passing the key to `factory.client()`. Clients are cached per key, so the same instance is returned for the same key.

```javascript
const factory = ConfigsFactory({
  sdkKey: 'YOUR_CLIENT_SIDE_SDK_KEY',
  // Key of the default client
  key: 'CUSTOMER_ACCOUNT_ID'
});

// The default client, bound to the account ID passed in the settings
const accountClient = factory.client();

// A client bound to a user ID
const userClient = factory.client('CUSTOMER_USER_ID');

// Evaluate configs for each key
const userConfig = userClient.getConfig('user_config');
const accountConfig = accountClient.getConfig('account_config');

// Track events for each key
accountClient.track('account', 'PAGELOAD', 7.86);
userClient.track('user', 'ACCOUNT_CREATED');
```

Each client has its own readiness, so wait for the `SDK_READY` event, or `whenReady()`, of each client before evaluating with it.

{% hint style="info" %}
**Number of SDK instances**

While the SDK does not put any limitations on the number of factories that can be created, we strongly recommend instantiating **one** factory and creating a client per key from it.
{% endhint %}

### Subscribe to events <a href="#subscribe-to-events" id="subscribe-to-events"></a>

You can listen for three different events from the SDK.

* `SDK_READY`. This event fires once the SDK is ready to evaluate configs using the most up-to-date version of your rollout plan, downloaded from Harness servers.
* `SDK_READY_TIMED_OUT`. This event fires if the SDK could not fully download the data from Harness servers (`client.Event.SDK_READY` event) within the time specified by the `sync.readyTimeout` setting. This event does not indicate that the SDK initialization was interrupted. The SDK continues downloading and fires the `client.Event.SDK_READY` event when finished. This delayed `client.Event.SDK_READY` event may happen with slow connections or large rollout plans with many configs and segments.
* `SDK_UPDATE`. This event fires whenever your rollout plan is changed. Listen for this event to refresh your app whenever a config or segment is changed in Harness FME.

These events provide hooks to run custom logic whenever the SDK state changes.

{% code title="TypeScript" %}

```typescript
client.on(client.Event.SDK_READY, () => {
  console.log('Configs SDK is ready.');
});

client.on(client.Event.SDK_READY_TIMED_OUT, () => {
  console.log('Configs SDK emitted SDK_READY_TIMED_OUT event.');
});

client.on(client.Event.SDK_UPDATE, (metadata: SplitIO.SdkUpdateMetadata) => {
  const type = metadata.type; // 'CONFIGS_UPDATE' or 'SEGMENTS_UPDATE'
  const names: string[] = metadata.names;
});
```

{% endcode %}

**Include metadata**

`metadata` provides additional context for events:

* `SDK_UPDATE`: Includes `type` (`CONFIGS_UPDATE` or `SEGMENTS_UPDATE`) and `names` (list of impacted configs; empty for segment-only updates).
* `SDK_READY` and `SDK_READY_TIMED_OUT`: No metadata is included.

{% @harness-feedback/feedback %}
