Skip to main content

Node Server SDK

Installation

npm i @statsig/statsig-node-core

The node SDK is pre-built and compiled for different OSs & CPU architectures. Package managers will resolve the correct version automatically.

Frozen lockfile/locked dependencies

If your service has locked dependencies with package-lock.json or pnpm-lock.yml, you'll need to include all versions you need. For example, if you develop locally on macOS, and deploy to linux, then you have to include:

dependencies {
"statsig/statsig-node-core-darwin-arm64": "0.1.0" // for macOS
"statsig/statsig-node-core-linux-x64-gnu": "0.1.0" // for linux x64 machines
}

Using statsig-node-core with Next.js

statsig-node-core works well with Next, but can't be packaged with webpack. To prevent errors, designate @statsig/statsig-node-core as a serverExternalPackage in your next.config.js file:

const nextConfig = {
serverExternalPackages: ['@statsig/statsig-node-core'],
}

Initialize the SDK

After installation, you will need to initialize the SDK using a Server Secret Key from the statsig console.

info

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.

There is also an optional parameter named 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: StatsigOptions = { 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",
null,
{
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:

const gate = statsig.getFeatureGate(statsigUser, "example_gate")
console.log(gate.rule_id)
console.log(gate.value)

Manual Exposures

warning

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.

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');

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. At least one ID (userID or customID) is required because it's needed to provide a consistent experience for a given user (click here)

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

Previous Statsig SDKs enabled country and user agent parsing by default, but our new class of SDKs require you to opt-in by setting StatsigOptions.enable_country_lookup and StatsigOptions.enable_user_agent_parsing. Providing parsed fields yourself is often advantageous for consistency and speed.

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>
    Default off. You need to turn this on if you are using legacy Big ID Lists.

  • enableUserAgentParsing Optional<bool> Default off. When enabled, the SDK will attempt to parse UserAgents (attached to the user object) into browserName, browserVersion, systemName, systemVersion, and appVersion at evaluation time, when needed for evaluation.

  • enableCountryLookup Optional<bool> Default off. When enabled, the SDK will attempt to parse IP addresses (attached to the user object) into Country codes at evaluation time, when needed for evaluation.

  • 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();

Local Overrides

To override the return value of a gate/config/experiment/layer locally, we expose a set of override APIs. Coupling this with StatsigOptions.disable_network can be helpful when writing unit tests.

// Overrides the given gate to the specified value
statsig.override_gate("a_gate_name", true);

// Overrides the given dynamic config to the provided value
statsig.override_dynamic_config("a_config_name", { "key": "value" });

// Overrides the given experiment to the provided value
statsig.override_experiment("an_experiment_name", { "key": "value" });

// Overrides the given layer to the provided value
statsig.override_layer("a_layer_name", { "key": "value" });
note
  1. These only apply locally - they do not update definitions in the Statsig console or elsewhere.
  2. The local override API is not designed to be a full mock. They are only a convenient way to override the value of the gate/config/etc.

FAQ

How do I run experiments for logged out users?

See the guide on device level experiments

Common Problems while installing

  1. Seeing SSL Error Right now the binary files will look at certain versions of SSL.
// Try run this
apt-get update && apt-get install libcurl4-openssl-dev -y && rm -rf /var/lib/apt/lists/*