Skip to main content
Migrating from the Legacy Node SDK? See our Migration Guide.

Setup the SDK

1

Install the SDK

The Node SDK is pre-built and compiled for different OSs & CPU architectures. Package managers will resolve the correct version automatically.
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:
statsig-node-core uses native binary files that can’t be packaged with webpack/esbuild. To prevent errors, take the following steps:
In your next.config.js file, add the @statsig/statsig-node-core package to the serverExternalPackages array:
2

Initialize the SDK

After installation, you will need to initialize the SDK using a Server Secret Key from the Statsig console.
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
There is also an optional parameter named options that allows you to pass in a StatsigOptions to customize the SDK.
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:

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 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 a Layer/Experiment

Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but often recommend the use of layers, which make parameters reusable and let you run mutually exclusive experiments.

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:

Parameter Stores

Sometimes you don’t know whether you want a value to be a Feature Gate, Experiment, or Dynamic Config yet. If you want on-the-fly control of that outside of your deployment cycle, you can use Parameter Stores to define a parameter that can be changed into at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application can prove very useful for future flexibility and can even allow non-technical Statsig users to turn parameters into experiments.

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:
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.

Sending Events to Log Explorer

You can forward logs to Logs Explorer for convenient analysis using the Forward Log Line Event API. This lets you include custom metadata and event values with each log.

Using Shared Instance

In some applications, you may want to create a single Statsig instance that can be accessed globally throughout your codebase. The shared instance functionality provides a singleton pattern for this purpose:
The shared instance functionality provides a singleton pattern where a single Statsig instance can be created and accessed globally throughout your application. This is useful for applications that need to access Statsig functionality from multiple parts of the codebase without having to pass around a Statsig instance.
  • Statsig.newShared(sdkKey, options): Creates a new shared instance of Statsig that can be accessed globally
  • Statsig.shared(): Returns the shared instance
  • Statsig.hasSharedInstance(): Checks if a shared instance exists (useful when you aren’t sure if the shared instance is ready yet)
  • Statsig.removeShared(): Removes the shared instance (useful when you want to switch to a new shared instance)
hasSharedInstance() and removeShared() are helpful in specific scenarios but aren’t required in most use cases where the shared instance is set up near the top of your application.Also note that only one shared instance can exist at a time. Attempting to create a second shared instance will result in an error.

Manual Exposures

By default, the SDK will automatically log an exposure event when you check a gate, get a config, get an experiment, or call get() on a parameter in a layer. However, there are times when you may want to log an exposure event manually. For example, if you’re using a gate to control access to a feature, but you don’t want to log an exposure until the user actually uses the feature, you can use manual exposures. All of the main SDK functions (checkGate, getDynamicConfig, getExperiment, getLayer) accept an optional disableExposureLogging parameter. When this is set to true, the SDK will not automatically log an exposure event. You can then manually log the exposure at a later time using the corresponding manual exposure logging method:

Statsig User

The StatsigUser object represents a user in Statsig. You must provide a userID or at least one of the customIDs to identify the 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.

Private Attributes

Private attributes are user attributes that are used for evaluation but are not forwarded to any integrations. They are useful for PII or sensitive data that you don’t want to send to third-party services.

Statsig Options

You can pass in an optional parameter options in addition to sdkKey during initialization to customize the Statsig client. Here are the available options that you can configure.

Parameters

