Node Core Server SDK
Statsig Server Core
Statsig Server Core is currently in beta - we encourage you to try it out and give us feedback in the Statsig Slack.
Statsig Server Core is a performance-focused rewrite of Statsig server SDKs with a shared core Rust library, that we're rolling out as an option for each Server Environment we currently support with SDKs.
Server Core brings Rust's natural speed and performance optimizations to each language, as we develop them in one, shared library. Initial benchmarking suggests Server Core can evaluate 5-10x as fast as existing SDKs. Beside evaluation performance improvement, we introduced new compression mechanism, which should reduce outbound (egress) network payload significantly.
Server Core also introduces many new features, for example,
- Param Stores, including bootstrap with param stores,
- SDK Observability Interface
- Streaming Config Specs and etc.
Server Core is currently available for Java, Node, and Python. Need another language? Let us know in the Statsig Slack and we'll prioritize it.
Installation
To use the Statsig Server Core SDK, install the @statsig/statsig-node-core
package.
npm i @statsig/statsig-node-core
or
dependencies {
"statsig/statsig-node-core": "0.0.6-beta.2"
}
SDKs are pre-built, compiled according to different os and cpu architectures, for most of cases you don't need to worry about which version to use. But if your service is locking you dependency with package-lock.json (e.g. using pnpm-lock.yml). You need to be aware that you are installing all packages (architectures and system specific versions). For example, you need to run the service locally (macOS) and deployed service to linux, then you need to include both packages.
// For example
dependencies {
"statsig/statsig-node-core-darwin-arm64": "0.0.6-beta.2" // for macOS
"statsig/statsig-node-core-linux-x64-gnu": "0.0.6-beta.2" // for linux x64 machines
}
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the statsig console.
Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.
options
that allows you to pass in a StatsigOptions to customize the SDK.// Basic initialization
const statsig = new Statsig("secret-key");
await statsig.initialize();
// or with StatsigOptions
const options = new StatsigOptions();
options.environment = "staging";
const statsigWithOptions = new Statsig("secret-key", options);
await statsigWithOptions.initialize();
initialize
will perform a network request. After initialize
completes, virtually all SDK operations will be synchronous (See Evaluating Feature Gates in the Statsig SDK). The SDK will fetch updates from Statsig in the background, independently of your API calls.Working with the SDK
Checking a Feature Flag/Gate
Now that your SDK is initialized, let's fetch 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.
From this point on, all APIs will require you to specify the user (see Statsig user) associated with the request. For example, check a gate for a certain user like this:
const user = new StatsigUser({ userID: "a-user" });
if (statsig.checkGate(user, "a_gate")) {
// Gate is on, enable new feature
} else {
// Gate is off
}
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:
// Get the dynamic config
const config = statsig.getDynamicConfig(user, "a_config");
// Get typed values using the get() method
const itemName = config.get("product_name", "Awesome Product v1");
const price = config.get<number>("price", 10.0);
const shouldDiscount = config.get<boolean>("discount", false);
// Or access the entire value object directly
const value = config.value;
Getting a 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.
// Or, via individual experiments
const titleExp = statsig.getExperiment(user, "new_user_promo_title");
const priceExp = statsig.getExperiment(user, "new_user_promo_price");
const experimentTitle = titleExp.get("title", "Welcome to Statsig!");
const experimentDiscount = priceExp.get<number>("discount", 0.1);
// Get values via Layer
const layer = statsig.getLayer(user, "user_promo_experiments");
const title = layer.get("title", "Welcome to Statsig!");
const discount = layer.get<number>("discount", 0.1);
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 and specify the user and event name to log; you additionally provide some value and/or an object of metadata to be logged together with the event:
statsig.logEvent(
user,
"add_to_cart",
{
price: "9.99",
item_name: "diet_coke_48_pack"
}
);
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
Retrieving Feature Gate Metadata
In certain scenarios, you may need more information about a gate evaluation than just a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object:
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 = Statsig.checkGate(aUser, 'a_gate_name', {disableExposureLogging: true});
Later, if you would like to expose this gate, you can call the following.
Statsig.manuallyLogGateExposure(aUser, 'a_gate_name');
To get a dynamic config without an exposure being logged, call the following.
const config = Statsig.getDynamicConfig(aUser, 'a_dynamic_config_name', {disableExposureLogging: true});
Later, if you would like to expose the dynamic config, you can call the following.
Statsig.manuallyLogDynamicConfigExposure(aUser, 'a_dynamic_config_name');
To get an experiment without an exposure being logged, call the following.
const experiment = Statsig.getExperiment(aUser, 'an_experiment_name', {disableExposureLogging: true});
Later, if you would like to expose the experiment, you can call the following.
Statsig.manuallyLogExperimentExposure(aUser, 'an_experiment_name');
To get a layer parameter without an exposure being logged, call the following.
const layer = Statsig.getLayer(aUser, 'a_layer_name', {disableExposureLogging: 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.
Statsig.manuallyLogLayerParameterExposure(aUser, 'a_layer_name', 'a_param_name');
Statsig User
When calling APIs that require a user, you should pass as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and correctly measure impact of your experiments on your metrics/events. The userID
field is required because it's needed to provide a consistent experience for a given user (click here to understand further why it's important to always provide a userID).
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.
Note that while typing is lenient on the StatsigUser
object to allow you to pass in numbers, strings, arrays, objects, and potentially even enums or classes, the evaluation operators will only be able to operate on primitive types - mostly strings and numbers. While we attempt to smartly cast custom field types to match the operator, we cannot guarantee evaluation results for other types. For example, setting an array as a custom field will only ever be compared as a string - there is no operator to match a value in that array.
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!
Statsig Options
StatsigOptions Class
The StatsigOptions
class is used to specify optional parameters when initializing the Statsig client.
Parameters
-
environment
:Optional<string>
Environment parameter for evaluation. -
specsUrl
:Optional<string>
Custom URL for fetching feature specifications. -
specsSyncIntervalMs
:Optional<number>
How often the SDK updates specifications from Statsig servers (in milliseconds). -
fallbackToStatsig
:Optional<bool>
Default off. Turn this one on if you are proxying download_config_specs / get_id_lists endpoint and wish to fallback to statsig default endpoint to increase reliability. -
logEventUrl
:Optional<string>
Custom URL for logging events. -
disableAllLogging
:Optional<bool>
Default off. If turned on, SDK will not collect any loggings within the sessions, including custom events and config check exposure events. -
enableIDLists
:Optional<bool>
By default off. You need to turn this on if you are using legacy Big ID Lists. -
eventLoggingFlushIntervalMs
:Optional<number>
How often events are flushed to Statsig servers (in milliseconds). -
eventLoggingMaxQueueSize
:Optional<number>
Maximum number of events to queue before forcing a flush. -
dataStore
:Optional<DataStore>
An adapter with custom storage behavior for config specs.Can also be used to continuously fetch updates in place of the Statsig network. See Data Stores.
For example, see our 1P implementation via Redis statsig-node-redis.
-
specsAdapterConfig
:Optional<SpecAdapterConfig>
More advanced settings to config SDK to fetch from different sources: for example, statsig forward proxy, your own proxy server, data store. Or using different network protocol, http vs grpc streaming. -
observabilityClient
:Optional<ObservabilityClient>
Interface for you to integrate observability metrics exposed by SDK, including, config propagation delay, initialization time spent. See details
// Example usage:
const options = new StatsigOptions();
options.environment = "staging";
options.initTimeoutMs = 3000;
const statsig = new Statsig("secret-key", options);
await statsig.initialize();
Shutting Statsig Down
Because we batch and periodically flush events, some events may not have been sent when your app/server shuts down.
To make sure all logged events are properly flushed, you should tell Statsig to shutdown when your app/server is closing:
await statsig.shutdown();
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments