NodeJS SDK
Introduction
Welcome to the developer documentation for the Kameleoon NodeJS SDK. Our SDK makes it possible to run experiments and activate feature flags on your back-end NodeJS server. Integrating our SDK into your web application is easy, and its requirements, in terms of memory and network usage are low.
We created this guide to help you integrate our SDK in just a few minutes so that you can start activating feature flags and running feature experiments in your NodeJS applications.
Requirements
Kameleoon supports any NodeJS version that is equal or superior to 8.0
.
Changelog
Latest version of the NodeJS SDK: 3.3.0 (changelog).
Installation
Installing the NodeJS client
npm install kameleoon-client-nodejs
You can install the SDK directly through an NPM
module. Our module is hosted on official npm repositories, so you just have to run the following command:
npm install kameleoon-client-nodejs
Additional configuration
Provide credentials for the NodeJS SDK via a configuration file, which you can also use to customize the SDK's behavior. Get a sample configuration file here. We recommend installing this file to the default path of /etc/kameleoon/client-nodejs.json
, which will be read by default. If you need to customize this, you can provide an additional argument to the KameleoonClient()
constructor method: Use either a string specifying an alternative path (to save the configuration file in another location), or directly add a JavaScript object (map) containing the configuration. The current version of the NodeJS SDK has the following keys available:
- client_id: a
client_id
is required for authentication to the Kameleoon service. - client_secret: a
client_secret
is required for authentication to the Kameleoon service. - actions_configuration_refresh_interval: this key specifies the refresh interval, in minutes, for the configuration of experiments and feature flags. (Active experiments and feature flags are fetched from Kameleoon's CDN). The value defined here will determine the maximum duration of the interval required to propagate changes, i.e., activate or deactivate feature flags or launch experiments, in production to your servers. If not specified, the default interval is 60 minutes. We also provide a streaming mode that allows the SDK to automatically take into account the new configuration, without delays, thanks to server-sent events (SSE).
- visitor_data_maximum_size: this key specifies the maximum amount of memory, in MB, that the map holding all visitor data (particularly custom data) can take. If not specified, the default size is 500MB.
- proxy_host: host to be used as proxy for all the outgoing server calls made by the SDK.
- environment: can be used optionally to specify the environment from which a feature flag’s configuration is to be used. By default, each feature flag is split into production, staging, development. If not specified, the default value will be set to production. More information
SDK methods
Follow the Main usage section to configure your NodeJS app and start running feature experiments and roll out new features to your users. This section contains all the main steps for the proper configuration of the Kameleoon NodeJS SDK as well as main tools for development.
We recommend you explore the Additional Tools section containing additional useful information features, utility hooks, and higher-order components, which will simplify the usage of NodeJS SDK.
- Initialize
- runWhenReady
- Visitor Code / User ID
- Feature Variables
- Feature Flag list
- Add User Data
- Retrieve External Segments
- On Update Configuration
- Filtering bot traffic
To run server-side or hybrid experiments, without the need to configure feature flags, use the following methods:
Review the Technical Considerations section to learn how the SDK operates.
Main usage
Below is a step-by-step guide for configuring the NodeJS SDK in your application.
1. Initialize the Kameleoon Client
let { KameleoonClient, KameleoonData } = require("kameleoon-client-nodejs");
let siteCode = "a8st4f59bj";
let kameleoonClient = new KameleoonClient(siteCode);
// Option 1 - Using configuration saved in the fyle system
kameleoonClient = new KameleoonClient(siteCode, "/etc/kameleoon/client-nodejs.json");
// Option 2 - Using configuration passed to client
kameleoonClient = new KameleoonClient(siteCode, {
"client_id": "YOUR_CLIENT_ID",
"client_secret": "YOUR_CLIENT_SECRET",
"actions_configuration_refresh_interval": 60,
"visitor_data_maximum_size": 500
});
// Waiting for the client to be properly initialized
await kameleoonClient.initialize();
After installing the SDK in your application and configuring the correct credentials (in /etc/kameleoon/client-nodejs.json
), you need to create the Kameleoon client in your application code. A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment.
Arguments
Name | Type | Description |
siteCode | string | Unique identifier code of the project (website or app), which can be found in our platform's back-office. This field is mandatory. |
configuration | String or ClientConfiguration | Depending on the type of argument provided, this represents either the path to the SDK configuration file (if a string is passed), or the configuration object directly (which should contain the correct configuration keys). This field is optional and set to /etc/kameleoon/client-nodejs.json , by default. |
Exceptions Thrown
Type | Description |
KameleoonException.CredentialsNotFound | Exception indicating that the requested credentials were not provided (either via the configuration file, or via a configuration map passed as a parameter). |
2. Get access to feature flags and variations
const visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com");
// Required if you want to filter out bots from your traffic. You need to get the user agent for the visitor and pass it to the Kameleoon client object
kameleoonClient.addData(
visitorCode,
new KameleoonData.UserAgent("visitor_user_agent"));
const featureKey = "feature_key";
let hasNewCheckout = false;
// First option: check if a Feature Flag is active (ON / OFF)
try {
hasNewCheckout = kameleoonClient.isFeatureActive(visitorCode, featureKey);
}
catch (e) {
if (e instanceof KameleoonException.VisitorCodeNotValid) {
// The visitor code provided is not valid. Trigger the old checkout for this visitor.
hasNewCheckout = false;
} else if (e instanceof KameleoonException.FeatureConfigurationNotFound) {
// The feature flag has not been found in the current configuration fetched by the SDK
hasNewCheckout = false;
}
}
if (hasNewCheckout) {
// Implement new checkout code here
}
// Second option: Feature Experiment with variations
let variationKey = ""
try {
variationKey = kameleoonClient.getFeatureVariationKey(visitorCode, featureKey);
}
catch (e) {
if (e instanceof KameleoonException.FeatureConfigurationNotFound) {
// The feature flag has not been found in the current configuration fetched by the SDK
}
}
switch(variationKey) {
case 'on':
//main variation key
break;
case 'alternative_variation':
//alternative variation key
break;
default:
//default variation key
break;
}
To implement a feature flag in your code, you must first create a feature flag in your Kameleoon account.
isFeatureActive
This method takes a visitorCode and featureKey as mandatory arguments to check if the feature flag is active for a given user. Call the getVisitorCode() method to obtain the Kameleoon visitorCode for the current visitor when using Kameleoon in Hybrid mode, where user identification consistency must be guaranteed. Alternatively, if you provide your own User ID / Visitor code, you must ensure its uniqueness on your end.
If such a user has never been associated with a feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous FeatureFlag value.
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
featureKey | string | The key of the feature you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
bool | Value of the feature flag that is registered for a given visitorCode. |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This means that the feature flag has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode. |
KameleoonException.VisitorCodeNotValid | Exception indicating that the visitor code provided is not valid (empty or length of the User ID you provide is longer than 255 characters). |
getFeatureVariationKey
To get a feature variation key, call the getFeatureVariationKey()
method of our SDK.
This method takes a visitorCode and featureKey as mandatory arguments to get a variation key for a given user. Call the getVisitorCode() method to obtain the Kameleoon visitorCode for the current visitor when using Kameleoon in Hybrid mode, where user identification consistency must be guaranteed. Alternatively, if you provide your own User ID / Visitor code, you must ensure its uniqueness on your end.
If a user has never been associated with a feature flag, the SDK returns a variation key randomly, in accordance with the feature flag rules. If a user with a given visitorCode is already registered with the feature flag, the SDK will detect the previous variation key value. If a user does not match any of the rules, the default value will be returned. (The default value is defined in Kameleoon's feature flag delivery rules.)
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
featureKey | string | The key of the feature you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
string | Variation key of the feature flag that is registered for a given visitorCode. |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This means that the feature flag has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode. |
3. Track goals
trackConversion
let visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com");
let goalID = 83023;
kameleoonClient.trackConversion(visitorCode, goalID);
Use this method to track conversion for any goal set up in your account. This method requires visitorCode and goalID to track conversion on a particular goal. This method also accepts revenue as a third, optional argument to track revenue.
The trackConversion()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
goalID | number | The ID of the goal. This field is mandatory. |
revenue | number | The revenue of the conversion. This field is optional. |
Additional Tools
initialize
const { KameleoonClient } = require("kameleoon-client-nodejs");
const kameleoonClient = new KameleoonClient(siteCode, {...myConfiguration});
await kameleoonClient.initialize();
const variationKey = kameleoonClient.getFeatureVariationKey(visitorCode, featureKey);
The initialize
method makes sure the client was properly initialized with the http request. Using initialize
before any other client methods will ensure that remote server configuration is in place to perform zero-latency tasks.
Return value
Type | Description |
Promise | Empty Promise |
runWhenReady
const { KameleoonClient } = require("kameleoon-client-nodejs");
const kameleoonClient = new KameleoonClient(siteCode, {...myConfiguration});
kameleoonClient.runWhenReady(
() => {
const variationKey = kameleoonClient.getFeatureVariationKey(visitorCode, featureKey);
},
() => {
console.log("Timeout occurred in the NodeJS SDK initialization.");
},
2000
);
const variationKey = kameleoonClient.getFeatureVariationKey(visitorCode, featureKey);
The runWhenReady
method makes sure the client was properly initialized with the http request. It is called directly on the client, and it processes the code in a callback fashion upon client initialization, using success and error callbacks along with the timeout.
Arguments
Name | Type | Description |
successCallback | () => void | callback which will be executed upon successful initialization of the client |
errorCallback | () => void | callback which will be executed if the initialization fails or timeout runs out |
timeout | number | timeout time, in milliseconds, to await the initialization |
getVisitorCode
const { v4: uuidv4 } = require("uuid");
let visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com");
visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com", visitorCode);
visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com", uuidv4());
Call the getVisitorCode()
helper method to obtain the Kameleoon visitorCode for the current visitor. This is especially important when using Kameleoon in Hybrid mode with mixed front-end and back-end environments, where user identification consistency must be guaranteed. The implementation logic is described here:
First, Kameleoon checks if there is a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request. If there is, we will use this as the visitor identifier.
If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the defaultVisitorCode argument as an identifier if it is passed. This allows you to use your own identifiers as visitor codes, if you choose so. This gives you the added benefit of matching Kameleoon visitors with your own users without any additional look-ups in a matching table.
In any case, the server-side kameleoonVisitorCode cookie is set with the value (via HTTP header). Then this identifier value is finally returned by the method.
For more information, refer to this article.
Arguments
Name | Type | Description |
req | http.ClientRequest | The current ClientRequest object should be passed as the first parameter. This field is mandatory. |
res | http.ServerResponse | The current ServerResponse object should be passed as the second parameter. This field is mandatory. |
topLevelDomain | string | Your current top level domain for the particular site. (This information is necessary to set the corresponding cookie accordingly on the top level domain). This field is mandatory. |
defaultVisitorCode | string | This parameter will be used as the visitorCode if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and by default a random visitorCode will be generated. |
Return value
Type | Description |
string | A visitorCode that will be associated with this particular user. It should be used with most methods of the SDK. |
Feature Variables
getFeatureVariable
const visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com");
const featureKey = "feature_key";
const variableName = "var"
try {
const variableValue = kameleoonClient.getFeatureVariable(visitorCode, featureKey, variableName);
// your custom code depending of variableValue
}
catch (e) {
if (e instanceof KameleoonException.FeatureConfigurationNotFound) {
// The feature flag has not been found in the current configuration fetched by the SDK
}
}
To get a feature variable of a variation key associated with a user, call the getFeatureVariable()
method of our SDK.
This method takes a visitorCode, featureKey and variableName as mandatory arguments to get a variable of the variation key for a given user.
If a user has never been associated with this feature flag, the SDK returns a variable value of the variation key randomly, in accordance with the feature flag rules. If a user with a given visitorCode is already registered with this feature flag, the SDK will detect the variable value for previously associated variation. If the user does not match any of the rules, the default variable will be returned.
Make sure you set up proper error handling in your code, as shown in the example to the right, to catch potential exceptions.
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
featureKey | string | The key of the feature you want to expose to a user. This field is mandatory. |
variableName | string | The name of the variable for which you want to get a value. This field is mandatory. |
Return value
Type | Description |
any | The value for the variable of the variation that is registered for a given visitorCode for a particular feature flag. Possible types: boolean, number, string, JSON object |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This means that the feature flag has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode. |
getFeatureAllVariables
let featureKey = "myFeature";
let data;
try {
data = kameleoonClient.getFeatureAllVariables(featureKey);
}
catch (e) {
if (e instanceof KameleoonException.FeatureConfigurationNotFound) {
// The feature is not yet activated on Kameleoon's side
}
}
To retrieve all variables of a feature, call the getFeatureAllVariables()
method of our SDK. You can easily change feature variables in our web application.
This method takes one input parameter: featureKey. It will return the data with the object type, as defined in the web interface. It will throw an exception (KameleoonException.FeatureConfigurationNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
Arguments
Name | Type | Description |
featureKey | string | The key of the feature you want to obtain for a user. This field is mandatory. |
Return value
Type | Description |
object | Data associated with the feature flag. Possible values of the object: boolean, number, string or JSON object, depending on the type defined in the web interface. |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This means that the feature flag has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode. |
Get Feature List
getFeatureList
const featureFlagIds = kameleoonClient.getFeatureList()
The get a list of feature flag keys currently available for the SDK, call the kameleoonClient.getFeatureList()
method.
Return value
Type | Description |
Array | List of feature flag keys |
getFeatureListForVisitorCode
const onlyActive = true
const experimentIds = kameleoonClient.getFeatureListForVisitorCode(visitorCode, onlyActive)
This method takes two input parameters: visitorCode and onlyActive. If the onlyActive
parameter is true
, the result will contain only active feature flags. Otherwise, it will contain all targeted feature flags to a specific visitorCode
. The method will returns a list of feature flag IDs currently available for specific visitorCode
according to the onlyActive
option.
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
onlyActive | boolean | The value is true by default, and the result contains only active feature flags for the user. To fetch all targeted feature flag IDs, set the value to false . This field is optional. |
Return value
Type | Description |
Array | List of feature flag keys available for a specific visitorCode , according to the onlyActive option |
Add User Data
addData
To associate various data points with the current user, you can use the addData()
method. This method requires the visitorCode as a first parameter, then accepts several additional parameters. These additional parameters represent the various Data Types allowed in Kameleoon.
Note that the addData()
method doesn't return any value and doesn't interact with Kameleoon back-end servers by itself. Instead, all declared data is saved for further sending via the flush()
method described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of flush()
.
CustomData
kameleoonClient.addData(visitorCode, new KameleoonData.CustomData(1, 'some custom value'));
Name | Type | Description |
index | number | The Index / ID of the custom data to be stored. This field is mandatory. |
value | string | The value of the custom data to be stored. This field is mandatory. |
Browser
kameleoonClient.addData(visitorCode, new KameleoonData.Browser(KameleoonData.browsers.CHROME));
kameleoonClient.addData(visitorCode, new KameleoonData.Browser(KameleoonData.BrowserType.CHROME));
Name | Type | Description |
browser | number or BrowserType | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory. |
PageView
kameleoonClient.addData(visitorCode, new KameleoonData.PageView('https://url.com', 'title', [3]));
Name | Type | Description |
url | string | The URL of the page viewed. This field is mandatory. |
title | string | The title of the page viewed. This field is mandatory. |
referrers | Array | The referrers of the viewed pages. This field is optional. |
Conversion
kameleoonClient.addData(visitorCode, new KameleoonData.Conversion(32, 10, false));
Name | Type | Description |
goalID | number | The ID of the goal. This field is mandatory. |
revenue | number | Conversion revenue. This field is optional. |
negative | boolean | Defines if the revenue is positive or negative. This field is optional. |
Device
kameleoonClient.addData(visitorCode, new KameleoonData.Device(KameleoonData.DeviceType.Desktop));
Name | Type | Description |
device | DeviceType | List of devices: Phone, Tablet, Desktop. This field is mandatory. |
UserAgent
Server-side experiments are usually more vulnerable to bot traffic than client-side experiments. We recommend you pass the user agent to be filtered by Kameleoon when running server-side experiments. However, if you run a Kameleoon hybrid experiment, server-side experiments will automatically be protected against bot traffic.
kameleoonClient.addData(
visitorCode,
new KameleoonData.UserAgent("visitor_user_agent"));
Name | Type | Description |
value | string | The User-Agent value that will be sent with tracking requests. This field is mandatory. |
retrieveDataFromRemoteSource
const data = await kameleoonClient.retrieveDataFromRemoteSource("USER_ID")
kameleoonClient.retrieveDataFromRemoteSource("USER_ID").then((data: any) => {
//operate with retrieving data
})
The retrieveDataFromRemoteSource()
method allows you to retrieve external data (according to a key passed as argument) for the specified siteCode (specified in KameleoonClient
constructor) stored on Kameleoon's remote server. Usually, data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users. We provide native integrations with Mixpanel, Segment, and GA4 to retrieve external cohorts and use them in feature experiments. The key used in these integrations are either our own Visitor code or your User ID.
Note that, since a server call is required, this mechanism is asynchronous.
Arguments
Name | Type | Description |
key | string | The key with which the data you are trying to retrieve is associated. This field is mandatory. |
Return value
Type | Description |
Promise | Promise with retrieving data for a specific key |
flush
var {KameleoonClient, KameleoonData} = require("kameleoon-client-nodejs");
let visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com");
kameleoonClient.addData(visitorCode, new KameleoonData.Browser(KameleoonData.browsers.CHROME));
kameleoonClient.addData(
visitorCode,
new KameleoonData.PageView("https://url.com", "title", [3])
);
kameleoonClient.addData(visitorCode, new KameleoonData.Conversion(32, 10, false));
kameleoonClient.flush(visitorCode);
The flush()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
onUpdateConfiguration
kameleoonClient.onUpdateConfiguration(() => {
// configuration was updated
})
The onUpdateConfiguration()
method allows you to handle the event when a configuration has updated data. It takes one input parameter, handler. The handler that will be called when the configuration is updated, using a real-time configuration event.
Arguments
Name | Type | Description |
handler | () => void | The handler that will be called when the configuration is updated, using a real-time configuration event. |
triggerExperiment
let visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com");
let experimentID = 75253;
let variationID;
try {
variationID = kameleoonClient.triggerExperiment(
visitorCode,
experimentID
);
} catch (e) {
if (e instanceof KameleoonException.NotTargeted) {
// The user did not trigger the experiment, as the associated targeting segment conditions were not fulfilled. He should see the reference variation
variationID = 0;
}
if (e instanceof KameleoonException.NotActivated) {
// The user triggered the experiment, but did not activate it. Usually, this happens because the user has been associated with excluded traffic
variationID = 0;
}
if (e instanceof KameleoonException.ExperimentConfigurationNotFound) {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
}
}
To implement a server-side or hybrid experiment in your code, you must first create the experiment in your Kameleoon account.
To trigger an experiment, call the triggerExperiment()
method of our SDK.
This method takes the visitorCode and experimentID as mandatory arguments to register a variation for a given user.
If a user has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given visitorCode is already registered with a variation, it will detect the previously registered variation and return the variationID.
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
experimentID | number | The ID of the experiment you want to expose to a user. This field is mandatory. |
Return value
Name | Type | Description |
variationID | number | The ID of the variation that is registered for a given visitorCode. By convention, the reference (i.e., original variation) always has an ID equal to 0. |
Exceptions Thrown
Type | Description |
KameleoonException.NotTargeted | Exception indicating that the current visitor / user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder. |
KameleoonException.NotActivated | Exception indicating that the current visitor / user triggered the experiment (i.e., met the targeting conditions), but did not activate it. The most common reason for this is that part of the traffic has been excluded from the experiment and should not be tracked. |
KameleoonException.ExperimentConfigurationNotFound | Exception indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This means that the experiment has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode. |
getVariationAssociatedData
let visitorCode = kameleoonClient.getVisitorCode(req, res, "example.com");
int experimentID = 75253;
try {
let variationID = kameleoonClient.triggerExperiment(visitorCode, experimentID);
let jsonObject = kameleoonClient.getVariationAssociatedData(variationID);
let firstName = jsonObject["firstName"];
}
catch (e) {
if (e instanceof KameleoonException.VariationConfigurationNotFound) {
// The variation is not yet activated on Kameleoon's side, i.e., the associated experiment is not online
}
}
To retrieve JSON data associated with a variation, call the getVariationAssociatedData()
method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.
This method takes the variationID as a parameter, and will return the data as a JavaScript object. It will throw an exception (KameleoonException.VariationConfigurationNotFound
) if the variation ID is wrong or corresponds to an experiment that is not yet online.
Arguments
Name | Type | Description |
variationID | int | The ID of the variation for which you want to obtain the associated data. This field is mandatory. |
Return value
Type | Description |
Object | Data associated with this variationID. |
Exceptions Thrown
Type | Description |
KameleoonException.VariationConfigurationNotFound | Exception indicating that the requested variation ID has not been found in the internal configuration of the SDK. This means that the experiment has not yet been retrieved by the SDK. This may happen if the SDK is in polling mode. |
Get Experiment List
getExperimentList
const experimentIds = kameleoonClient.getExperimentList()
This method returns a list of experiment IDs currently available for the SDK.
Return value
Type | Description |
Array | List of experiment IDs |
getExperimentListForVisitorCode
const activeExperimentList = kameleoonClient.getExperimentListForVisitorCode(visitorCode)
const onlyActive = false
const targetedExperimentList = kameleoonClient.getExperimentListForVisitorCode(visitorCode, onlyActive)
This method takes two input parameters: visitorCode and onlyActive. It returns a list of experiment IDs currently available for a specific visitorCode
according to the onlyActive
option.
If the onlyActive
parameter is true
, the result will only contain active experiments. Otherwise, it will contain all targeted experiments for the specific visitorCode
.
Arguments
Name | Type | Description |
visitorCode | string | The user's unique identifier. This field is mandatory. |
onlyActive | boolean | The value is true by default, and the result contains only active experiments for the user. To fetch all targeted experiment IDs, set the value to false . This field is optional. |
Return value
Type | Description |
Array | The list of experiment IDs available for a specific visitorCode according to the onlyActive option. |
Technical Considerations
Overview
Kameleoon made an important architectural design decision with its SDK technology, namely that every SDK must comply with a zero latency policy.
In practice, this means that any blocking remote server call is banned, as even the fastest remote call would add a 20ms latency to your application. And, if for any reason, our servers are slower to reply than usual (unfortunately, this can happen), this delay can quickly increase to hundreds of milliseconds, seconds...or even completely block the loading of the web page for the end user. We believe that web performance is of paramount importance today, and adding server-side A/B testing or feature flagging capabilities should not come at the cost of increased web page rendering time. For this reason, we guarantee that the use of our SDKs has no impact on the performance of the host platform.
However, having a zero latency policy does impose some constraints. The main one is that user data about your visitor should be kept locally, and not fetched from a remote server. For instance, if you set a custom data for a given visitor, we have to store it in your server / infrastructure in some way, and not on our (remote) side.
In the case of the NodeJS SDK, this is implemented via a map of visitor data (where the keys are the visitorCodes), directly on RAM. So, if you use new KameleoonData.CustomData()
and the kameleoonClient.addData()
methods, the information will be stored in the application's RAM (the one hosting the SDK, usually an application server). The map is regularly cleaned (i.e., old visitor data is erased); therefore, it usually doesn't get too large in size, unless you have a very large traffic and use lots of custom data.
Configuration Updates
When you update your experiment or feature flag configuration, the SDK can get it in two different ways. The first - polling - consists of retrieving the configuration at regular intervals. The second - streaming - is to retrieve the new configuration immediately.
Polling
This mode of obtaining the configuration is used by default. The SDK will send a request to Cloudflare CDN at regular intervals to retrieve the configuration. If you have not set an interval in the SDK configuration, the configuration in the SDK will be refreshed every 60 minutes. It can be configured with the actions_configuration_refresh_interval parameter.
-
Benefits:
- When intervals are moderately spaced, updating the configuration consumes nominal memory and network resources.
Streaming
This mode allows the SDK to automatically take into account the new configuration without delay. When streaming is enabled, the Kameleoon SDK is notified of any changes to the configuration in real-time, thanks to server-sent events (SSE).
-
Benefits:
- Streaming makes it possible to propagate and apply a new configuration in real-time.
- It also reduces network traffic compared to polling at short intervals, as streaming does not require sending periodic requests. It opens the connection once, then keeps it permanently open and remain ready to receive data.