string
Environment parameter for evaluation.
string
Custom URL for fetching feature specifications.
number
How often the SDK updates specifications from Statsig servers (in milliseconds).
boolean
default:"false"
Turn this on if you are proxying download_config_specs / get_id_lists and want to fall back to the default Statsig endpoint to increase reliability.
string
Custom URL for logging events.
boolean
default:"false"
If true, the SDK will not collect any logging within the session, including custom events and config check exposure events.
boolean
default:"false"
Required to be true when using segments with more than 1000 IDs. See ID List segments.
boolean
default:"false"
If true, the SDK will not parse User-Agent strings into browserName, browserVersion, systemName, systemVersion, and appVersion when needed for evaluation.
boolean
default:"false"
When true, the SDK waits until user agent parsing data is fully loaded during initialization (~1 second), ensuring parsing is ready before any evaluations.
boolean
default:"false"
If true, the SDK will not parse IP addresses (from user.ip) into country codes when needed for evaluation.
boolean
default:"false"
When true, the SDK waits for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization (~1 second), ensuring IP-to-country parsing is ready at evaluation time.
number
How often events are flushed to Statsig servers (in milliseconds).
number
Maximum number of events to queue before forcing a flush.
DataStore
An adapter with custom storage behavior for config specs. Can also continuously fetch updates in place of the Statsig network. See Data Stores. For example, see our 1P Redis implementation statsig-node-redis.
SpecAdapterConfig
Advanced settings to fetch from different sources (e.g., statsig forward proxy, your own proxy server, data store) or to use different network protocols (HTTP vs gRPC streaming).
ObservabilityClient
Interface to integrate observability metrics exposed by the SDK (e.g., config propagation delay, initialization time). See details.
PersistentStorage
Interface to use persistent storage within the SDK. See details.
ProxyConfig
Configuration for connecting through a proxy server.
string
Proxy server host.
number
Proxy server port.
string
Proxy authentication in the form “username:password”.
string
Protocol (e.g., “http”, “https”).

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 call shutdown() before your app/server shuts down:

Client SDK Bootstrapping | SSR

If you are using the Statsig client SDK in a browser or mobile app, you can bootstrap the client SDK with the values from the server SDK to avoid a network request on the client. This is useful for server-side rendering (SSR) or when you want to reduce the number of network requests on the client.

Client Initialize Response

The Node Core SDK provides a method to generate a client initialize response that can be used to bootstrap client SDKs without requiring network requests.
The getClientInitializeResponse method accepts an optional options parameter with the following properties:
The hashAlgorithm option specifies which algorithm to use for hashing gate and experiment names in the client initialize response. The default is 'djb2' for better performance and smaller payload size.
The clientSdkKey option lets you filter the response to only the specific feature gates, experiments, dynamic configs, layers, or parameter stores that a particular client key has access to - effectively letting you apply target apps.
The filter options allow you to reduce the payload size by only including specific feature gates, experiments, dynamic configs, layers, or parameter stores in the response.
The includeLocalOverrides option determines whether to consider local overrides you’ve set when evaluating each config in the response.
Below is a complete example of using the client initialize response to bootstrap a client SDK. Note that you may choose to parallelize or inline the initialize response data with other requests to your server, to eliminate additional requests and latency.

SDK Event Subscriptions

The Statsig SDK provides an event subscription system that allows you to listen for evaluation events in real-time. This feature is useful for debugging, analytics, custom logging, and integrating with external systems.

Supported Events

The SDK supports subscribing to the following evaluation events:
  • gate_evaluated - Fired when a feature gate is evaluated for a user
  • dynamic_config_evaluated - Fired when a dynamic config is retrieved for a user
  • experiment_evaluated - Fired when an experiment is evaluated for a user
  • layer_evaluated - Fired when a layer is evaluated for a user
  • "*" - Subscribe to all evaluation events

SDK Event Data

Each event includes relevant context about the evaluation:
  • Gate Evaluated Events include: gate_name, value (boolean), rule_id, reason
  • Dynamic Config Events include: the full dynamic_config object with values and metadata
  • Experiment Events include: the full experiment object with variant assignment and parameters
  • Layer Events include: the full layer object with allocated experiment and parameters

Use Cases

Event subscriptions are particularly useful for:
  • Debugging: Monitor which features are being evaluated and their results
  • Analytics: Track feature usage patterns and user segments
  • Custom Logging: Send evaluation data to your own logging systems
  • Integration: Forward events to external analytics or monitoring tools
  • Testing: Verify that features are being evaluated as expected

Best Practices

  • Clean up subscriptions: Always unsubscribe when you no longer need to listen for events to prevent memory leaks
  • Handle event data carefully: Event objects may contain sensitive user information depending on your configuration
  • Use specific event types: Subscribe to specific events rather than ”*” when possible for better performance
  • Avoid heavy processing: Keep event handlers lightweight to avoid impacting SDK performance

