To install the Statsig Web SDK, add the package via your preferred package manager. Include optional packages if you plan to enable Session Replay or Auto Capture.
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. These keys are safe to embed in a client application.Along with the key, pass in a User Object with the attributes you’d like to target later on in a gate or experiment.
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.
Now that your SDK is initialized, let’s check a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;) by default.
Copy
Ask AI
if (client.checkGate('new_homepage_design')) { // Gate is on, show new experience} else { // Gate is off, render the default experience}
Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.
Copy
Ask AI
// Reading values via getLayerconst layer = client.getLayer('user_promo_experiments');const promoTitle = layer.get('title', 'Welcome to Statsig!');const discount = layer.get('discount', 0.1);```text```tsx// Reading values via getExperimentconst 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;
Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API for the event, and you can additionally provide some value and/or an object of metadata to be logged together with the event:
Layer, Experiment, and DynamicConfig objects support a typed get method. Using a fallback that matches the expected type helps avoid returning unintended values.
Parameter Stores hold a set of parameters for your mobile app. These parameters can be remapped on-the-fly from a static value to a Statsig entity (Feature Gates, Experiments, and Layers), so you can decouple your code from the configuration in Statsig. Read more about Param Stores here.
You need to provide a StatsigUser object to check/get your configurations. You should pass as much
information as possible in order to take advantage of advanced gate and config conditions.Most of the time, the userID field is needed in order to provide a consistent experience for a given
user (see logged-out experiments to understand how to correctly run experiments for logged-out
users).Besides userID, we also have email, ip, userAgent, country, locale and appVersion as top-level fields on
StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom field and be able to
create targeting based on them.Once the user logs in or has an update/changed, make sure to call updateUser
with the updated userID and/or any other updated user attributes:
In order to save users’ data and battery usage, as well as prevent logged events from being dropped, we keep event logs in client cache and flush periodically.
Because of this, some events may not have been sent when your app shuts down.To make sure all logged events are properly flushed or saved locally, you should tell Statsig to shutdown when your app is closing:
Each client SDK has the notion of stableID, a devive-level identifier that is generated the first time the SDK is initialized and is stored locally for all future sessions. Unless storage is wiped (or app deleted), the stableID will not change.
This allows us to run device level experiments and experiments when other user identifiable information is unavailable (Logged out users).
Up to this point, we’ve used the SDK’s singleton. We also support creating multiples instances of the SDK - the Statsig singleton wraps a single instance of the SDK (typically called a StatsigClient) that you can instantiate.
You must use a different SDK key for each sdk instance you create for this to work. Various functionality of the Statsig client is keyed on the SDK key being used. Using the same key will lead to collisions.
All top level static methods from the singleton carry over as instance methods. To create an instance of the Statsig sdk:
Use the LocalOverrideAdapter to define local overrides for gates, configs, experiments, or layers.
Copy
Ask AI
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,});```text### Persisting OverridesPass your client SDK key to the adapter to persist overrides between sessions when using multi-instance setups.```tsxconst overrideAdapter = new LocalOverrideAdapter('client-xyz');
Capture cookies or URL parameters and pass them through StatsigUser.custom for targeting rules.
Copy
Ask AI
const user = { custom: { isLoggedIn: cookieLib.get('isLoggedIn'), utm: new URL(window.location.href).searchParams.get('utm'), },};const client = new StatsigClient('client-xyz', user, options);```text<Frame> <img src="/images/client/js-common-targeting.png" alt="Targeting in Console" /></Frame>## Async TimeoutsLimit how long `initializeAsync` and `updateUserAsync` wait for network responses before falling back to cached values.```tsxawait client.initializeAsync({ timeoutMs: 1000 });await client.updateUserAsync( { userID: 'a-user' }, { timeoutMs: 1000 },);
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.See Using EvaluationsDataAdapter for full examples, including bootstrapping, prefetching, and custom adapters.
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.
import { LogLevel, StatsigClient } from '@statsig/js-client';const client = new StatsigClient('client-xyz', { userID: 'a-user' }, { logLevel: LogLevel.Debug,});```ruby### Inspect the `__STATSIG__` GlobalOpen your browser console and run `__STATSIG__` to inspect the current client instance. Useful properties include `_logger._queue` for pending events.<Frame> <img src="/images/client/statsig-global.png" alt="Statsig Global" /></Frame>### Review Network TrafficFilter network requests by `client-` to see initialization and logging calls.<Frame> <img src="/images/client/network-logs.png" alt="Network Logs" /></Frame>### Check Evaluation Reasons```tsconst 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 via dataAdapter.setData.
window.Statsig.instance().logEvent('test_event');```text```tsimport { StatsigClient } from '@statsig/js-client';StatsigClient.instance().logEvent('test_event');```text<Info>With multiple instances, pass the SDK key: `Statsig.instance('client-YOUR_KEY')`.</Info>#### How do I handle consent or GDPR flows?Start with logging disabled and storage blocked, then enable them after consent.```tsxconst 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 once logging is re-enabled.