Statsig Node.js SDK
The Statsig Node.js SDK (current stable version 6.5.1) provides robust tools for managing feature gates, dynamic configurations, and A/B testing within multi-user server environments. It enables developers to implement continuous deployment strategies and understand the impact of new features on key performance indicators. The package sees frequent updates, typically releasing bug fixes and minor improvements multiple times a month, as evidenced by recent changelogs. Key differentiators include its comprehensive A/B testing capabilities, detailed analytics, and a focus on server-side performance and data consistency, contrasting with client-side SDKs that handle single-user contexts. It is designed for use cases where server-side evaluation of features is critical for performance and security.
Common errors
-
Error: Statsig.initialize must be called first.
cause Attempted to use `Statsig.checkGate`, `getConfig`, or `logEvent` before `Statsig.initialize` has completed.fixEnsure `await Statsig.initialize('YOUR_SECRET_KEY');` is called and awaited at the start of your application before any other Statsig SDK methods are invoked. -
TypeError: Statsig is not a constructor
cause Attempting to import Statsig using CommonJS `require` syntax when the package is primarily designed for ES Modules or when using `new Statsig()` instead of directly calling methods on the imported `Statsig` object.fixUse ES module `import { Statsig } from 'statsig-node';` syntax. If using CommonJS, ensure your environment and build tools correctly transpile or interpret named exports, or use `const Statsig = require('statsig-node').Statsig;` if available, though direct named imports are preferred. -
Error: Invalid Statsig secret key provided.
cause The secret key passed to `Statsig.initialize` is incorrect, malformed, or empty.fixVerify that `YOUR_STATSIG_SERVER_SECRET_KEY` is a valid Statsig server secret key (starting with `secret-`) obtained from your Statsig console, and that no leading/trailing whitespace is present. -
TypeError: fetch is not a function
cause The SDK relies on the `fetch` API, which might not be globally available in some older Node.js environments or specific serverless runtimes without polyfills.fixEnsure your Node.js environment is v18+ (where `fetch` is native) or provide a global `fetch` polyfill (e.g., `node-fetch`) if running on older Node.js versions or restricted environments.
Warnings
- breaking Timestamp evaluation for conditions was previously inconsistent, expecting milliseconds but potentially receiving seconds. This was fixed in v6.5.1.
- gotcha Earlier versions (pre-6.4.7) of the SDK had potential memory leaks due to data not being cleaned up regularly in `StatsigFetcher`.
- breaking A security vulnerability was identified in the `sha.js` dependency, which `statsig-node` uses for cryptographic operations. This was patched by upgrading `sha.js` to version 2.4.12.
- gotcha Versions prior to 6.4.3 had build issues or runtime errors in environments lacking native `AbortSignal` support, affecting fetch operations.
- gotcha When initialization failed in versions prior to 6.4.5, the secret key might have been logged unmasked in network logs, posing a security risk.
Install
-
npm install statsig-node -
yarn add statsig-node -
pnpm add statsig-node
Imports
- Statsig
const Statsig = require('statsig-node');import { Statsig } from 'statsig-node'; - StatsigUser
import StatsigUser from 'statsig-node';
import { StatsigUser } from 'statsig-node'; - initialize
Statsig.initialize('YOUR_SECRET_KEY');await Statsig.initialize('YOUR_SECRET_KEY');
Quickstart
import { Statsig, StatsigUser } from 'statsig-node';
const STATSIG_SECRET_KEY = process.env.STATSIG_SERVER_SECRET_KEY ?? '';
async function runStatsigExample() {
if (!STATSIG_SECRET_KEY) {
console.error('STATSIG_SERVER_SECRET_KEY environment variable is not set.');
return;
}
try {
await Statsig.initialize(STATSIG_SECRET_KEY, {
localMode: false, // Set to true for local testing without network calls
// Additional options like 'environment', 'api' can be passed here
});
const user: StatsigUser = {
userID: 'unique-user-id-123',
email: 'test@example.com',
country: 'US',
custom: { membershipTier: 'premium' },
// Additional custom properties can be added
};
if (await Statsig.checkGate(user, 'my_new_feature_gate')) {
console.log('Feature "my_new_feature_gate" is ENABLED for the user!');
} else {
console.log('Feature "my_new_feature_gate" is DISABLED for the user.');
}
const config = await Statsig.getConfig(user, 'product_pricing_config');
console.log('Product pricing level:', config.get('priceLevel', 'standard'));
Statsig.logEvent(user, 'checkout_completed', 99.99, { currency: 'USD', items: 3 });
} catch (error) {
console.error('Statsig initialization or usage failed:', error);
} finally {
await Statsig.shutdown(); // Important to call shutdown for graceful exit and event flushing
}
}
runStatsigExample();