Local Overrides

Local Overrides are a way to override the values of gates, configs, experiments, and layers for testing purposes. This is useful for local development or testing scenarios where you want to force a specific value without having to change the configuration in the Statsig console.

Persistent Storage

The Persistent Storage interface allows you to implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups even when the user returns later. This is particularly useful for client-side A/B testing where you want to ensure users always see the same variant.
PersistentStorageInterface.ts

Usage Example

PersistentStorageUsage.ts
Persistent storage support was added in version 0.6.1 of the Node.js SDK.

Data Store

The Data Store interface allows you to implement custom storage for Statsig configurations. This enables advanced caching strategies and integration with your preferred storage systems.
For example, see our 1P implementation via Redis statsig-node-redis.

Custom Output Logger

The Output Logger interface allows you to customize how the SDK logs messages. This enables integration with your own logging system and control over log verbosity.

Implementation Example

  • All methods in the OutputLoggerProvider interface are optional
  • The tag parameter indicates the SDK component or category generating the log message
  • Use outputLogLevel in StatsigOptions to control which log levels are actually called
  • The logger is automatically initialized when the Statsig client initializes and shut down when the client shuts down

Observability Client

The Observability Client interface allows you to monitor the health of the SDK by integrating with your own observability systems. This enables tracking metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, see the Monitoring documentation.

FAQs

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.
  1. Docker build failing with platform-specific dependencies
When building in Docker (Linux environment), the build may fail if your local package-lock.json or yarn.lock contains platform-specific dependencies for macOS. This happens because npm install locally on Mac pulls down Apple-specific variants, but Docker tries to use those same locked dependencies on Linux. Solution: Either install the Linux-specific variant during your Docker build step:
Or add both platform variants as dependencies in your package.json:

Reference

  • checkGate(user: StatsigUser, gateName: string, options?: EvaluationOptions): boolean
  • getDynamicConfig(user: StatsigUser, configName: string, options?: EvaluationOptions): DynamicConfig
  • getExperiment(user: StatsigUser, experimentName: string, options?: EvaluationOptions): DynamicConfig
  • getLayer(user: StatsigUser, layerName: string, options?: EvaluationOptions): Layer
  • getFeatureGate(user: StatsigUser, gateName: string, options?: EvaluationOptions): FeatureGate
  • getParameterStore(user: StatsigUser, parameterStoreName: string, options?: EvaluationOptions): ParameterStore
  • getPrompt(user: StatsigUser, promptName: string, options?: EvaluationOptions): Prompt
  • getPromptSet(user: StatsigUser, promptSetName: string, options?: EvaluationOptions): PromptSet
  • logEvent(user: StatsigUser, eventName: string, value?: string | number | null, metadata?: Record<string, string>): void
  • forwardLogLineEvent(user: StatsigUser, level: string, message: string, metadata?: Record<string, string>): void
  • manuallyLogGateExposure(user: StatsigUser, gateName: string): void
  • manuallyLogDynamicConfigExposure(user: StatsigUser, configName: string): void
  • manuallyLogExperimentExposure(user: StatsigUser, experimentName: string): void
  • manuallyLogLayerParameterExposure(user: StatsigUser, layerName: string, parameterName: string): void
  • getClientInitializeResponse(user: StatsigUser, options?: ClientInitializeResponseOptions): ClientInitializeResponse
  • shutdown(): Promise<void>
The following methods return information about which user fields are needed for evaluation:
  • getGateFieldsNeeded(gateName: string): string[]
  • getDynamicConfigFieldsNeeded(configName: string): string[]
  • getExperimentFieldsNeeded(experimentName: string): string[]
  • getLayerFieldsNeeded(layerName: string): string[]
These methods return an array of strings representing the user fields that are required to properly evaluate the specified gate, config, experiment, or layer. This can be useful for:
  • Optimizing user object creation by only including necessary fields
  • Understanding which user attributes affect a particular feature
  • Debugging evaluation issues