Node
Latest Version: v0.0.2
Updated: 2026-10-29
1. Overview
Starting from AE 6.1, the Experiment Suite supports creating experiments in the AE console and configuring different variable values for control and experiment groups. The Node.js server-side Experiment SDK retrieves these Feature configurations: your application passes the current user identity and Feature Key, the configuration center (RCC) performs remote allocation, and the SDK returns the configuration values and information about the matched experiment. After your application uses the configuration, report an event at the actual point of exposure.
- A Feature Key is the variable identifier configured in the AE console. The examples use checkout_button; replace it with a Key actually published in your project when integrating.
- createClient() only validates and creates the client. It does not access the network or fetch configurations automatically; use client.fetch(request) to make a query.
- Default configuration values from the AE console may still be returned when no experiment is matched. Whether a Feature has a value and whether an experiment is matched are two separate checks.
- The current version supports only remote allocation (REMOTE). LOCAL is reserved and returns INVALID_CONFIG if passed; the result cache and application default values do not perform local allocation.
2. Integration
2.1 Environment and Dependencies
Node.js 12.0.0 or later is required. The SDK is published as CommonJS and provides TypeScript type declarations; the CommonJS examples below work on the minimum supported runtime.
The SDK is published on npm. Install the latest version:
npm install td-feature-node@latest
npm also installs the production dependencies, including the official data collection SDK, thinkingdata-node@1.5.0. Your application does not need TypeScript or other development tools at runtime; installation requires access to the configured npm registry.
2.2 Prerequisites
| Information | Purpose |
|---|---|
| appId | The App ID of the experiment project. Use the value provided by the platform. |
| serverUrl | The base service URL that supports remote decisions and exposure event collection, for example, https://service.example.com. |
| Feature Key | The variable identifier configured and published on the platform. |
| Current User Identity | At least one of accountId and distinctId must be a non-empty string and must meet the allocation subject and audience conditions in the AE console. |
| Custom Request Parameters | The context required by rules in the AE console. Parameter names, types, and meanings must match the configuration in the AE console. |
3. Initialization and Quick Start
3.1 Complete Example
Save this as quickstart.js, replace the App ID, service URL, user identity, and application Key with actual values, and run node quickstart.js. The example uses the default configuration, retrieves all Keys, reads checkout_button, and manually reports exposure after using the result; the SDK creates a data collection instance automatically.
const { createClient, SplitMode } = require('td-feature-node');
// In a long-running service, reuse one Client per process for each project.
const client = createClient({
appId: 'YOUR_APP_ID',
serverUrl: 'https://YOUR_SERVER_URL',
splitMode: SplitMode.REMOTE,
});
async function main() {
try {
const config = await client.fetch({
accountId: 'user_123',
distinctId: 'visitor_456',
// Omit featureKeys to retrieve all configurations visible to the current identity.
});
console.log('All Feature Keys returned by this request:', Object.keys(config.features));
const feature = config.features['checkout_button'];
const buttonStyle = feature ? feature.asString('control') : 'control';
console.log('Button style used:', buttonStyle); // Replace this with your actual application logic.
// Report exposure after actually using the result; the SDK skips it if no valid experiment is matched.
client.expose(feature, { scene: 'checkout' });
} catch (error) {
// If the request fails, use the application default without constructing experiment results or reporting exposure.
console.error('Configuration request failed:', error.code, error.message);
console.log('Button style used: control');
} finally {
// This is a one-off script; long-running services should close the shared Client only when the application exits.
await client.close();
}
}
main().catch(function (error) {
console.error(error);
process.exitCode = 1;
});
Long-running services should reuse a Client for each project and service URL within each process. Pass the current user's identity with each application request. Do not create or close a Client for each request, or reuse Features across users. client.options contains the normalized, read-only configuration, and client.closed indicates whether shutdown has started.
3.2 Reuse an Existing Data Collection Instance
If your application already uses the official Node.js data collection SDK, keep the existing instance's Consumer, batching, and scheduled flush settings. After the data collection instance is initialized, pass that same instance to tdAnalytics:
const { createClient, SplitMode } = require('td-feature-node');
// existingAnalytics is the application's initialized instance with track/flush/close methods.
const client = createClient({
appId: 'YOUR_APP_ID',
serverUrl: 'https://YOUR_SERVER_URL',
splitMode: SplitMode.REMOTE,
tdAnalytics: existingAnalytics,
});
If no instance is injected, the SDK lazily creates an official Batch data collection instance on the first exposure, using the same appId and serverUrl.
3.3 ESM and TypeScript
ESM projects consume the CommonJS package through a default import. The import syntax is shown below; place the remaining calls in an async function:
import sdk from 'td-feature-node';
const { createClient, SplitMode } = sdk;
TypeScript projects can import APIs and public types directly. The compiler version should match your application project:
import { createClient, SplitMode } from 'td-feature-node';
import type { ClientOptions, FeatureRequest } from 'td-feature-node';
const options: ClientOptions = {
appId: 'YOUR_APP_ID',
serverUrl: 'https://YOUR_SERVER_URL',
splitMode: SplitMode.REMOTE,
};
const client = createClient(options);
const request: FeatureRequest = {
accountId: 'user_123',
featureKeys: ['checkout_button'],
};
3.4 Initialization Configuration Reference
3.4.1 Connections and Requests
| Configuration | Default Value | Description |
|---|---|---|
| appId | Required | The project App ID, as a non-empty string. |
| serverUrl | Required | The HTTP(S) base URL shared by remote decisions and SDK-created data collection. |
| splitMode | SplitMode.REMOTE | The string REMOTE is also accepted; LOCAL is currently unsupported. |
| timeout | 5000 ms | The timeout for each HTTP attempt. |
| maxHttpConnections | 20 | The maximum number of connections in the RCC connection pool. |
| tlsCa | Node's default trust roots | An optional PEM CA string or array. Setting this explicitly replaces the default CA list for this Client. |
3.4.2 Retries
| Configuration | Default Value | Description |
|---|---|---|
| retryTimes | 0 | The number of additional retries after the initial request, ranging from 0 to 10. |
| retryStrategy | EXPONENTIAL_BACKOFF | FIXED_INTERVAL is also available. |
| retryInterval | 500 ms | The initial backoff interval. A value of 0 is allowed. |
3.4.3 Result Cache
| Configuration | Default Value | Description |
|---|---|---|
| enableCache | false | Explicitly enables caching of successful results. |
| cacheExpireTime | 86400 seconds | Used as a fallback only when the RCC TTL is non-positive. A value of 0 is allowed. |
| maxCacheSize | 10000 | The maximum number of result cache entries. A value of 0 means results are not stored. |
3.4.4 Exposure and Data Collection
| Configuration | Default Value | Description |
|---|---|---|
| autoExposure | false | Attempts to report exposure on the first read of the raw or typed value. |
| exposureDedupMaxSize | 100000 | The maximum number of exposure deduplication entries. |
| exposureDedupExpireSeconds | 86400 seconds | The non-sliding deduplication TTL. |
| tdAnalytics | Not specified | The application's existing official data collection instance, owned and closed by the application. |
| exposureAdapter | Not specified | A custom data collection adapter, mutually exclusive with tdAnalytics and owned by the application. |
3.4.5 Private CAs and Custom Data Collection
When using a private CA, you can explicitly pass a trusted certificate; certificate chain and hostname validation still apply. tlsCa affects only RCC and the SDK-created collector. External instances continue to use their own TLS configurations:
const fs = require('fs');
const { createClient } = require('td-feature-node');
const client = createClient({
appId: 'YOUR_APP_ID',
serverUrl: 'https://YOUR_SERVER_URL',
tlsCa: fs.readFileSync('/path/to/trusted-ca.pem', 'utf8'),
});
4. Retrieve Configuration and Experiment Information
4.1 Pass the Current User Identity
| Request Parameter | Meaning | Usage Requirements |
|---|---|---|
| accountId | Account ID, corresponding to #account_id | Pass a stable, accurate account identifier when allocating by account. |
| distinctId | Visitor or device ID, corresponding to #distinct_id | Pass an identifier consistent with the definition in the AE console when allocating by visitor. |
At least one of accountId and distinctId must be a non-empty string; both can also be passed. Your application must explicitly convert numeric IDs to strings; identities cannot contain control characters.
4.2 Retrieve One or More Features
client.fetch(request, options?) returns Promise<Evaluation>. In the partial examples below, client is the shared Client created in section 3, and await calls should be placed inside an async function. Use the featureKeys array for both a single Key and multiple Keys:
const config = await client.fetch({
accountId: 'user_123',
distinctId: 'visitor_456',
featureKeys: ['checkout_button', 'recommendation_enabled'],
});
const feature = config.features['checkout_button'];
4.3 Read Configuration Values of Different Types
| Variable Type in the AE Console | Read Method | Return Type and Fallback Rules |
|---|---|---|
| String | feature.asString(defaultValue) | string; converts non-null values to strings, and objects and arrays to JSON text. |
| Number | feature.asNumber(defaultValue) | number; accepts numbers or non-empty numeric strings and converts them using the native Number() function. |
| Boolean | feature.asBoolean(defaultValue) | boolean; accepts booleans and case-insensitive true/false strings. Numeric 0/1 values are not converted. |
| JSON Object | feature.asJson(defaultValue) | JSON object; accepts objects or JSON strings that can be parsed as objects. Arrays, null, and invalid JSON use the fallback. |
| Raw Value | feature.value | The raw JSON value, including arrays and null. |
const config = await client.fetch({
accountId: 'user_123',
featureKeys: ['recommendation_enabled', 'discount_rate', 'page_config'],
});
const enabledFeature = config.features['recommendation_enabled'];
const enabled = enabledFeature ? enabledFeature.asBoolean(false) : false;
const rateFeature = config.features['discount_rate'];
const rate = rateFeature ? rateFeature.asNumber(0) : 0;
const defaults = { theme: 'default' };
const pageFeature = config.features['page_config'];
const page = pageFeature ? pageFeature.asJson(defaults) : defaults;
For all four typed getters, the fallback is null when the default value is omitted; when the value is null or cannot be converted, the provided default value is used. Handle missing configurations and conversion failures separately. false, 0, and empty strings are valid values; do not override them with value || defaultValue.
4.4 Retrieve Experiment Information
const feature = config.features['checkout_button'];
if (feature) {
console.log('Feature Key:', feature.key);
console.log('Has value:', feature.hasValue);
const info = feature.experiment;
if (info && info.experimentId && info.experimentGroupId) {
console.log('Experiment ID:', info.experimentId);
console.log('Group ID:', info.experimentGroupId);
console.log('Is control group:', info.isControlGroup);
console.log('Bucket identity:', info.bucketId);
}
}
4.5 Retrieve All Configurations Visible to the Current Request
const all = await client.fetch({
accountId: 'user_123',
distinctId: 'visitor_456',
});
const keys = Object.keys(all.features);
console.log(keys);
console.log(all.ttl); // The original RCC TTL in seconds, not the remaining cache lifetime.
When featureKeys is omitted, null, or an empty array, all configurations returned by the server for the current identity and request conditions are retrieved.
4.6 Custom Request Parameters
const config = await client.fetch({
accountId: 'user_123',
featureKeys: ['checkout_button'],
customParams: {
vip_level: 3,
channel: 'app_store',
country: 'CN',
},
});
customParams is a JSON object. Parameter names, types, and meanings must match the rules in the AE console. Strings, finite numbers, booleans, null, arrays, and nested objects are supported; undefined, Date, BigInt, functions, NaN, Infinity, and circular references are not accepted. null values in objects and arrays are preserved. #account_id, #distinct_id, #lib, and #feature_key are managed by the SDK and cannot be overridden through custom parameters. Custom parameters do not set a new allocation subject.
5. Report Exposure Events
Exposure means that an experiment configuration is actually used by the application. A successful fetch, obtaining a Feature, or inspecting experiment metadata does not mean exposure has occurred. The SDK uses the data collection instance to report te_experiment_exposure with #experiment_id, #experiment_group_id, #is_control_group, and #rule_type="experiment". Fields such as the Feature version and allocation source that are not provided by the current remote parsing are not fabricated in the event.
5.1 Manual Exposure (Default)
The default is autoExposure: false. After your application actually uses the configuration, pass the Feature object returned by this request to expose(); the argument is not a Feature Key string:
const feature = config.features['checkout_button'];
const style = feature.asString('control');
console.log('Value used by the application:', style); // Replace this with your actual application logic.
const accepted = client.expose(feature, { scene: 'checkout', channel: 'web' });
console.log('Exposure enqueued:', accepted);
5.2 Automatic Exposure (Optional)
const client = createClient({
appId: 'YOUR_APP_ID',
serverUrl: 'https://YOUR_SERVER_URL',
autoExposure: true,
});
const config = await client.fetch({
accountId: 'user_123',
featureKeys: ['checkout_button'],
});
const feature = config.features['checkout_button'];
const style = feature ? feature.asString('control') : 'control';
When enabled, the first read of feature.value or call to asString/asNumber/asBoolean/asJson attempts to report exposure, provided valid experiment information is present. Each returned Feature automatically triggers exposure at most once, followed by Client-level deduplication; a cache hit returns a new Feature with its own automatic trigger state.
5.3 Deduplication, Asynchronous Sending, and Flushing
- Deduplication uses "allocation subject + experiment ID + group ID" in the current Client's memory. The subject is selected from the first non-empty entry in bucketId, then accountId, then distinctId. The Feature Key is not part of deduplication; multiple Features in the same experiment group share one exposure.
- Deduplication is always enabled, with a default maximum of 100000 entries and a TTL of 86400 seconds. Reads do not extend the TTL. Exposure may be reported again after expiry, capacity eviction, Client recreation, or process restart;
- Exposure events are sent through a bounded asynchronous queue, with 10000 waiting slots by default plus one active task. The SDK-created collector defaults to batches of 100 events and buffers incomplete batches for up to 1000 ms.
6. Retrieve Configurations Asynchronously
6.1 async/await and Promise
async function readStyle(accountId) {
try {
const config = await client.fetch({
accountId: accountId,
featureKeys: ['checkout_button'],
});
const feature = config.features['checkout_button'];
return feature ? feature.asString('control') : 'control';
} catch (error) {
console.error('Configuration request failed:', error.code);
return 'control';
}
}
client.fetch({ accountId: 'user_123', featureKeys: ['checkout_button'] })
.then(function (config) {
const feature = config.features['checkout_button'];
console.log(feature ? feature.asString('control') : 'control');
})
.catch(function (error) {
console.error(error.code, error.message);
});
The asynchronous retrieval examples above only show queries and do not report exposure by default. Add an exposure call as described in section 5 at the point where the returned value is actually used.
6.2 Timeouts, Retries, and Concurrency
- timeout defaults to 5000 ms and applies only to each HTTP attempt, including waiting for a connection and reading the response. Queueing, retry backoff, and RCC field decoding are not included in this HTTP timeout; when retries are enabled, the timer resets for each attempt.
- retryTimes defaults to 0, with no automatic retries. When explicitly set to a positive number, the maximum number of attempts is 1 + retryTimes. Temporary network errors, individual attempt timeouts, and HTTP 408/429/500/502/503/504 can be retried a limited number of times. RCC business errors, invalid responses, permanent DNS/certificate errors, and similar errors are not retried.
- By default, at most 20 fetch calls can be active, with no waiting queue (maxQueueSize: 0). Requests are rejected immediately with QUEUE_FULL when all concurrency slots are occupied. A bounded FIFO queue is enabled only when maxQueueSize is explicitly set to a positive number; requests are also rejected when all waiting slots are occupied. Cache hits return directly without using the queue.

