Experiment Node.js SDK
Official documentation for Amplitude Experiment's server-side Node.js SDK implementation.
SDK Resources
This documentation has separate sections for remote and local evaluation:
Remote evaluation¶
Implements fetching variants for a user via remote evaluation.
Install¶
Node version compatibility
The Node Server SDK works with Node 10+.
Install the Node.js Server SDK with npm or yarn.
npm install --save @amplitude/experiment-node-server
yarn add @amplitude/experiment-node-server
Quick Start
import { Experiment } from '@amplitude/experiment-node-server';
// (1) Initialize the experiment client
const experiment = Experiment.initializeRemote('<DEPLOYMENT_KEY>', config: {
fetchTimeoutMillis: 500,
fetchRetries: 1,
fetchRetryBackoffMinMillis: 0,
fetchRetryTimeoutMillis: 500,
});
// (2) Fetch variants for a user
const user = {
user_id: 'user@company.com',
device_id: 'abcdefg',
user_properties: {
'premium': true,
},
};
const variants = await experiment.fetch(user);
// (3) Access a flag's variant
const variant = variants['YOUR-FLAG-KEY'];
if (variant?.value === 'on') {
// Flag is on
} else {
// Flag is off
}
Not getting the expected variant result for your flag? Make sure your flag is activated, has a deployment set, and has users allocated.
Initialize remote¶
The SDK client should be initialized in your server on startup. The deployment key argument passed into the apiKey
parameter must live within the same project that you are sending analytics events to.
initializeRemote(apiKey: string, config?: RemoteEvaluationConfig): RemoteEvaluationClient
Parameter | Requirement | Description |
---|---|---|
apiKey |
required | The deployment key which authorizes fetch requests and determines which flags should be evaluated for the user. |
config |
optional | The client configuration used to customize SDK client behavior. |
Timeout & Retry Configuration
The default timeout and retry configuration options are too high for most server environments. Configure the timeout and retry options to best fit your performance requirements. If remote evaluation performance is too slow, consider using local evaluation.
import { Experiment } from '@amplitude/experiment-node-server';
const experiment = Experiment.initializeRemote('<DEPLOYMENT_KEY>', config: {
fetchTimeoutMillis: 500,
fetchRetries: 1,
fetchRetryBackoffMinMillis: 0,
fetchRetryTimeoutMillis: 500,
});
Configuration¶
The SDK client can be configured on initialization.
Configuration Options
Name |
Description | Default Value |
---|---|---|
debug |
Enable additional debug logging. | false |
serverUrl |
The host to fetch variants from. | https://api.lab.amplitude.com |
fetchTimeoutMillis |
The timeout for fetching variants in milliseconds. This timeout only applies to the initial request, not subsequent retries | 10000 |
fetchRetries |
The number of retries to attempt if a request to fetch variants fails. | 8 |
fetchRetryBackoffMinMillis |
The minimum (initial) backoff after a request to fetch variants fails. This delay is scaled by the fetchRetryBackoffScalar |
500 |
fetchRetryBackoffMaxMillis |
The maximum backoff between retries. If the scaled backoff becomes greater than the max, the max is used for all subsequent requests | 10000 |
fetchRetryBackoffScalar |
Scales the minimum backoff exponentially. | 1.5 |
fetchRetryTimeoutMillis |
The request timeout for retrying variant fetches. | 10000 |
EU Data Center
If you're using Amplitude's EU data center, configure the serverUrl
option on initialization to https://api.lab.eu.amplitude.com
Fetch¶
Fetches variants for a user and returns the results. This function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.
fetch(user: ExperimentUser): Promise<Variants>
Parameter | Requirement | Description |
---|---|---|
user |
required | The user to remote fetch variants for. |
const user = {
user_id: 'user@company.com',
device_id: 'abcdefg',
user_properties: {
'premium': true,
},
};
const variants = await experiment.fetch(user);
After fetching variants for a user, you may to access the variant for a specific flag.
const variant = variants['YOUR-FLAG-KEY'];
if (variant?.value === 'on') {
// Flag is on
} else {
// Flag is off
}
Local evaluation¶
Implements evaluating variants for a user via local evaluation. If you plan on using local evaluation, you should understand the tradeoffs.
Local Evaluation Mode
The local evaluation client can only evaluation flags which are set to local evaluation mode.
Install¶
Install the Node.js Server SDK with npm
or yarn
.
$ npm install --save @amplitude/experiment-node-server
$ yarn add @amplitude/experiment-node-server
Quick Start
import { Experiment } from '@amplitude/experiment-node-server';
// (1) Initialize the local evaluation client with a server deployment key.
const experiment = Experiment.initializeLocal('<DEPLOYMENT_KEY>');
// (2) Start the local evaluation client.
await experiment.start();
// (2) Evaluate a user.
const user = { device_id: 'abcdefg' };
const variants = await experiment.evaluate(user);
Not getting the expected variant result for your flag? Make sure your flag is activated, has a deployment set, and has users allocated.
Initialize Local¶
Initializes a local evaluation client.
Server Deployment Key
You must initialize the local evaluation client with a server deployment key to get access to local evaluation flag configs.
initializeLocal(apiKey: string, config?: LocalEvaluationConfig): LocalEvaluationClient
Parameter | Requirement | Description |
---|---|---|
apiKey |
required | The server deployment key which authorizes fetch requests and determines which flags should be evaluated for the user. |
config |
optional | The client configuration used to customize SDK client behavior. |
Flag Polling Interval
Use the flagConfigPollingIntervalMillis
configuration to determine the time flag configs take to update once modified (default 30s).
Configuration¶
You can configure the SDK client on initialization.
Configuration Options
LocalEvaluationConfig
Name |
Description | Default Value |
---|---|---|
debug |
Set to true to enable debug logging. |
false |
serverUrl |
The host to fetch flag configurations from. | https://api.lab.amplitude.com |
bootstrap |
Bootstrap the client with a map of flag key to flag configuration | {} |
flagConfigPollingIntervalMillis |
The interval (in milliseconds) to poll for updated flag configs after calling start() |
30000 |
assignmentConfig |
Configuration for automatically tracking assignment events after an evaluation. | null |
AssignmentConfig
Name |
Description | Default Value |
---|---|---|
apiKey |
The analytics API key and NOT the experiment deployment key | required |
cacheCapacity |
The maximum number of assignments stored in the assignment cache | 65536 |
Analytics SDK Options | Options to configure the underlying Amplitude Analytics SDK used to track assignment events |
EU Data Center
If you're using Amplitude's EU data center, configure the serverUrl
option on initialization to https://api.lab.eu.amplitude.com
Start¶
Start the local evaluation client, pre-fetching local evaluation mode flag configs for evaluation and starting the flag config poller at the configured interval.
start(): Promise<void>
You should await the result of start()
to ensure that flag configs are ready to be used before calling evaluate()
await experiment.start();
Evaluate¶
Executes the evaluation logic using the flags pre-fetched on start()
. You must give evaluate a user object argument. You can optionally pass an array of flag keys if you require only a specific subset of required flag variants.
Automatic Assignment Tracking
Set assignmentConfig
to automatically track an assignment event to Amplitude when evaluate()
is called.
evaluate(user: ExperimentUser, flagKeys?: string[]): Promise<Variants>
Parameter | Requirement | Description |
---|---|---|
user |
required | The user to evaluate. |
flagKeys |
optional | Specific flags or experiments to evaluate. If undefined, null, or empty, all flags and experiments are evaluated. |
// The user to evaluate
const user = { device_id: 'abcdefg' };
// Evaluate all flag variants
const allVariants = await experiment.evaluate(user);
// Evaluate a specific subset of flag variants
const specificVariants = await experiment.evaluate(user, [
'my-local-flag-1',
'my-local-flag-2',
]);
Access Amplitude cookies¶
If you're using the Amplitude Analytics SDK on the client-side, the Node.js server SDK provides an AmplitudeCookie
class with convenience functions for parsing and interacting with the Amplitude identity cookie. This is useful for ensuring that the Device ID on the server matches the Device ID set on the client, especially if the client hasn't yet generated a Device ID.
import { AmplitudeCookie } from '@amplitude/experiment-node-server';
app.use((req, res, next) => {
const { query, cookies, url, path, ip, host } = req
// grab amp device id if present
const ampCookieName = AmplitudeCookie.cookieName('amplitude-api-key');
let deviceId = null;
if (cookies[ampCookieName]) {
deviceId = AmplitudeCookie.parse(cookies[ampCookieName]).device_id;
}
if (!deviceId) {
// deviceId doesn't exist, set the Amplitude Cookie
deviceId = random22CharBase64String();
const ampCookieValue = AmplitudeCookie.generate(deviceId);
res.cookie(ampCookieName, ampCookieValue, {
domain: '.your-domain.com', // this should be the same domain used by the Amplitude JS SDK
maxAge: 365 * 24 * 60 * 60 * 1000, // this is currently the same as the default in the Amplitude JS SDK, can be modified
sameSite: 'Lax'
});
}
next()
});