Skip to main content

Node.js Server SDK

Getting Started

The following will outline how to get up and running with Statsig for Node.js.

Create an Account

To work with the SDK, you will need a Statsig account. If you don't yet have an account, you can sign up for a free one here. 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

The Node.js SDK is hosted here. You can install the SDK using NPM or Yarn:

npm install statsig-node

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 exposed it, you can create a new one in Statsig console.

There is also an optional parameter named options that allows you to pass in a StatsigOptions to customize the SDK.
const Statsig = require("statsig-node");

await Statsig.initialize(
"server-secret-key",
{ environment: { tier: "staging" } } // optional, pass options here if needed
);
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 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 = {
userID: '12345',
email: '12345@gmail.com',
...
};

const showNewDesign = Statsig.checkGateSync(user, 'new_homepage_design');
if (showNewDesign) {
// show new design here
} else {
// show old design here
}

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:

const config = await Statsig.getConfig(user, "awesome_product_details");

// The 2nd parameter is the default value to be used in case the given parameter name does not exist on
// the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the
// value has not been cached on the client.
const itemName = config.get("product_name", "Awesome Product v1");
const price = config.get("price", 10.0);
const shouldDiscount = config.get("discount", false);

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.

// Values via getLayer

const layer = await Statsig.getLayer(user, "user_promo_experiments");
const promoTitle = layer.get("title", "Welcome to Statsig!");
const discount = layer.get("discount", 0.1);

// or, via getExperiment

const titleExperiment = await Statsig.getExperiment(user, "new_user_promo_title");
const priceExperiment = await Statsig.getExperiment(user, "new_user_promo_price");

const promoTitle = titleExperiment.get("title", "Welcome to Statsig!");
const discount = priceExperiment.get("discount", 0.1);

...

const price = msrp * (1 - discount);


Asynchronous APIs

We mentioned earlier that after calling initialize most SDK APIs would run synchronously, so why are getConfig and checkGate asynchronous?

The main reason is that older versions of the SDK might not know how to interpret new types of gate conditions. In such cases the SDK will make an asynchronous call to our servers to fetch the result of a check. This can be resolved by upgrading the SDK, and we will warn you if this happens.

For more details, read our blog post about SDK evaluations. If you have any questions, please ask them in our Feedback Repository.

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", "SKU_12345", {
price: "9.99",
item_name: "diet_coke_48_pack",
});

Retrieving Feature Gate Metadata

In certain scenarios, it's beneficial to access detailed information about a feature gate, such as its current state for a specific user or additional contextual data. This can be accomplished effortlessly through the Get Feature Gate API. By providing the necessary user details and the name of the feature gate you're interested in, you can fetch this metadata to inform your application's behavior or for analytical purposes.

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.

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

