Setup the SDK
1
Install the SDK
Frozen Lockfile Setup
Frozen Lockfile Setup
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:
Usage with Next.js
Usage 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:
2
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the Statsig console.There is also an optional parameter named
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
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 (thinkreturn 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: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:Statsig.newShared(sdkKey, options)
: Creates a new shared instance of Statsig that can be accessed globallyStatsig.shared()
: Returns the shared instanceStatsig.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 get 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:
- Feature Gates
- Dynamic Configs
- Experiments
- Layers
Statsig User
TheStatsigUser
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 parameteroptions
in addition to sdkKey
during initialization to customize the Statsig client. Here are the available options that you can configure.
StatsigOptions
StatsigOptions
Parameters
Environment parameter for evaluation.
Custom URL for fetching feature specifications.
How often the SDK updates specifications from Statsig servers (in milliseconds).
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.Custom URL for logging events.
If true, the SDK will not collect any logging within the session, including custom events and config check exposure events.
Required to be
true
when using segments with more than 1000 IDs. See ID List segments.If true, the SDK will not parse User-Agent strings into
browserName
, browserVersion
, systemName
, systemVersion
, and appVersion
when needed for evaluation.When true, the SDK waits until user agent parsing data is fully loaded during initialization (~1 second), ensuring parsing is ready before any evaluations.
If true, the SDK will not parse IP addresses (from
user.ip
) into country codes when needed for evaluation.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.
How often events are flushed to Statsig servers (in milliseconds).
Maximum number of events to queue before forcing a flush.
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.
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).
Interface to integrate observability metrics exposed by the SDK (e.g., config propagation delay, initialization time). See details.
Configuration for connecting through a proxy server.
ProxyConfig
ProxyConfig
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 callshutdown()
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.Initialize Response Options
Initialize Response Options
The
getClientInitializeResponse
method accepts an optional options
parameter with the following properties:Hash Algorithm
Hash Algorithm
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.Client SDK Key
Client SDK Key
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.Filtering
Filtering
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.
Local Overrides
Local Overrides
The
includeLocalOverrides
option determines whether to consider local overrides you’ve set when evaluating each config in the response.Full Code Example
Full Code Example
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 userdynamic_config_evaluated
- Fired when a dynamic config is retrieved for a userexperiment_evaluated
- Fired when an experiment is evaluated for a userlayer_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.- Feature Gates
- Dynamic Configs
- Experiments
- Layers
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.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.Logger Interface
Logger Interface
Implementation Example
Implementation Example
Implementation Example
Usage with StatsigOptions
Usage with StatsigOptions
Notes
Notes
- 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
- Seeing SSL Error
- Docker build failing with platform-specific dependencies
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:
package.json
:
Reference
All API Methods
All API Methods
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>
Fields Needed Methods
Fields Needed Methods
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[]
- Optimizing user object creation by only including necessary fields
- Understanding which user attributes affect a particular feature
- Debugging evaluation issues