---
title: JavaScript Client SDK (Web)
description: Statsig's JavaScript SDK for browser and React applications.
product: general
token_estimate: 7992
---
# JavaScript Client SDK (Web)

> 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-client` ([npm](https://www.npmjs.com/package/@statsig/js-client))
- **Latest version:** 3.33.5
- **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo)

## Set up the SDK

1. **Install the SDK**

   To install the Statsig Web SDK, add the package using your preferred package manager. Include optional packages if you plan to enable Session Replay or Auto Capture.

   #### npm

   ```bash
   npm install @statsig/js-client @statsig/session-replay @statsig/web-analytics
   ```

   #### yarn

   ```bash
   yarn add @statsig/js-client @statsig/session-replay @statsig/web-analytics
   ```

   > **Info:**
   >
   > If you don't need Session Replay or Auto Capture, omit the `@statsig/session-replay` and `@statsig/web-analytics` packages.

   After installation, configure the SDK in your app entry point before rendering your UI.
2. **Initialize the SDK**

   Next, 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.

   ```tsx
   import { StatsigClient } from '@statsig/js-client';

   const client = new StatsigClient(
     'client-xyz',
     { userID: 'a-user' },
     {
       environment: { tier: 'development' },
     },
   );

   await client.initializeAsync();
   ```

   Use `initializeAsync` when you need to await the latest values. For a non-blocking approach, you can call `initializeAsync()` without awaiting and rely on cached values until the promise resolves.

## Use the SDK

### 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.

```tsx
if (client.checkGate('new_homepage_design')) {
  // Gate is on, show new experience
} else {
  // Gate is off, render the default experience
}
```

### 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:

```tsx
const config = client.getDynamicConfig('awesome_product_details');
const itemName = config.get('product_name', 'Some Fallback');
const price = config.value.price ?? 10.0;

