JavaScript Client SDK
On-device evaluation sdks are for Enterprise and Pro Tier companies only. If you are trying to follow these instructions but do not meet that criteria, some of the setup steps may not work.
The @statsig/js-on-device-eval-client
SDK uses a different paradigm then its precomputed counter part (@statsig/js-client).
It is a Client SDK that behaves more like a Server SDK. Rather than requiring a user up front, you can check gates/configs/experiments for any set of user properties, because 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 - just 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 cannot be cached as much)
Cons
- Entire project definition is available client side - the names and configurations of all experiments and feature flags accessible by your client key are exposed.
- Payload size is strictly larger than what is required for the @statsig/js-client.
- Evaluation performance is slightly slower - rather than looking up the value, the SDK must actually evaluate targeting conditions and an allocation decision
- Does not support ID list segments with > 1000 IDs
- Does not support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country)
Installation
You can install the Statsig SDK via npm, yarn or jsdelivr:
- NPM
- CDN / <script>
- Yarn
<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 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
npm install @statsig/js-on-device-eval-client
yarn add @statsig/js-on-device-eval-client
Initialize the SDK
Initialize the SDK using a Client SDK key from the "API Keys" tab on the Statsig console. When creating the key, or using an existing key, you will need to add the "Allow Download Config Specs" scope. Client keys, by default, are not able to download the project definition to do on device evaluation. You must opt in to allow your client key to access your full project definition on our cdn.
- New SDK Keys
- Existing SDK Keys
To add the scope to an existing key, under Project Settings > API Keys > Client API Keys, select Actions > Edit Scopes, and "Allow Download Config Specs", then Save.
When creating a new client key, select "Allow Download Config Specs"
Do NOT embed a Server Secret Key in client side applications.
Note: In advanced use cases, you may want to Prefetch or Bootstrap (Provide) values for initialization. See Using EvaluationsDataAdapter to learn how this can be achieved.
Working with the SDK
Setup a StatsigUser
To interact with the SDK, you will need to create a StatsigUser
object. The full definition of this
object can be found here.
const myUser = {
userID: "a-user",
email: "user@statsig.com"
};
Checking a Feature Flag/Gate
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.
Reading a Dynamic Config
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:
Getting an Layer/Experiment
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.
Logging an Event
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:
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
Code Examples
Prefer seeing it in practice? Included in the open source repository are some Code Examples. View these for common use cases for the SDK.
Statsig User
You should provide a StatsigUser object whenever possible when initializing the SDK, passing as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks).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.
Private Attributes
Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes
, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes
will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.
For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" }
to privateAttributes
on the user and that's it!
Client Event Emitter
It is possible to subscribe to StatsigClientEvents (Not to be confused with StatsigEvent). These events occur at various stages while using the Statsig client. You can subscribe to specific events by specifying the StatsigClientEvent name, or, all events by using the wildcard token '*'.
The full list of events and descriptions can be found here.
Statsig Options
You can configure certain aspects of the SDKs behavior by passing a StatsigOptions object during initialization.
- api:
string
- The API to use for all SDK network requests. You should not need to override this unless you have another API that implements the Statsig API endpoints.
- logEventUrl:
string
- The URL used to flush queued events via a POST request. Takes precedence over
StatsigOptions.api
.
- The URL used to flush queued events via a POST request. Takes precedence over
- logEventBeaconUrl:
string
- The URL used to flush queued events via
window.navigator.sendBeacon
(web only). Takes precedence overStatsigOptionsCommon.api
.
- The URL used to flush queued events via
- downloadConfigSpecsUrl:
string
, defaulthttps://api.statsigcdn.com/v1/download_config_specs
- The URL used to fetch your latest Statsig specifications. Takes precedence over
StatsigOptions.api
.
- The URL used to fetch your latest Statsig specifications. Takes precedence over
- environment:
StatsigEnvironment
- An object you can use to set environment variables that apply to all of your users in the same session.
- overrideStableID:
string
- Overrides the auto-generated stableID that is set for the device.
- logLevel:
LogLevel
, defaultLogLevel.Warn
- How much information is allowed to be printed to the console.
- dataAdapter:
SpecsDataAdapter
, defaultStatsigSpecsDataAdapter
- Implementing this type allows customization of the initialization. See Using SpecsDataAdapter to learn more.
- networkTimeoutMs:
number
, default10,000
- The maximum amount of time (in milliseconds) that any network request can take before timing out.
- loggingBufferMaxSize:
number
, default50
- The maximum number of events to batch before flushing logs to Statsig.
- loggingIntervalMs:
number
, default10,000
- How often (in milliseconds) to flush logs to Statsig.
- overrideAdapter:
OverrideAdapter
- An implementor of
OverrideAdapter
, used to alter evaluations before its returned to the caller of a check api (checkGate/getExperiment etc).
- An implementor of
Manual Exposures
Manually logging exposures can be tricky and may lead to an imbalance in exposure events. For example, only triggering exposures for users in the Test group of an experiment will imbalance the experiment, making it useless.
Added in version , you can now query your gates/experiments without triggering an exposure as well as manually logging your exposures.
- Check Gate
- Get Config
- Get Experiment
- Get Layer
To check a gate without an exposure being logged, call the following.
const result = myStatsigClient.checkGate('a_gate_name', { user, disableExposureLog: true });
Later, if you would like to expose this gate, you can call the following.
myStatsigClient.checkGate('a_gate_name', { user });
To get a dynamic config without an exposure being logged, call the following.
const config = myStatsigClient.getConfig('a_dynamic_config_name', { user, disableExposureLog: true });
Later, if you would like to expose the dynamic config, you can call the following.
myStatsigClient.getConfig('a_dynamic_config_name', { user });
To get an experiment without an exposure being logged, call the following.
const experiment = myStatsigClient.getExperiment('an_experiment_name', { user, disableExposureLog: true });
Later, if you would like to expose the experiment, you can call the following.
myStatsigClient.getExperiment('an_experiment_name', { user });
To get a layer parameter without an exposure being logged, call the following.
const layer = myStatsigClient.getLayer('a_layer_name', { user, disableExposureLog: true });
const paramValue = layer.get('a_param_name', 'fallback_value');
Later, if you would like to expose the layer parameter, you can call the following.
const layer = myStatsigClient.getLayer('a_layer_name', { user });
const paramValue = layer.get('a_param_name', 'fallback_value');
Shutting Statsig Down
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:
Data Adapter
The EvaluationsDataAdapter
type outlines how the StatsigClient
should fetch and cache 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.
See Using EvaluationsDataAdapter to learn more and see example usage.
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments
Does the SDK use the browser local storage or cookies? If so, for what purposes?
The SDK does not use any cookies.
It does use the local storage for feature targeting and experimentation purposes only. Values for feature gates, dynamic configs and experiments are cached in the local storage, which are used as a backup in the event that your website/app cannot reach the Statsig server to fetch the latest values. If any events were logged but could not be sent to Statsig server due to issues like network failure, we also save them in the local storage to be sent again when network restores.