statsig.initialize() takes an optional parameter options in addition to the secret key that you can provide to customize the Statsig client. Here are the current options and we are always adding more to the list:

  • api: string, default https://statsigapi.net/v1

    • The base url to use for all network requests. Defaults to the statsig API.
  • environment: StatsigEnvironment, default null

    • An object you can use to set environment variables that apply to all of your users in the same session and will be used for targeting purposes.
    • The most common usage is to set the environment tier ('production', 'staging' or 'development'), e.g. { tier: 'staging' }, and have feature gates pass/fail for specific environments.
  • bootstrapValues: string, default null

    • A string that represents all rules for all feature gates, dynamic configs and experiments. It can be provided to bootstrap the Statsig server SDK at initialization in case your server runs into network issue or Statsig server is down temporarily.
  • rulesUpdatedCallback: function, default null

    • A callback function that's called whenever we have an update for the rules; it's called with a JSON string (used as is for bootstrapValues mentioned above) and a timestamp, like below:

      options.rulesUpdatedCallback(specsString, timeStamp)
  • logger: LoggerInterface, default console.log

    • The logger interface to use for printing to stdout/stderr
  • localMode: boolean, default false

    • Pass true to this option to turn on Local Mode for the SDK, which will stop the SDK from issuing any network requests and make it only operate with only local overrides (If supported) and cache.
      Note: Since no network requests will be made, a dummy SDK key starting with "secret-" can be used. (eg "secret-key")
    • Disables all network access, so the SDK will only return default (or overridden) values. Useful in testing.
  • initTimeoutMs: number, default 0

    • Sets a maximum time to wait for the config download network request to resolve before considering the SDK initialized and resolving the call to initialize()
  • dataAdapter: IDataAdapter, default null

    • An adapter with custom storage behavior for config specs. Can be used to bootstrap Statsig server (takes priority over bootstrapValues). Can also be used to continously fetch updates in place of the Statsig network. See Data Stores.
    • For example, see our 1P implementation via Redis statsig-node-redis.
  • rulesetsSyncIntervalMs: number, default 10,000

    • Sets the polling interval for the SDK to ask Statsig backend for changes on the rulesets.
  • idListsSyncIntervalMs: number, default 60,000

    • Sets the polling interval for the SDK to ask Statsig backend for changes on the ID Lists.
  • loggingIntervalMs: number, default 60,000

    • Sets the interval for the SDK to periodically flush all logging events to Statsig backend.
  • loggingMaxBufferSize: number, default 1,000

    • Sets the maximum number of events the SDK's logger will batch before flushing them all to Statsig backend.
  • disableDiagnostics: boolean, default false

    • Disables diagnostics events from being logged and sent to Statsig
  • initStrategyForIP3Country: 'await' | 'lazy' | 'none', default 'await'

    • Method of initializing IP to country lookup on statsig.initialize().
  • initStrategyForIDLists: 'await' | 'lazy' | 'none', default 'await'

    • Method of initializing ID lists on statsig.initialize().
  • postLogsRetryLimit: number, default 5

    • The maximum number of retry attempts when sending /log_event requests to Statsig server
  • postLogsRetryBackoff: number | (retry: number) => number, default 1,000

    • A fixed number or callback on the retry attempt number to configure the time in ms to wait between each /log_event retry.
    • If using a fixed number, a 10x multiplier will be applied on each subsequent retry

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:

statsig.shutdown();
Alternatively, if you are operating in a serverless environment/cloud function, you may wish to leave Statsig running in case your function is recycled but flush the logs to Statsig servers. Or, if you need an async method to wait for logs to post before resolving, you can use:
await Statsig.flush();

Client SDK Bootstrapping | SSR v4.13.0+

The Node server SDK, starting in 4.13.0 supports generating the initializeValues needed to bootstrap a Statsig Client SDK preventing a round trip to Statsig servers. This can also be used with web [statsig-js, statsig-react] SDKs to perform server side rendering (SSR).
const values = Statsig.getClientInitializeResponse(user); // Record<string, unknown> | null

if (values != null) {
// Bootstrap the Statsig React Client SDK
return <StatsigSynchronousProvider initializeValues={values} ... />;
}

Working with IP or UserAgent Values

This will not automatically use the ip, or userAgent for gate evaluation as Statsig servers would, since there is no request from the client SDK specifying these values. If you want to use conditions like IP, or conditions which are inferred from the IP/UA like: Browser Name or Version, OS Name or Version, Country, you must manually set the ip and userAgent field on the user object when calling getClientInitializeResponse.

Working with StableID

There is no auto-generated stableID for device based experimentation, since the server generates the initialize response without any information from the client SDK. If you wish to run a device based experiment while using the server to generate the initialize response, we recommend you:

  1. Create a customID in the Statsig console. See experimenting on custom IDs for more information.
  2. Generate an ID on the server, and set it in a cookie to be used on the client side as well.
  3. Set that ID as the customID on the StatsigUser object when generating the initialize response from the SDK.
  4. Get that ID from the cookie, and set it as the customID on the StatsigUser object when using the client SDK, so all event data and exposure checks tie back to the same user.

