Skip to main content

Client-side feature gating

Step 1: Get the Statsig client SDK key#

To get the Statsig client SDK key,

  • Log into the Statsig console at https://console.statsig.com

  • Click on the Project Settings gear icon next to your account settings at the top right corner of the page as shown below

    image

  • Click on the API Keys tab

  • Copy the active Client API Key

Step 2: Install the SDK#

You can install the statsig SDK via npm or yarn:

Install using npm or yarn:

npm install statsig-js
yarn add statsig-js

You can also use jsdelivr, an open source CDN that we use on www.statsig.com. To access the current primary JavaScript bundle, include the following in your client application:

https://cdn.jsdelivr.net/npm/statsig-js/dist/statsig-prod-web-sdk.min.js

To access specific versions and files, use the following format:

http://cdn.jsdelivr.net/npm/statsig-js@{version}/{file}

Step 3: Initialize the SDK#

To initialize the SDK, copy the following in your client application:

const statsig = require('statsig-js');
await statsig.initialize(
'<CLIENT_SDK_KEY>',
{ userID: '<LOGGED_IN_USER_ID>' },
{ environment: { tier: 'staging' } }, // optional, pass options here if needed
);
You must provide a user ID at a minimum to initialize the SDK. Statsig also provides built-in user attributes such as email, IP address, user agent, country, locale, and client version that you can also pass as part of a user object to create targeting rules based on any of these dimensions.
const user = {
userID: <LOGGED_IN_USER_ID>,
ip: currentIP,
custom: {
new_user: true,
level: 2
}
};
await statsig.initialize('<CLIENT_SDK_KEY>', user);

Step 4: Check the feature gate#

To implement a feature gate, you must include a feature gate check in your application code.

A feature gate check returns a Boolean value. A feature gate is closed/off and a gate check returns false by default. After you have created a rule to target a set of users, the feature gate check returns true when you perform a check for an eligible user. You can use this return value to expose the eligible user to the feature as shown below.

if (statsig.checkGate('<FEATURE_GATE_NAME>')) {
// Gate is on, show new home page
} else {
// Gate is off, show old home page
}

Step 5 (Optional): Log an event#

You can optionally log an event to capture any metrics that show the impact of your feature.

statsig.logEvent('<EVENT_NAME>', '<EVENT_VALUE>', {'price': '<KEY>', 'item_name': '<VALUE>'});