JavaScript, React, React Native Client SDK
Getting Started
The following will outline how to get up and running with Statsig for JavaScript Precomputed Evaluations.Create an Account
To work with the SDK, you will need a Statsig account. If you don't yet have an account, go ahead and sign up for a free account now.
You could skip this for now, but you will need an SDK key and some gates/experiments to use with the SDK in just a minute.
Installation
You can install the Statsig SDK via npm, yarn or jsdelivr:
- NPM
- CDN / <script>
<script src="https://cdn.jsdelivr.net/npm/@statsig/js-client@latest/build/statsig-js-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-client
yarn add @statsig/js-client
Initialize the SDK
After installation, you will need to initialize the SDK using a Client SDK key from the "API Keys" tab on the Statsig console.
These Client SDK Keys are intended to be embedded in client side applications. If need be, you can invalidate or create new SDK Keys for other applications/SDK integrations.
Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you do accidentally expose it, you can create a new one in the Statsig console.
In addition to the SDK key, you should also pass in a StatsigUser for feature gate targeting and experimentation grouping purposes.
The 3rd parameter is optional and allows you to pass in a StatsigOptions to customize the SDK.
- NPM
- CDN / <script>
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.
It is possible to apply a timeout to async operations. See Async timeouts.
[Recommended] Asynchronous Initialization (Network)
When calling StatsigClient.initializeAsync
, the client will load values
from cache and provide them to the client. The client will then fetch the latest values from the network,
providing the ability to await the latest values from Statsig.
If you want the latest values, but do not want to await the asynchronous call, you may call initializeAsync
and simply .catch
the promise. Note that
this could lead to values changing mid-session as newer values arrive from the network. Alternatively, you can use initializeSync
to initialize with cached values and update the cache in the background. To learn more about sync vs async initialization and how it can be customized, see Using EvaluationsDataAdapter
Working with the SDK
Checking a 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:
See Typed Getters to learn more about accessing values.
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.
See Typed Getters to learn more about accessing values.
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:
Typed Getters
The Layer
, Experiment
and DynamicConfig
objects all support a "typed" get
method. This method can help avoid issues where a
value is not the type you expect.
For example, imagine we have a Dynamic Config with a single number
value called "my_value"
:
// { "my_value": 1 }
const myDynamicConfig = myStatsigClient.getDynamicConfig("a_config");
const myFallbackValue = myDynamicConfig.get("my_value", "fallback"); // returns: "fallback"
const myTypedValue = myDynamicConfig.get("my_value", 0); // returns: 1
const myRawValue = myDynamicConfig.get("my_value"); // returns: 1
Because "my_value"
points to a number
but in the myFallbackValue
case,
we are calling .get
with a string
fallback value, the fallback is being returned.
In the myTypedValue
case, we are passing a number
fallback value, and since "my_value"
is
also a number
, the actual value of 1
is returned.
If typing is not important to you, the fallback argument can be omitted, and
the SDK will simply return the value. This is highlighted in the myRawValue
case.
Evaluation Details
When you receive a value, it may be useful to know how the SDK came to that result.
For this purpose, on every Statsig type there exists a way to check the EvaluationDetails
object.
This object contains the following fields:
Reason
: This is a string containing the source as well as whether or not the specific config was found.Network:Recognized
means the SDK has the latest values and found an entry for the config.Cache:Unrecognized
means we are working with cached values, are could not find the given config.- For the full list of possible combinations, see the page on Debugging.
lcut
: Last Config Update Time - This is the unix timestamp for when any configuration in your project changed.- lcut works as a version number for you project. If it changes, values are deemed out of date and possibly need to be refetched.
receivedAt
: This is the unix timestamp of when the SDK received these values. This can be useful in knowing how old your cache is.
Code Examples
Parameter Stores
Parameter Stores hold a set of parameters for your mobile app. These parameters can be remapped between Statsig entities (Feature Gates, Experiments, and Layers), so you can decouple your code from the configuration in Statsig.
You can read more about the concept here.
Getting a Parameter Store
To fetch a set of parameters, use the following api:
const hompageStore = myStatsigClient.getParameterStore("homepage");
Getting a parameter
You can then access parameters like this:
const title = homepageStore.get(
"title", // parameter name
"Welcome", // default value
);
const showUpsell = homepageStore.get(
"upsell_upgrade_now",
false,
);
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.
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:
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!
Updating Users
At some point, you will probably need to change the StatsigUser being used by the Statsig client. To do this you can call updateUserSync
or updateUserAsync
.
In advanced use cases, you may want to Prefetch or Bootstrap (Provide) values for the updating of a user. See Using EvaluationsDataAdapter to learn how this can be achieved.
Prefetching Users
In some usecases, it can be useful to prefetch values for a given user, such that switching to that user later can be done synchronously.
To do this, you would call prefetchData
and then later updateUserSync
.
Statsig Options
disableLogging boolean
Prevents sending any events over the network.
disableStorage boolean
Prevents writing anything to storage.
Note: caching will not work if storage is disabled
networkConfig object
Allows for fine grained control over which api or urls are hit for specific Statsig network requests
See NetworkConfig object
api string
The API to use for all SDK network requests. You should not need to override this unless you have a custom API that implements the Statsig endpoints.
logEventUrl string
The URL used to flush queued events via a POST request. Takes precedence over
NetworkConfig.api
.default:
https://prodregistryv2.org/v1/rgstr
networkTimeoutMs number
The maximum amount of time (in milliseconds) that any network request can take before timing out.
default:
10,000 ms
(10 seconds)
preventAllNetworkTraffic boolean
Intended for testing purposes. Prevents any network requests being made.
networkOverrideFunc function
Overrides the default networking layer used by the Statsig client. By default, the client use
fetch
, but overriding this you could useaxios
or rawXMLHttpRequest
default:
fetch
initializeUrl string
The URL used to fetch the latest evaluations for a given user. Takes precedence over
NetworkConfig.api
.default:
https://featureassets.org/v1/initialize
environment StatsigEnvironment
An object you can use to set environment variables that apply to all of your users in the same session.
logLevel LogLevel
How much information is allowed to be printed to the console.
default:
LogLevel.Warn
loggingBufferMaxSize number
The maximum number of events to batch before flushing logs to Statsig.
default:
50
loggingIntervalMs number
How often (in milliseconds) to flush logs to Statsig.
default:
10,000 ms
(10 seconds)
overrideAdapter OverrideAdapter
An implementor of OverrideAdapter, used to alter evaluations before its returned to the caller of a check api (checkGate/getExperiment etc).
includeCurrentPageUrlWithEvents boolean
(Web only) Should the 'current page' url be included with logged events.
default:
true
disableStatsigEncoding boolean
Whether or not Statsig should use raw JSON for network requests where possible.
default:
false
disableCompression boolean
Whether or not Statsig should compress JSON bodies for network requests where possible.
default:
false
dataAdapter EvaluationsDataAdapter
An implementor of EvaluationsDataAdapter, used to customize the initialization/update flow.
default:
StatsigEvaluationsDataAdapter
customUserCacheKeyFunc CustomCacheKeyGenerator
Overrides the default cache key generation. Given the SDKKey and current StatsigUser, return a key to be used for storing values related to that user.
default: Cache key is a hash of the
sdkKey
+user.userID
+user.customIDs
.
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:
Advanced
Async timeouts
For the Statsig client calls that hit the network (initializeAsync and updateUserAsync), it is possible to specify a maximum amount of time (in milliseconds) that the method is allowed to take before the promise is resolved.
If this timeout is hit, the promise will resolve and cached values will be used (If any are available). The network request will continue and upon a response, will write values to cache so the will be available for subsequent calls.
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.
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.
Multiple Client Instances
In some usecases, it might be useful to have multiple instances of the Statsig client running.
🔥IMPORTANT: You must use two different SDK keys 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.
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.