Alternatively, if you wish to use the stableID field rather than a custom ID, you still need to do step (2) above. Then:

  • Override the stableID in the client SDK by getting the value from the cookie and setting the overrideStableID parameter in StatsigOptions
  • Set the stableID field on the StatsigUser object in the customIDs map when generating the initialize response from the SDK

Local Overrides v4.8.0+

If you want to locally override gates/configs/experiments/layers, there are a set of override APIs as follows. Coupling this with StatsigOptions.localMode can be useful when writing unit tests.

// Overrides the given gate to the specified value
Statsig.overrideGate("a_gate_name", true, "a_user_id");

// Overrides the given config (dynamic config or experiment) to the provided value
Statsig.overrideConfig("a_config_or_experiment_name", { key: "value" }, "a_user_id");

// Overrides the given layer to the provided value
Statsig.overrideLayer("a_layer_name", { key: "value" }, "a_user_id");

These can be used to set an override for a specific user, or for all users (by not providing a specific user ID). Experiments/Autotune are overridden with the overrideConfig API.

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.

Manual Exposures v5.0.0+

danger

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 5.0.0, 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.checkGateWithExposureLoggingDisabledSync(aUser, 'a_gate_name');

Later, if you would like to expose this gate, you can call the following.

Statsig.manuallyLogGateExposure(aUser, 'a_gate_name');

Environment Specific Setup

Cloudflare

Polling for updates v5.13.0+

The SDK cannot poll for updates accross requests since Cloudflare does not allow for timers**.
To solve for this, a manual sync API is available for independently updating the SDK internal store.

if (env.lastSyncTime < Date.now() - env.syncInterval) {
env.lastSyncTime = Date.now();
context.waitUntil(Statsig.syncConfigSpecs());
}

Flushing events v4.16.0+

The SDK enqueues logged events and flushes them in batches. In order to ensure events are properly flushed, we recommend calling flush using context.waitUntil. This will keep the request handler alive until events are flushed without blocking the response.

context.waitUntil(Statsig.flush());

Node.JS Compatibility v5.16.0+

Many native JavaScript API and Node standard libraries can be accessed in Cloudflare via the nodejs_compat compatibility flag.
The SDK is now compatible with nodejs_compat (since v5.16.0). In older versions, manual polyfilling is required.

FAQ

How do I run experiments for logged out users?

See the guide on device level experiments

How can I use the node SDK for server side rendering?

See Client SDK Bootstrapping | SSR

How can I mock Statsig for testing?

See LocalOverrides

Reference

Type StatsigUser

export type StatsigUser =
// at least one of userID or customIDs must be provided
({ userID: string } | { customIDs: Record<string, string> }) & {
userID?: string;
customIDs?: Record<string, string>;
email?: string;
ip?: string;
userAgent?: string;
country?: string;
locale?: string;
appVersion?: string;
custom?: Record<
string,
string | number | boolean | Array<string> | undefined
>;
privateAttributes?: Record<
string,
string | number | boolean | Array<string> | undefined
> | null;
statsigEnvironment?: StatsigEnvironment;
}

Type StatsigOptions

export type StatsigOptions = {
api: string;
bootstrapValues: string | null;
environment: StatsigEnvironment | null;
rulesUpdatedCallback: RulesUpdatedCallback | null;
localMode: boolean;
initTimeoutMs: number;
dataAdapter: IDataAdapter | null;
rulesetsSyncIntervalMs: number;
idListsSyncIntervalMs: number;
loggingIntervalMs: number;
loggingMaxBufferSize: number;
};

Type StatsigEnvironment

export type StatsigEnvironment = {
tier?: "production" | "staging" | "development";
bootstrapValues: string;
rulesUpdatedCallback: function;
};

DataAdapter

export interface IDataAdapter {
get(key: string): Promise<AdapterResponse>;
set(key: string, value: string, time?: number): Promise<void>;
initialize(): Promise<void>;
shutdown(): Promise<void>;
supportsPollingUpdatesFor(key: DataAdapterKey): boolean;
}