if (config.value.is_discount_enabled === true) {
  // apply 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.

```tsx
// Reading values via getLayer
const layer = client.getLayer('user_promo_experiments');
const promoTitle = layer.get('title', 'Welcome to Statsig!');
const discount = layer.get('discount', 0.1);
```

```tsx
// Reading values via getExperiment
const titleExperiment = client.getExperiment('new_user_promo_title');
const priceExperiment = client.getExperiment('new_user_promo_price');

const experimentTitle = titleExperiment.value.title ?? 'Welcome to Statsig!';
const experimentDiscount = 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:

```tsx
client.logEvent('my_simple_event');

client.logEvent({
  eventName: 'add_to_cart',
  value: 'SKU_12345',
  metadata: {
    price: '9.99',
    item_name: 'diet_coke_48_pack',
  },
});
```

### Flushing logged events

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

```tsx
await client.flush();
```

### Typed getters

`Layer`, `Experiment`, and `DynamicConfig` objects support a typed `get` method. Using a fallback that matches the expected type helps avoid returning unintended values.

```tsx
// config value: { "my_value": 1 }
const dynamicConfig = client.getDynamicConfig('a_config');

const fallbackString = dynamicConfig.get('my_value', 'fallback'); // returns 'fallback'
const fallbackNumber = dynamicConfig.get('my_value', 0); // returns 1
const rawValue = dynamicConfig.get('my_value'); // returns 1
```

Passing a fallback of the wrong type returns that fallback. When you don't need type safety, omit the fallback to receive the raw value.

### Evaluation details

Each gate, config, experiment, and layer exposes `details` describing how Statsig resolved the value.

- `reason` explains the source (e.g., `Network:Recognized`, `Cache:Unrecognized`).
- `lcut` is the last time any configuration changed in your project.
- `receivedAt` marks when the SDK received this response, useful for judging cache staleness.

```tsx
const gate = client.getFeatureGate('a_gate');
console.log(gate.details);
// { reason: 'Cache:Recognized', lcut: 1713837126636, receivedAt: 1713838137598 }

const config = client.getDynamicConfig('a_config');
console.log(config.details);
// { reason: 'Cache:Unrecognized', lcut: 1713837126636, receivedAt: 1713838137598 }
```

Go to [`/sdk/debugging`](https://docs.statsig.com/sdks/debugging) for the full list of `reason` values.

### Sample projects

Explore end-to-end examples in the [`js-client-monorepo` samples folder](https://github.com/statsig-io/js-client-monorepo/tree/main/samples) for React, Next.js, precomputed clients, and more.

## Parameter Stores

Parameter Stores hold a set of parameters for your mobile app. You can remap these parameters dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers), so you can decouple your code from the configuration in Statsig. Go to [Parameter Stores](https://docs.statsig.com/client/concepts/parameter-stores) to learn more.

```tsx
const homepageStore = client.getParameterStore('homepage');

const title = homepageStore.get('title', 'Welcome');
const showUpsell = homepageStore.get('upsell_upgrade_now', false);
```

## 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 also 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.

After the user logs in or their attributes change, call `updateUser` with the updated `userID` and/or any other updated user attributes.

### Updating users

Call `updateUserAsync` when the signed-in user changes to fetch fresh values for that identity.

```tsx
const user = { userID: 'a-user' };
await client.updateUserAsync(user);
```

For advanced flows such as bootstrapping or prefetching users, go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter).

### Prefetching users

Use `prefetchData` to prepare values for another user so you can switch synchronously later.

```tsx
const nextUser = { userID: 'my-other-user' };

await client.dataAdapter.prefetchData(nextUser);
// Optionally handle failures without blocking the UI
client.dataAdapter.prefetchData(nextUser).catch((err) => {
  console.warn('Failed to prefetch', err);
});

client.updateUserSync(nextUser);
const gate = client.getFeatureGate('a_gate');
console.log(gate.value, gate.details.reason); // true, 'Prefetch:Recognized'
```

## Statsig options

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| loggingEnabled | LoggingEnabledOption | No | — | Controls logging behavior.- `browser-only` (default): log events from browser environments. - `disabled`: never send events. - `always`: log in every environment, including non-browser contexts. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableLogging | boolean | No | — | Use `loggingEnabled: 'disabled'` instead. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableStableID | boolean | No | — | Skip generating a device-level Stable ID. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableEvaluationMemoization | boolean | No | — | Recompute every evaluation instead of using the memoized result. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| initialSessionID | string | No | — | Override the generated session ID. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| enableCookies | boolean | No | — | Persist Stable ID in cookies for cross-domain tracking. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableStorage | boolean | No | — | Prevent any local storage writes (disables caching). |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| networkConfig | NetworkConfig | No | — | Override network endpoints per request type. |

#### Network Config Options

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| api | string | No | — | Base URL for all requests. The SDK appends endpoint paths like `/initialize` and `/rgstr`; append `/v1` when your proxy expects it. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| initializeUrl | string | No | — | Endpoint for initialization requests only. Takes precedence over `api` for `/initialize`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| initializeFallbackUrls | string[] | No | — | Fallback endpoints for initialization requests only. This doesn't create a generic fallback for `api`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logEventUrl | string | No | — | Endpoint for event uploads. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logEventFallbackUrls | string[] | No | — | Fallback endpoints for event uploads only. This doesn't create a generic fallback for `api`. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| networkTimeoutMs | number | No | — | Request timeout in milliseconds. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| preventAllNetworkTraffic | boolean | No | — | Disable all outbound requests; combine with `loggingEnabled: 'disabled'` to silence log warnings. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| networkOverrideFunc | function | No | — | Provide custom transport (e.g., Axios). |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| environment | StatsigEnvironment | No | — | Set environment-wide defaults (for example `{ tier: 'staging' }`). |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logLevel | LogLevel | No | — | Console verbosity. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| loggingBufferMaxSize | number | No | — | Max events per log batch. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| loggingIntervalMs | number | No | — | Interval between automatic flushes. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| overrideAdapter | OverrideAdapter | No | — | Modify evaluations before returning them. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| includeCurrentPageUrlWithEvents | boolean | No | — | Attach the current page URL to logged events. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableStatsigEncoding | boolean | No | — | Send requests without Statsig-specific encoding. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| logEventCompressionMode | LogEventCompressionMode | No | — | Control compression for batched events. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| disableCompression | boolean | No | — | Use `logEventCompressionMode` instead. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| dataAdapter | EvaluationsDataAdapter | No | — | Provide a custom data adapter to control caching/fetching. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| customUserCacheKeyFunc | CustomCacheKeyGenerator | No | — | Override cache key generation for stored evaluations. |

## 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:

#### Feature Gates

```tsx
const result = client.checkGate('a_gate_name', { disableExposureLog: true });
// ...
client.checkGate('a_gate_name'); // later, when ready to log the exposure
```

#### Dynamic Configs

```tsx
const config = client.getConfig('a_dynamic_config_name', { disableExposureLog: true });
client.getConfig('a_dynamic_config_name');
```

#### Experiments

```tsx
const experiment = client.getExperiment('an_experiment_name', { disableExposureLog: true });
client.getExperiment('an_experiment_name');
```

#### Layers

```tsx
const layer = client.getLayer('a_layer_name', { disableExposureLog: true });
const value = layer.get('param_name', 'fallback');

// When ready to log
const exposure = client.getLayer('a_layer_name');
exposure.get('param_name', 'fallback');
```

## Session Replay

Install `@statsig/session-replay` and register the plugin to record user sessions.

```tsx
import { StatsigProvider } from '@statsig/react-bindings';
import { StatsigSessionReplayPlugin } from '@statsig/session-replay';

<StatsigProvider
  sdkKey="client-xyz"
  user={{ userID: 'a-user' }}
  loadingComponent={<div style={{ height: 100, width: 300, padding: 16 }}>Loading...</div>}
  options={{ plugins: [new StatsigSessionReplayPlugin()] }}
>
  <App />
</StatsigProvider>;
```

## Web Analytics / Auto Capture

By including the [`@statsig/web-analytics`](https://www.npmjs.com/package/@statsig/web-analytics) package in your project, you can automatically capture common web events like clicks and page views.

For more information on filtering events, enabling console log capture, and other configuration options available in web analytics, refer to the [Web Analytics Configuration](https://docs.statsig.com/webanalytics/overview#event-filtering-and-console-configuration) documentation.

```tsx
import { StatsigProvider } from '@statsig/react-bindings';
import { StatsigAutoCapturePlugin } from '@statsig/web-analytics';

<StatsigProvider
  sdkKey="client-xyz"
  user={{ userID: 'a-user' }}
  loadingComponent={<div style={{ height: 100, width: 300, padding: 16 }}>Loading...</div>}
  options={{ plugins: [new StatsigAutoCapturePlugin()] }}
>
  <App />
</StatsigProvider>;
```

## Content Security Policy

Add Statsig endpoints to your CSP `connect-src` directive when running the web SDK.

```js
const cspConfig = {
  directives: {
    'connect-src': [
      'api.statsig.com',
      'featuregates.org',
      'statsigapi.net',
      'events.statsigapi.net',
      'api.statsigcdn.com',
      'featureassets.org',
      'assetsconfigcdn.org',
      'prodregistryv2.org',
      'cloudflare-dns.com',
      'beyondwickedmapping.org',
    ],
  },
};
```

> **Info:**
>
> Statsig occasionally updates its network domains. Verify the latest list in [Statsig Domains](https://docs.statsig.com/infrastructure/statsig_domains).

## 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.

```tsx
await client.shutdown();
```

## Stable ID

Stable ID provides a consistent device identifier. It lets you run [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) and target gates at the device level.

### How Stable ID works

- On first initialization the SDK generates a Stable ID and stores it in `localStorage` under `statsig.stable_id.<SDK_KEY_HASH>`.
- Subsequent sessions reuse the stored value. Each client SDK key has its own Stable ID entry.
- Local storage is scoped per domain, so cross-domain usage requires sharing the value manually (see below).

### Reading the Stable ID

#### JavaScript

```tsx
const context = client.getContext();
console.log('Statsig StableID:', context.stableID);
```

#### React

```tsx
import { useStatsigClient } from '@statsig/react-bindings';

function MyComponent() {
  const { client } = useStatsigClient();
  const context = client.getContext();

  return <div>{context.stableID}</div>;
}
```

### Overriding the Stable ID

Provide a custom Stable ID through `StatsigUser.customIDs.stableID` if you already manage a durable device identifier.

#### JavaScript

```tsx
import { StatsigClient, StatsigUser } from '@statsig/js-client';

const userWithStableID: StatsigUser = {
  customIDs: {
    stableID: 'my-custom-stable-id',
  },
};

const client = new StatsigClient('client-xyz', userWithStableID);
await client.updateUserAsync(userWithStableID);
```

#### React

```tsx
import { StatsigProvider, useStatsigClient } from '@statsig/react-bindings';

function App() {
  return (
    <StatsigProvider
      sdkKey="client-xyz"
      user={{
        customIDs: { stableID: 'my-custom-stable-id' },
      }}
    >
      <div>Your App</div>
    </StatsigProvider>
  );
}

function MyComponent() {
  const { client } = useStatsigClient();
  useEffect(() => {
    client.updateUserAsync({
      customIDs: { stableID: 'my-custom-stable-id' },
    });
  }, [client]);
}
```

> **Note:**
>
> When you override the Stable ID, Statsig persists it to local storage, so subsequent sessions reuse your custom value.

### Sharing Stable ID across subdomains

Add this helper script before initializing the SDK and then copy the stored value onto your user object.

```html
<!-- cross domain id script -->
<script>!function(){let t="STATSIG_LOCAL_STORAGE_STABLE_ID";function e(){if(crypto&&crypto.randomUUID)return crypto.randomUUID();let t=()=>Math.floor(65536*Math.random()).toString(16).padStart(4,"0");return`$\{t()\}${t()}-$\{t()\}-4${t().substring(1)}-$\{t()\}-${t()}$\{t()\}${t()}`}let i=null,n=localStorage.getItem(t)||null;if(document.cookie.match(/statsiguuid=([\w-]+);?/)&&([,i]=document.cookie.match(/statsiguuid=([\w-]+);?/)),i&&n&&i===n);else if(i&&n&&i!==n)localStorage.setItem(t,i);else if(i&&!n)localStorage.setItem(t,i);else{let o=e();localStorage.setItem(t,o),function t(i){let n=new Date;n.setMonth(n.getMonth()+12);let o=window.location.host.split(".");o.length>2&&o.shift();let s=`.$\{o.join(".")\}`;document.cookie=`statsiguuid=${i||e()};Expires=$\{n\};Domain=${s};Path=/`}(o)}}();</script>

<!-- Manually attach stableID to user object -->
<script>
const userObj = {};
if (localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID')) {
  userObj.customIDs = {
    stableID: localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID'),
  };
}
const client = new Statsig.StatsigClient('<client-sdk-key>', userObj);
</script>
```

_Use this script at your discretion and test thoroughly._

### Aligning Stable ID between client and server

To share Stable ID with a backend Statsig SDK, send the value with requests and persist it server-side when missing. The server can bootstrap the client with the same Stable ID.

```tsx
// Server: ensure Stable ID exists, then return initialize response for the client
const values = Statsig.getClientInitializeResponse(user, YOUR_CLIENT_KEY, {
  hash: 'djb2',
});

// Client: apply the server-provided values and initialize synchronously
const { values, user: verifiedUser } = await fetch('/init-statsig-client', {
  method: 'POST',
  body: loadUserData(),
}).then((res) => res.json());

const myClient = new StatsigClient(YOUR_CLIENT_KEY, verifiedUser);
myClient.dataAdapter.setData(values);
myClient.initializeSync();
```

## Using multiple instances of the SDK

The examples above use the SDK's singleton. Statsig also supports creating multiple instances of the SDK. The `Statsig` singleton wraps a single instance of the SDK (typically called a `StatsigClient`) that you can instantiate directly.

> **Note:**
>
> Use a different SDK key for each SDK instance. The Statsig client keys various functionality on the SDK key you use. Using the same key causes collisions.

All top-level static methods from the singleton carry over as instance methods. To create an instance of the Statsig SDK:

```tsx
import { StatsigClient } from '@statsig/js-client';

const mainClient = new StatsigClient('client-xyz', { userID: 'a-user' });
const secondaryClient = new StatsigClient('client-abc', { userID: 'another-user' });

await Promise.all([
  mainClient.initializeAsync(),
  secondaryClient.initializeAsync(),
]);

if (mainClient.checkGate('a_gate')) {
  // ...
}

if (secondaryClient.checkGate('some_other_gate')) {
  // ...
}
```

## Override adapter

Use the `LocalOverrideAdapter` to define local overrides for gates, configs, experiments, or layers.

```tsx
import { LocalOverrideAdapter } from '@statsig/js-local-overrides';
import { StatsigClient, LogLevel } from '@statsig/js-client';

const overrideAdapter = new LocalOverrideAdapter();
overrideAdapter.overrideGate('gate_a', false);
overrideAdapter.overrideGate('gate_b', true);

const client = new StatsigClient('client-xyz', { userID: 'a-user' }, {
  logLevel: LogLevel.Debug,
  overrideAdapter,
});
```

### Persisting overrides

Pass your client SDK key to the adapter to persist overrides between sessions when using multi-instance setups.

```tsx
const overrideAdapter = new LocalOverrideAdapter('client-xyz');
```

## Using persistent evaluations

Persist experiment assignments so users keep the same variant even if targeting rules change.

```tsx
import { StatsigClient } from '@statsig/js-client';
import { UserPersistentOverrideAdapter } from '@statsig/js-user-persisted-storage';

class LocalStorageUserPersistedStorage {
  load(key: string) {
    return JSON.parse(localStorage.getItem(key) ?? '{}');
  }

  save(key: string, experiment: string, data: string) {
    const values = JSON.parse(localStorage.getItem(key) ?? '{}');
    values[experiment] = JSON.parse(data);
    localStorage.setItem(key, JSON.stringify(values));
  }

  delete(key: string, experiment: string) {
    const data = JSON.parse(localStorage.getItem(key) ?? '{}');
    delete data[experiment];
    localStorage.setItem(key, JSON.stringify(data));
  }
}

const storage = new LocalStorageUserPersistedStorage();
const adapter = new UserPersistentOverrideAdapter(storage);
const client = new StatsigClient('client-xyz', { overrideAdapter: adapter });

await client.initializeAsync({ userID: '123' });

const userPersistedValues = adapter.loadUserPersistedValues({ userID: '123' }, 'userID');
const experiment = client.getExperiment('active_experiment', { userPersistedValues });
```

Refer to [Client Persistent Assignment](https://docs.statsig.com/client/concepts/persistent_assignment) for additional patterns and storage options.

## Common targeting use cases

Capture cookies or URL parameters and pass them through `StatsigUser.custom` for targeting rules.

```tsx
const user = {
  custom: {
    isLoggedIn: cookieLib.get('isLoggedIn'),
    utm: new URL(window.location.href).searchParams.get('utm'),
  },
};

const client = new StatsigClient('client-xyz', user, options);
```

![Targeting in Console](https://docs.statsig.com/images/client/js-common-targeting.png)

## Async timeouts

Limit how long `initializeAsync` and `updateUserAsync` wait for network responses before falling back to cached values.

```tsx
await client.initializeAsync({ timeoutMs: 1000 });

await client.updateUserAsync(
  { userID: 'a-user' },
  { timeoutMs: 1000 },
);
```

### Data adapter

`StatsigClient` uses an `EvaluationsDataAdapter` to manage caching and network fetches. The default implementation (`StatsigEvaluationsDataAdapter`) reads from local storage synchronously and refreshes values from Statsig asynchronously.

Go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) for full examples, including bootstrapping, prefetching, and custom adapters.

### Partial user matching

Use `customUserCacheKeyFunc` with `updateUserSync` when you need to enrich a user locally without triggering a full network refresh.

```tsx
const originalUser = {
  customIDs: {
    analyticsID: 'analytics-123',
  },
};

const customKey = (sdkKey: string, user: StatsigUser) => {
  const analyticsID = user.customIDs?.analyticsID ?? 'anonymous';
  return `sdkKey:$\{sdkKey\}:analyticsID:${analyticsID}`;
};

const client = new StatsigClient('client-xyz', originalUser, {
  customUserCacheKeyFunc: customKey,
});

await client.initializeAsync();

someAsyncFunction().then((newData) => {
  const enrichedUser = {
    ...originalUser,
    userID: newData.userID,
    email: newData.email,
  };

  client.updateUserSync(enrichedUser);
});
```

> **Warning:**
>
> Custom cache keys can produce stale or incorrect evaluations if multiple users map to the same key. Await `updateUserAsync` when you need guaranteed fresh values per user.

### Client event emitter

Subscribe to Statsig client lifecycle events to respond to initialization, logging, or evaluation changes.

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

const onAnyEvent = (event: AnyStatsigClientEvent) => {
  console.log('Statsig event', event);
};

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

client.on('logs_flushed', onLogsFlushed);
client.on('*', onAnyEvent);

client.off('logs_flushed', onLogsFlushed);
client.off('*', onAnyEvent);
```

| Event | Payload | Description |
| --- | --- | --- |
| `values_updated` | `{ status, values }` | Fired when initialize/update refreshes cached values. |
| `session_expired` | `{}` | Fired when the current session expires. |
| `error` | `{ error, tag }` | Unexpected client errors. |
| `pre_logs_flushed` | `{ events }` | Before Statsig sends a batch of events. |
| `logs_flushed` | `{ events }` | After Statsig sends events. |
| `pre_shutdown` | `{}` | Before the SDK shuts down. |
| `initialization_failure` | `{}` | Initialization failed. |
| `gate_evaluation` | `{ gate }` | When Statsig evaluates a gate. |
| `dynamic_config_evaluation` | `{ dynamicConfig }` | When Statsig evaluates a config. |
| `experiment_evaluation` | `{ experiment }` | When Statsig evaluates an experiment. |
| `layer_evaluation` | `{ layer }` | When Statsig evaluates a layer. |
| `log_event_called` | `{ event }` | When you call `logEvent`. |

## Quality and troubleshooting

## Testing

Mock Statsig APIs in Jest to isolate business logic.

```tsx
import { StatsigClient } from '@statsig/js-client';

export async function transform(input: string): Promise<string> {
  const client = new StatsigClient('client-xyz', { userID: 'a-user' }, {
    networkConfig: {
      preventAllNetworkTraffic:
        typeof process !== 'undefined' && process.env['NODE_ENV'] === 'test',
    },
  });

  await client.initializeAsync();

  if (client.checkGate('a_gate')) {
    input = 'transformed';
  }

  const experiment = client.getExperiment('an_experiment');
  input += '-' + experiment.get('my_param', 'fallback');

  await client.shutdown();
  return input;
}
```

```tsx
import { StatsigClient } from '@statsig/js-client';

jest.mock('@statsig/js-client');

test('string transformations', async () => {
  jest
    .spyOn(StatsigClient.prototype, 'checkGate')
    .mockImplementation(() => true);

  jest
    .spyOn(StatsigClient.prototype, 'getExperiment')
    .mockImplementation(() => ({ get: () => 'my-value' } as any));

  const result = await transform('original');
  expect(result).toBe('transformed-my-value');
});
```

## Debugging

When results look unexpected, use these tools to inspect what the SDK is doing.

### Enable verbose logging

```ts
import { LogLevel, StatsigClient } from '@statsig/js-client';

const client = new StatsigClient('client-xyz', { userID: 'a-user' }, {
  logLevel: LogLevel.Debug,
});
```

### Inspect the `__STATSIG__` global

Open your browser console and run `__STATSIG__` to inspect the current client instance. Useful properties include `_logger._queue` for pending events.

![Statsig Global](https://docs.statsig.com/images/client/statsig-global.png)

### Review network traffic

Filter network requests by `client-` to see initialization and logging calls.

![Network Logs](https://docs.statsig.com/images/client/network-logs.png)

### Check evaluation reasons

```ts
const gate = client.getFeatureGate('a_gate');
console.log(gate.details.reason);
```

Common reasons:

- `Network` | `NetworkNotModified`: latest values from the API.
- `Cache`: loaded from local storage.
- `NoValues`: no cached values and network failed.
- `Bootstrap`: values provided through `dataAdapter.setData`.
- `Prefetch`: values from `dataAdapter.prefetchData`.

Go to [`/sdk/debugging`](https://docs.statsig.com/sdks/debugging#reasons) for full details.

## FAQs

#### Does the SDK use local storage or cookies

Statsig's web SDK doesn't set cookies. It stores gate/config values and unsent events in `localStorage` so features keep working when offline.

#### Can I access the SDK instance globally

```tsx
window.Statsig.instance().logEvent('test_event');
```

```ts
import { StatsigClient } from '@statsig/js-client';
StatsigClient.instance().logEvent('test_event');
```

> **Info:**
>
> With multiple instances, pass the SDK key: `Statsig.instance('client-YOUR_KEY')`.

#### How do I handle consent or GDPR flows

Start with logging disabled and storage blocked, then enable them after consent.

```tsx
const client = new StatsigClient('client-xyz', {}, {
  loggingEnabled: 'disabled',
  disableStorage: true,
});
await client.initializeAsync();

client.updateRuntimeOptions({
  loggingEnabled: 'browser-only',
  disableStorage: false,
});
```

The SDK buffers up to 500 events in memory and flushes them after logging is re-enabled.

## Additional resources

- [Client Persistent Assignment](https://docs.statsig.com/client/concepts/persistent_assignment)
- [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter)
- [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging)

