---
title: "JavaScript On-Device Evaluation Client SDK"
description: "Statsig's JavaScript SDK for on-device evaluation with browser and Node.js applications."
product: general
token_estimate: 4261
---
# JavaScript On-Device Evaluation Client SDK

> For AI agents: a documentation index is available at [/llms.txt](/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

- **Package:** `@statsig/js-on-device-eval-client` ([npm](https://www.npmjs.com/package/@statsig/js-on-device-eval-client))
- **Latest version:** 3.33.4
- **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo)

> **Info:**
>
> Statsig recommends its normal (remote evaluation) SDKs for most client applications. Understand the use case and privacy risks by reading the [On-Device Eval SDK overview](https://docs.statsig.com/client/onDeviceOverview). On-device evaluation SDKs are for Enterprise & Pro Tier only.

These SDKs use a different paradigm than their precomputed counterparts ([JS](https://docs.statsig.com/client/javascript-sdk), [Android](https://docs.statsig.com/client/Android), [iOS](https://docs.statsig.com/client/iosClientSDK)) and behave more like Server SDKs. Rather than requiring a user in advance, you can check gates/configs/experiments for any set of user properties. The SDK downloads a complete representation of your project and evaluates checks in real time.

### Pros

- No need for a network request when changing user properties: check the gate/config/experiment locally
- Can bring your own CDN or synchronously initialize with a preloaded project definition
- Lower latency to download configs cached at the edge, rather than evaluated for a given user (which Statsig can't cache as much)

### Cons

- The client has the entire project definition: it exposes the names and configurations of all experiments and feature flags accessible by your client key. Refer to [client key with server permission best practices](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions).
- Payload size is strictly larger than what the traditional SDKs require
- Evaluation performance is slightly slower: rather than looking up the value, the SDK must evaluate targeting conditions and an allocation decision
- Doesn't support ID list segments with > 1000 IDs
- Doesn't support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country)

## Set up the SDK

1. **Install the SDK**

   Install the Statsig SDK using npm, yarn, or jsdelivr:

   #### npm

   ```bash
   npm install @statsig/js-on-device-eval-client
   ```

   #### yarn

   ```bash
   yarn add @statsig/js-on-device-eval-client
   ```

   #### CDN / <script>

   ```html
   <script src="https://cdn.jsdelivr.net/npm/@statsig/js-on-device-eval-client@1/build/statsig-js-on-device-eval-client.min.js"></script>
   ```

   Statsig is hosted on the [jsDelivr](https://www.jsdelivr.com/package/npm/@statsig/js-client) CDN.

   To access the current primary JavaScript bundle, use:

   `https://cdn.jsdelivr.net/npm/@statsig/js-client/build/statsig-js-client.min.js`

   To access specific files/versions:

   `https://cdn.jsdelivr.net/npm/@statsig/js-client@{version}/build/statsig-js-client.min.js`
2. **Initialize the SDK**

   Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application.

   Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment.

   > **Warning:**
   >
   > For On-Device Evaluation, you need to add the **"Allow Download Config Specs"** scope. Client keys, by default, can't download the project definition for on-device evaluation.
   >
   > While client keys are safe to include, always keep Server and Console keys private.

   #### How to add the scope

   #### New SDK Keys

   When creating a new client key, select **"Allow Download Config Specs"**

   ![Add DCS Scope to New Key](https://docs.statsig.com/images/local-eval/new-keys.png)

   #### Existing SDK Keys

   To add the scope to an existing key, under **Project Settings** → **API Keys** → **Client API Keys**, select **Actions** → **Edit Scopes**, and select **"Allow Download Config Specs"**, then **Save**.

   ![Add DCS Scope to Existing Key](https://docs.statsig.com/images/local-eval/existing-keys.png)

   ```typescript
   import { StatsigOnDeviceEvalClient } from '@statsig/js-on-device-eval-client';

   const myStatsigClient = new StatsigOnDeviceEvalClient(
     YOUR_CLIENT_KEY, 
     { environment: {tier: 'development'} }
   );

   // initialize and wait for the latest values
   await myStatsigClient.initializeAsync();
   ```

   > **Note:**
   >
   > In advanced use cases, you may want to Prefetch or Bootstrap (Provide) values for initialization. Go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) to learn how to do this.

## Working with the SDK

## Setup a StatsigUser

To interact with the SDK, create a `StatsigUser` object. The full definition of this object is [here](#statsig-user).

```typescript
const myUser = {
    userID: "a-user",
    email: "user@statsig.com"
};
```

### Checking a feature flag/gate

Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default.

```typescript
if (myStatsigClient.checkGate("new_homepage_design", myUser)) {
  // Gate is on, show new home page
} else {
  // Gate is off, show old home page
}
```

### Reading a dynamic config

Feature Gates work well for simple on/off switches with optional advanced user targeting. To send different values (strings, numbers, and similar types) to your clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates but returns a full JSON object you can configure on the server and fetch typed parameters from. For example:

```typescript
const dynamicConfig = myStatsigClient.getDynamicConfig("awesome_product_details", myUser);
const itemName = dynamicConfig.value["product_name"] ?? "Some Fallback";
const price = dynamicConfig.value["price"] ?? 10.0;

if (dynamicConfig.value["is_discount_enabled"] === true) {
  // apply some discount logic
}
```

### Getting a layer/experiment

Use **Layers/Experiments** to run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse.

```typescript
// Values via getLayer
const layer = myStatsigClient.getLayer("user_promo_experiments", myUser);
const promoTitle = layer.get("title") ?? "Welcome to Statsig!";
const discount = layer.get("discount") ?? 0.1;

// or, via getExperiment
const titleExperiment = myStatsigClient.getExperiment("new_user_promo_title", myUser);
const priceExperiment = myStatsigClient.getExperiment("new_user_promo_price", myUser);

const promoTitle = titleExperiment.value["title"] ?? "Welcome to Statsig!";
const discount = priceExperiment.value["discount"] ?? 0.1;
```

### Logging an event

After you set up a Feature Gate or an Experiment, you can track custom events to measure how your new features or experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and/or a metadata object to log together with the event:

```typescript
import type { StatsigEvent } from '@statsig/client-core';

// log a simple event
myStatsigClient.logEvent('my_simple_event');

// or, include more information by using a StatsigEvent object
const myEvent: StatsigEvent = {
  eventName: 'add_to_cart',
  value: 'SKU_12345',
  metadata: {
    price: '9.99',
    item_name: 'diet_coke_48_pack',
  },
};

myStatsigClient.logEvent(myEvent);
```

### Flushing logged events

`flush()` sends queued events immediately. Use `shutdown()` when your app is exiting.

```typescript
await myStatsigClient.flush();
```

### Code examples

Find working sample apps in the repository:

- [JavaScript & TypeScript Examples](https://github.com/statsig-io/js-client-monorepo/tree/main/samples)

## Statsig user

Provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions.

You usually need the `userID` field to provide a consistent experience for a given user. (Refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users.)

Besides `userID`, StatsigUser has the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them.

> **Note:**
>
> For the JavaScript On-Device Evaluation SDK, you pass the `StatsigUser` object into each evaluation method (`checkGate`, `getConfig`, etc.) rather than during initialization.

> **Note:**
>
> Unlike precomputed evaluation SDKs, the on-device evaluation SDK doesn't have an `updateUser` method since it evaluates gates/configs/experiments in real-time for any user object you pass in.

## Client event emitter

You can subscribe to StatsigClientEvents (not to be confused with [StatsigEvent](#logging-an-event)). These events occur at various stages while using the Statsig client. Subscribe to specific events by specifying the StatsigClientEvent name, or subscribe to all events using the wildcard token `'*'`.

```typescript
import type {
  AnyStatsigClientEvent,
  StatsigClientEvent,
  StatsigClientEventCallback,
} from '@statsig/client-core';

const onAnyClientEvent = (event: AnyStatsigClientEvent) => {
  console.log("Any Client Event", event);
};

const onLogsFlushed = (event: StatsigClientEvent<'logs_flushed'>) => {
  console.log("Logs", event.events);
};

// subscribe to an individual StatsigClientEvent
myStatsigClient.on('logs_flushed', onLogsFlushed);

// or, subscribe to all StatsigClientEvents
myStatsigClient.on('*', onAnyClientEvent);

// then later, unsubscribe from the events
myStatsigClient.off('logs_flushed', onLogsFlushed);
myStatsigClient.off('*', onAnyClientEvent);
```

The full list of events and descriptions can be found [here](https://github.com/statsig-io/js-client-monorepo/blob/main/packages/client-core/src/StatsigClientEventEmitter.ts).

## Statsig options

Configure the SDK's behavior by passing a StatsigOptions object during initialization.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| api | string | No | — | The API to use for all SDK network requests. You don't need to override this unless you have another API that implements the Statsig API endpoints. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logEventUrl | string | No | — | The URL used to flush queued events through a POST request. Takes precedence over `StatsigOptions.api`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logEventBeaconUrl | string | No | — | The URL used to flush queued events through `window.navigator.sendBeacon` (web only). Takes precedence over `StatsigOptions.api`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| downloadConfigSpecsUrl | string | No | — | The URL used to fetch your latest Statsig specifications. Takes precedence over `StatsigOptions.api`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| environment | StatsigEnvironment | No | — | An object you can use to set environment variables that apply to all of your users in the same session. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| overrideStableID | string | No | — | Overrides the auto-generated stableID that is set for the device. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logLevel | LogLevel | No | — | How much information Statsig can print to the console. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| dataAdapter | SpecsDataAdapter | No | — | Implementing this type allows customization of the initialization. Refer to [Using SpecsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) to learn more. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| networkTimeoutMs | number | No | — | The maximum amount of time (in milliseconds) that any network request can take before timing out. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| loggingBufferMaxSize | number | No | — | The maximum number of events to batch before flushing logs to Statsig. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| loggingIntervalMs | number | No | — | How often (in milliseconds) to flush logs to Statsig. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| overrideAdapter | OverrideAdapter | No | — | An implementor of `OverrideAdapter`, used to alter evaluations before Statsig returns them to the caller of a check API (checkGate/getExperiment etc). |

## Manual exposures

> **Warning:**
>
> Manual logging is error-prone and can often introduce issues like uneven exposures, which compromise experiment results.

You can query your gates/experiments without triggering an exposure and manually log the exposures later.

### Gates

```typescript
// Check gate with exposure disabled
const result = myStatsigClient.checkGate('a_gate_name', { user, disableExposureLog: true });

// Manually log the exposure
myStatsigClient.checkGate('a_gate_name', { user });
```

### Configs

```typescript
// Get config with exposure disabled
const config = myStatsigClient.getConfig('a_dynamic_config_name', { user, disableExposureLog: true });

// Manually log the exposure
myStatsigClient.getConfig('a_dynamic_config_name', { user });
```

### Experiments

```typescript
// Get experiment with exposure disabled
const experiment = myStatsigClient.getExperiment('an_experiment_name', { user, disableExposureLog: true });

// Manually log the exposure
myStatsigClient.getExperiment('an_experiment_name', { user });
```

### Layers

```typescript
// Get layer with exposure disabled
const layer = myStatsigClient.getLayer('a_layer_name', { user, disableExposureLog: true });
const paramValue = layer.get('a_param_name', 'fallback_value');

// Manually log the exposure
const layer = myStatsigClient.getLayer('a_layer_name', { user });
const paramValue = layer.get('a_param_name', 'fallback_value');
```

## Lifecycle and advanced usage

## Shutting Statsig down

To save users' data and battery usage and prevent dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, Statsig may not have sent some events when your app shuts down.

To ensure Statsig flushes or saves all logged events locally, call shutdown when your app is closing.

```typescript
await myStatsigClient.shutdown();
```

## Data adapter

The `EvaluationsDataAdapter` type outlines how the `StatsigClient` fetches and caches data during initialize and update operations. By default, the `StatsigClient` uses `StatsigEvaluationsDataAdapter`, a Statsig-provided implementor of the `EvaluationsDataAdapter` type. `StatsigEvaluationsDataAdapter` provides ways to fetch data synchronously from Local Storage and asynchronously from Statsig's servers. Go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) to learn more and see example usage.

## FAQs

#### Does the SDK use the browser local storage or cookies? If so, for what purposes?

The SDK doesn't use any cookies.

It does use local storage for feature targeting and experimentation purposes only. The SDK caches values for feature gates, dynamic configs, and experiments in local storage as a backup if your website/app can't reach the Statsig server to fetch the latest values. If the SDK logged events but couldn't send them to the Statsig server because of issues like network failure, Statsig also saves them in local storage and sends them again when the network restores.

#### How do I run experiments for logged out users?

Go to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment).

## Additional resources

- [On-Device Evaluation SDK Overview](https://docs.statsig.com/client/onDeviceOverview)
- [Client Keys with Server Permissions](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions)
- [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter)
- [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging)

