NAV
  • NodeJS SDK
  • 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:

    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.

    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
    NameTypeDescription
    siteCodestringUnique identifier code of the project (website or app), which can be found in our platform's back-office. This field is mandatory.
    configurationString or ClientConfigurationDepending 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
    TypeDescription
    KameleoonException.CredentialsNotFoundException 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
    NameTypeDescription
    visitorCodestringThe user's unique identifier. This field is mandatory.
    featureKeystringThe key of the feature you want to expose to a user. This field is mandatory.
    Return value
    TypeDescription
    boolValue of the feature flag that is registered for a given visitorCode.
    Exceptions Thrown
    TypeDescription
    KameleoonException.FeatureConfigurationNotFoundException 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.VisitorCodeNotValidException 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
    NameTypeDescription
    visitorCodestringThe user's unique identifier. This field is mandatory.
    featureKeystringThe key of the feature you want to expose to a user. This field is mandatory.
    Return value
    TypeDescription
    stringVariation key of the feature flag that is registered for a given visitorCode.
    Exceptions Thrown
    TypeDescription
    KameleoonException.FeatureConfigurationNotFoundException 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
    NameTypeDescription
    visitorCodestringThe user's unique identifier. This field is mandatory.
    goalIDnumberThe ID of the goal. This field is mandatory.
    revenuenumberThe 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
    TypeDescription
    PromiseEmpty 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
    NameTypeDescription
    successCallback() => voidcallback which will be executed upon successful initialization of the client
    errorCallback() => voidcallback which will be executed if the initialization fails or timeout runs out
    timeoutnumbertimeout 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:

    1. 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.

    2. 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.

    3. 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
    NameTypeDescription
    reqhttp.ClientRequestThe current ClientRequest object should be passed as the first parameter. This field is mandatory.
    reshttp.ServerResponseThe current ServerResponse object should be passed as the second parameter. This field is mandatory.
    topLevelDomainstringYour 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.
    defaultVisitorCodestringThis 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
    TypeDescription
    stringA 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
    NameTypeDescription
    visitorCodestringThe user's unique identifier. This field is mandatory.
    featureKeystringThe key of the feature you want to expose to a user. This field is mandatory.
    variableNamestringThe name of the variable for which you want to get a value. This field is mandatory.
    Return value
    TypeDescription
    anyThe 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
    TypeDescription
    KameleoonException.FeatureConfigurationNotFoundException 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
    NameTypeDescription
    featureKeystringThe key of the feature you want to obtain for a user. This field is mandatory.
    Return value
    TypeDescription
    objectData 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
    TypeDescription
    KameleoonException.FeatureConfigurationNotFoundException 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
    TypeDescription
    ArrayList 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
    NameTypeDescription
    visitorCodestringThe user's unique identifier. This field is mandatory.
    onlyActivebooleanThe 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
    TypeDescription
    ArrayList 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'));
    
    NameTypeDescription
    indexnumberThe Index / ID of the custom data to be stored. This field is mandatory.
    valuestringThe 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));
    
    NameTypeDescription
    browsernumber or BrowserTypeList 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]));
    
    NameTypeDescription
    urlstringThe URL of the page viewed. This field is mandatory.
    titlestringThe title of the page viewed. This field is mandatory.
    referrersArrayThe referrers of the viewed pages. This field is optional.
    Conversion
    kameleoonClient.addData(visitorCode, new KameleoonData.Conversion(32, 10, false));
    
    NameTypeDescription
    goalIDnumberThe ID of the goal. This field is mandatory.
    revenuenumberConversion revenue. This field is optional.
    negativebooleanDefines if the revenue is positive or negative. This field is optional.
    Device
    kameleoonClient.addData(visitorCode, new KameleoonData.Device(KameleoonData.DeviceType.Desktop));
    
    NameTypeDescription
    deviceDeviceTypeList 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"));
    
    NameTypeDescription
    valuestringThe 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
    NameTypeDescription
    keystringThe key with which the data you are trying to retrieve is associated. This field is mandatory.
    Return value
    TypeDescription
    PromisePromise 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
    NameTypeDescription
    visitorCodestringThe 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
    NameTypeDescription
    handler() => voidThe 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
    NameTypeDescription
    visitorCodestringThe user's unique identifier. This field is mandatory.
    experimentIDnumberThe ID of the experiment you want to expose to a user. This field is mandatory.
    Return value
    NameTypeDescription
    variationIDnumberThe 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
    TypeDescription
    KameleoonException.NotTargetedException 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.NotActivatedException 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.ExperimentConfigurationNotFoundException 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
    NameTypeDescription
    variationIDintThe ID of the variation for which you want to obtain the associated data. This field is mandatory.
    Return value
    TypeDescription
    ObjectData associated with this variationID.
    Exceptions Thrown
    TypeDescription
    KameleoonException.VariationConfigurationNotFoundException 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
    TypeDescription
    ArrayList 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
    NameTypeDescription
    visitorCodestringThe user's unique identifier. This field is mandatory.
    onlyActivebooleanThe 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
    TypeDescription
    ArrayThe 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.

    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).