Passer au contenu principal
Vous pouvez exécuter des expériences et activer des feature flags avec le SDK NodeJS. L’intégration de notre SDK dans votre serveur est simple, et son empreinte (utilisation de la mémoire et du réseau) est faible. Notre SDK Node prend en charge Node version 16+ avec la possibilité de le rétrograder aux versions 14 et 12 en utilisant le mode de compatibilité. Premiers pas : pour obtenir de l’aide pour démarrer, consultez le guide du développeur. Méthodes du SDK : pour la documentation de référence complète du SDK NodeJS, consultez la reference section. Changelog : dernière version du SDK NodeJS : Changelog.
Avant de commencer l’installation de notre SDK NodeJS, nous vous recommandons de lire notre article sur les considérations techniques pour comprendre les concepts technologiques derrière nos SDK. Cet article vous aidera à assurer une intégration réussie.

Guide du développeur

Suivez cette section pour installer et configurer le SDK et en apprendre davantage sur les fonctionnalités avancées.

Premiers pas

Installation

Utilisez l’outil d’installation du SDK Kameleoon pour installer le SDK. L’installateur de SDK vous aide à installer le SDK de votre choix, à générer un exemple de code de base et à configurer les external dependencies if needed. Pour utiliser l’outil d’installation du SDK, installez-le et exécutez-le globalement :
npm install --global @kameleoon/sdk-installer
kameleoon-sdk
Ou exécutez-le directement avec npx:
npx @kameleoon/sdk-installer
Lors de l’utilisation de Deno, fournissez les dépendances manuellement dans deno.json:
deno.json
{
  "imports": {
    "@kameleoon/nodejs-sdk": "npm:@kameleoon/nodejs-sdk@^4.0",
    // -- Optional dependencies, can be implemented manually
    "@kameleoon/nodejs-requester": "npm:@kameleoon/nodejs-requester@^1.0",
    "@kameleoon/nodejs-event-source": "npm:@kameleoon/nodejs-event-source@^1.0",
    "@kameleoon/deno-visitor-code-manager": "npm:@kameleoon/deno-visitor-code-manager@^1.0",
  }
}

Initialisation du client Kameleoon

Les développeurs doivent créer un point d’entrée pour le SDK NodeJS en instanciant un nouveau KameleoonClient. Il est recommandé de traiter KameleoonClient comme un singleton, en créant une seule instance partagée et en la réutilisant dans toute l’instance du serveur pour garantir la cohérence et éviter une réinitialisation inutile. Utilisez KameleoonClient to run feature expériences et récupérer the status of feature flags et their variations. KameleoonClient s’initialise de manière asynchrone pour s’assurer que la communication avec l’API Kameleoon réussit, en utilisant la initialize() méthode. Vous pouvez utiliser async/await, Promise.then(), ou tout autre modèle asynchrone pour gérer l’initialisation du client.
Pour ajouter le SDK NodeJS à un environnement Edge, veuillez consulter this section.
import {
  Environment,
  KameleoonClient,
  SDKConfigurationType,
  CredentialsType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';

// -- Mandatory credentials
const credentials: CredentialsType = {
  clientId: 'my_client_id',
  clientSecret: 'my_client_secret',
};

// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
  updateInterval: 20,
  environment: Environment.Production,
  cookieDomain: '.example.com',
};

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials,
  configuration,
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

// -- Waiting for the client initialization using `async/await`
async function init(): Promise<void> {
  await client.initialize();
}

init();

// -- Waiting for the client initialization using `Promise.then()`
client
  .initialize()
  .then(() => {})
  .catch((error) => {});
Arguments
NameTypeDescription
siteCode (requis)stringIl s’agit de la unique key du projet Kameleoon que vous utilisez avec le SDK. Ce champ est obligatoire.
credentials (requis)CredentialsTypeidentifiants API, voir flux d’identifiants pour plus d’informations
externals (requis)ExternalsTypeimplémentation externe des dépendances du SDK (Dépendances externes)
configuration (facultatif)Partial<SDKConfigurationType>configuration du client
compatibility (facultatif)Compatibilitymode de compatibilité du SDK, voir Mode de compatibilité
integrations (facultatif)IntegrationTypeintégrations compute edge, voir Intégration avec les fournisseurs Edge
Exceptions levées
TypeDescription
KameleoonException.CredentialsLes identifiants client n’ont pas été fournis ou sont vides
Paramètres de configuration
NameTypeDescriptionValeur par défaut
updateInterval (facultatif)numberSpécifie l’intervalle de rafraîchissement, en minutes, auquel le SDK récupère la configuration pour les expériences et feature flags actifs. La valeur détermine le temps maximum nécessaire pour propager les changements, tels que l’activation ou la désactivation de feature flags ou le lancement d’expériences, vers vos serveurs de production. S’il n’est pas spécifié, l’intervalle par défaut est de 60 minutes. De plus, nous offrons un mode streaming qui utilise les server-sent events (SSE) pour pousser automatiquement les nouvelles configurations au SDK et les appliquer en temps réel, sans délai.60
environment (facultatif)Environment | stringenvironnement du feature flagEnvironment.Production
targetingDataCleanupInterval (facultatif)numberinterval in minutes pour le nettoyage des données de ciblage, la valeur minimale est de 1 minute30
cookieDomain (facultatif)stringdomain that le cookie belongs to.undefined
networkDomain (facultatif)stringLe custom domain le SDK uses in all outgoing network requests, commonly utilisé for proxying. Le format is second_level_domain.top_level_domain (par exemple, example.com). Le SDK uses the default Kameleoon value si le format is invalid.undefined
requestTimeout (facultatif)numbertimeout in milliseconds for all SDK network requests, if timeout is exceeded request will fail immediately10_000 (10 seconds)
trackingInterval (facultatif)numberSpecifies the interval for suivi requests in milliseconds. All visitors who were evaluated for any feature flag ou had associated data will be included in this suivi request. Le suivi request is performed once per interval. Le minimum value is 1_000 ms et le maximum value is 5_000 ms1_000 (1 second)
defaultDataFile (facultatif)stringLe defaultDataFile feature ensures the Kameleoon SDK is always READY by providing a fallback configuration when no cached data file exists. Developers can preload a valid configuration by fetching it from https://sdk-config.kameleoon.eu/v3/<sitecode> et passing it as defaultDataFile pendant initialization. When a dateModified timestamp (in milliseconds) is fourni et is newer than the cached version, le SDK will use the default datafile au lieu du cached version. If dateModified is omitted, the default datafile is uniquement appliqué when no cached version exists. This ensures le SDK always has a valid configuration, whether default, cached, ou updated.undefined
Option 1 (Recommended): Utilisez JSON.stringify()
const dataFileJson = {"configuration":{"consentType":.....,
    {"key":"show_car","type":"JSON","value":"{\"make\":\"Porsche\",\"model\":\"911\"}"}},
    "dateModified":1752209266000};
const dataFileString = JSON.stringify(dataFileJson);
const configuration = {
  updateInterval: 20,
  defaultDataFile: dataFileString
};
Option 2: Raw JSON string (escape special characters)
const configuration = {
  updateInterval: 20,
  defaultDataFile: `{"configuration":{"consentType":.....,
    {"key":"show_car","type":"JSON","value":"{\\"make\\":\\"Porsche\\",\\"model\\":\\"911\\"}"},
    "dateModified":1752209266000}`
};
Mode de compatibilité
Utilisez le SDK parameter compatibility to disable some of le SDK’s features to improve compatibility avec older NodeJS versions. Compatibility is an enum representing all possible mode de compatibilités:
  • Compatibility.Node16 - default mode, all features are enabled. This mode will be utilisé if no mode de compatibilité is provided. Supports Node version 16 et higher.
  • Compatibility.Node14 - compatibility avec this version will make the requestTimeout parameter in SDKConfigurationType unavailable et prevent le SDK from en utilisant AbortController for request cancellation, even dans default 10_000 ms timeout. Supports Node version 14 et higher.
  • Compatibility.Node12 - compatibility avec this version implies the même limitations as the Node14 mode de compatibilité. De plus, you cannot provide “@kameleoon/nodejs-requester” as a requester implementation in this mode de compatibilité, as it uses the “node-fetch” library, which doesn’t support the Node.js 12.x.x version. A developer must provide a custom requester implementation of their choice, tel que an older “node-fetch” version ou autre HTTP based implementation.

Activation d’un feature flag

Attribution d’un identifiant unique à un utilisateur
To assign a unique ID to a user, vous pouvez use the getVisitorCode() method. If a visitor code doesn’t exist (from la requête headers cookie), la méthode generates a random unique ID ou uses a defaultVisitorCode that you would have generated. Le ID is alors défini in a response headers cookie. Si vous êtes en utilisant Kameleoon in Hybrid mode, en appelant the getVisitorCode() method ensures that the unique ID (visitor code) is shared entre l’application file engine.js (previously named, kameleoon.js) et le SDK.
Récupération de la configuration d’un flag
To implémenter a feature flag in your code, vous devez first créer le feature flag in your Kameleoon account. To determine the status ou variation of a feature flag for a specific user, vous devriez use the getVariation() ou isFeatureFlagActive() method to récupérer la configuration basé sur le featureKey. Le getVariation() method gère les deux simple feature flags avec ON/OFF states et more complex flags avec multiple variations. Le method récupère the appropriate variation for l’utilisateur by checking the feature rules, assigning la variation, et retournant it basé sur le featureKey et visitorCode. Le isFeatureFlagActive() method can be utilisé si vous souhaitez récupérer la configuration of a simple feature flag that has uniquement an ON ou OFF state, as opposed to more complex feature flags avec multiple variations ou targeting options. If your feature flag has associated variables (tel que specific behaviors tied to chaque variation) getVariation() également active you to access the Variation object, which fournit details about the assigned variation et its associated expérience. Cette méthode vérifie whether l’utilisateur is targeted, finds le visiteur’s assigned variation, et saves it to storage. When track=true, le SDK will envoyer the exposure event vers le spécifié expérience sur le next suivi request, which is automatically déclenché basé sur le SDK’s tracking_interval_millisecond. Par défaut, this interval is défini to 1000 milliseconds (1 second). Le getVariation() method permet you to control whether suivi is done. If track=false, no exposure events will be envoyé by le SDK. Ceci est useful si vous prefer not to suivre data à travers le SDK et instead rely on client-side suivi managed par le Kameleoon engine, par exemple. De plus, définition track=false is helpful when en utilisant the getVariations() method, where you might uniquement need la variations for all flags sans triggering any suivi events. Si vous souhaitez know more about how suivi works, view this article
Ajout de points de données pour cibler un utilisateur ou filtrer/segmenter les visites dans les rapports
To target a user, ensure you’ve ajouté relevant data points to their profile avant retrieving the feature variation ou checking si le flag is active. Utilisez le addData() method to ajouter these data points to l’utilisateur’s profile. To récupérer data points collected on autre devices ou to access past user data (collected client-side when en utilisant Kameleoon in Hybrid mode), use the getRemoteVisitorData() method. Cette méthode asynchronously fetches data from le serveurs. Il est important de appel getRemoteVisitorData() before retrieving la variation ou checking if le feature flag is active, as this data might be requis to assign a user to a given variation. To learn more about available targeting conditions, voir la detailed article sur le subject. De plus, les données points you ajouter to le visiteur profile will be available when analyzing your expériences, allowing you to filter et break down your results by factors like device et browser. Kameleoon Hybrid mode automatically collects a variety of data points on le client-side, making it easy to break down your results basé sur lese pre-collected data points. Voir la complete list here. Si vous avez besoin de suivre additional data points beyond what’s automatically collected, vous pouvez use Kameleoon’s Custom Data feature. Custom Data permet you to capture et analyze specific information relevant to your expériences. Don’t forget to appel the flush() method to envoyer the collected data to Kameleoon servers for analysis.
To ensure your results are accurate, it’s recommended to filter out bots by en utilisant the UserAgent data type.
Suivi des conversions d’objectifs
When a user completes a desired action (tel que making a purchase), it is recorded as a conversion. To suivre conversions, use the trackConversion() method et provide the requis visitorCode et goalId parameters. Le conversion suivi request will be envoyé along avec le next scheduled suivi request, which le SDK envoie at regular intervals (defined by tracking_interval_millisecond). Si vous prefer to envoyer la requête immediately, use the flush() method avec le paramètre instant=true.
Envoi d’événements aux solutions d’analyse
To suivre conversions et envoyer exposure events to your customer analytics solution, vous devez first implémenter Kameleoon in Hybrid mode. Ensuite, use the getEngineTrackingCode() method. Le getEngineTrackingCode() method récupère the unique suivi code requis to envoyer exposure events to your analytics solution. Using this method permet you to record events et envoyer them to your desired analytics platform.

Gestion des erreurs

Presque chaque méthode KameleoonClient peut lever une erreur à un moment donné. Ces erreurs sont des KameleoonError délibérément prédéfinies qui étendent la classe native JavaScript Error, fournissant des messages utiles et un champ type spécial de type KameleoonException. KameleoonException est une énumération contenant tous les types d’erreurs possibles. Pour savoir exactement quel type de KameleoonException la méthode peut lever, consultez la section Throws de la description de la méthode, ou survolez la méthode dans votre IDE pour voir la description jsdocs. La gestion des erreurs est considérée comme une bonne pratique pour rendre votre application plus stable et éviter les problèmes techniques.
import {
  KameleoonError,
  KameleoonClient,
  KameleoonException,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  try {
    await client.initialize();

    const customData = new CustomData(0, 'my_data');
    client.addData(visitorCode, customData);
  } catch (error) {
    // -- Type guard for inferring error type, as native JavaScript `catch`
    //    only infers `unknown`
    if (error instanceof KameleoonError) {
      switch (error.type) {
        case KameleoonException.VisitorCodeMaxLength:
          // -- Handle an error
          break;
        case KameleoonException.StorageWrite:
          // -- Handle an error
          break;
        case KameleoonException.Initialization:
          // -- Handle an error
          break;
        default:
          break;
      }
    }
  }
}

init();

Intégration avec les fournisseurs Edge

Kameleoon fournit les starter packs suivants pour automatiser votre intégration avec des fournisseurs edge spécifiques :For autre edge providers, use External Dependencies for greater control over le SDK.

Expérimentation cross-device

To support visitors who access an app from multiple devices, Kameleoon permet the synchronization of previously collected visitor data across chaque of le visiteur’s devices et reconciliation of their visit history across devices à travers cross-device experimentation. Case studies et detailed information on how Kameleoon gère data across devices are available dans le article on cross-device experimentation.

Synchronisation des données personnalisées entre appareils

Although custom mapping synchronization est utilisé pour align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not requis: Same user ID across devices Si le même user ID is utilisé consistently across all devices, synchronization is géré automatically sans a custom mapping sync. It is enough to appel the getRemoteVisitorData() method lorsque vous want to sync les données collected entre multiple devices. Multi-server instances avec consistent IDs In complex setups involving multiple servers (par exemple, distributed server instances), where the même user ID is available across servers, synchronization entre servers (with getRemoteVisitorData()) is sufficient sans additional custom mapping sync. Customers who need additional data can reportez-vous à la getRemoteVisitorData() method description for further guidance. In the ci-dessous code, it is assumed that the même unique identifier (in this case, the visitorCode, which can également be referred to as userId) is utilisé consistently entre the two devices for accurate data retrieval.
Si vous souhaitez sync collected data in real time, vous avez besoin de choose the scope Visitor for your custom data.
Device One
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Custom Data with index `0` was set to `Visitor` scope
  //    in Kameleoon.
  const customDataIndex = 0;
  const customData = new CustomData(customDataIndex, 'my_data');

  client.addData('my_visitor', customData);
  client.flush();
}

init();
Device Two
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Before working with data, call `getRemoteVisitorData`.
  await getRemoteVisitorData({ visitorCode: 'my_visitor_code' });

  // -- New SDK code will have access to CustomData with `Visitor` scope
  //    defined on Device One.
  //    So, "my_data" is available to target and track "my_visitor".
}

init();

Utilisation des données personnalisées pour la fusion de sessions

L’expérimentation cross-device vous permet de combine a visitor’s history across chaque of their devices (history reconciliation). Vous pouvez merge multiple visitor sessions into one avec history reconciliation. Utilisez CustomData et provide a unique identifier for le visiteur to reconcile visit history.Follow the activating cross-device history reconciliation guide to défini up your custom data in Kameleoon.Vous pouvez use custom data in your code to merge a visitor’s session. Sessions avec le même identifier will always voir la même expérience variation, et will be displayed as a single visitor dans le Visitor view of your experiment’s result page.Le SDK configuration ensures that associated sessions always voir la même variation of l’expérience.Before en utilisant autre methods, inform le SDK that le visiteur is a unique identifier by ajout UniqueIdentifier data to a visitor.
Since the custom data you use as the identifier must be défini vers le Visitor scope, vous devez use cross-device custom data synchronization to récupérer the identifier avec le getRemoteVisitorData method on chaque device.
In l’exemple suivant, we have an application avec a login page. Since we don’t know l’utilisateur ID at the time of login, we use an anonymous visitor identifier generated par le getVisitorCode method. After l’utilisateur logs in, we can associate the anonymous visitor avec l’utilisateur ID et use it as a unique identifier for le visiteur.
Login Page
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  const anonymousVisitor = getVisitorCode();
  // -- Saving `visitorCode` in `global` to re-use it later.
  global.anonymousVisitor = anonymousVisitor;

  // -- Getting a variation, assume it's variation `A`.
  const variation = client.getVariation({
    visitorCode: anonymousVisitor,
    featureKey: 'my_feature_key',
  });
}

init();
Application Page
import { CustomData, UniqueIdentifier } from '@kameleoon/nodejs-sdk';

async function init(): Promise<void> {
  // -- At this point anonymous visitor has logged in,
  //    and we have a user ID to use as a visitor identifier
  // -- Associating both visitors with an identifier Custom Data,
  //    where index `1` is the Custom Data's index, configured
  //    as a unique identifier in Kameleoon.
  const userIdentifierData = new CustomData(1, 'my_user_id');
  // -- Taking `visitorCode` from `global` object
  client.addData(global.anonymousVisitor, userIdentifierData);
  // -- Flushing data for the anonymous `visitorCode`
  client.flush(global.anonymousVisitor);


  // -- Informing the SDK that the visitor is a unique identifier.
  client.addData('my_user_id', new UniqueIdentifier(true));

  // -- Retrieving the variation for the user ID ensures
  //   consistency with the anonymous visitor's variation.
  //   Both the anonymous visitor and the user ID will be
  //   assigned variation `A`.
  const variation = client.getVariation({
    visitorCode: 'my_user_id',
    featureKey: 'my_feature_key',
  });

  // -- `my_user_id` and `anonymousVisitor` are now linked.
  //    They can be tracked as a single visitor.
  client.trackConversion({
    visitorCode: 'my_user_id',
    goalId: 123,
    revenue: 100,
  });

  // -- Additionally, linked visitors share previously
  //    collected remote data.
  const data = await client.getRemoteVisitorData({
    visitorCode: 'my_user_id',
  });
}

init();

Utilisation d’une clé de bucketing personnalisée

Par défaut, Kameleoon uses a unique, anonymous visitor ID (visitorCode) to assign users to feature flag variations. This ID is typically generated et stored on l’utilisateur’s device (in a browser cookie for client-side et server-side SDKs—in persistent storage for mobile SDKs). Cependant, in certain scenarios vous pouvez need to ensure all users du même organization voir la même variant of a feature flag. Le Custom Bucketing Key option permet you to remplacer this default behavior by providing your own custom identifier for bucketing. This remplacer ensures that Kameleoon’s assignment logic uses your spécifié key au lieu du default visitorCode.

Cas d’utilisation

Utilisation d’une clé de bucketing personnalisée is essential for maintaining consistency et accuracy in your feature flag assignments, particularly in these situations:
  • Account-level ou organizational experiments: For B2B products ou scenarios where you want to assign all users du même organization vers le même variation, vous pouvez use an identifier like an accountId. Custom bucketing keys are crucial for A/B testing features that impact an entire team ou company.
By implementing a clé de bucketing personnalisée, you ensure greater consistency et accuracy in your expériences, leading to more reliable results et a better user experience.

Détails techniques

Lorsque vous configurer a clé de bucketing personnalisée for a feature flag, you provide Kameleoon avec a specific identifier from your application’s data:
client.addData(visitorCode, new CustomData(index, 'newVisitorCode'));
  • Providing the custom key: You provide your custom identifier vers le Kameleoon SDK en utilisant the addData() method. In this method, vous allez pass your chosen clé de bucketing personnalisée as a CustomData object. Here, newVisitorCode refers vers le identifier you wish to use for your bucketing (par exemple, the new userId ou accountId).
For the clé de bucketing personnalisée to function correctly, it must également be défini et configuré for le feature flag pendant the flag creation ou editing process. Without this corresponding configuration, le SDK’s bucketing will not appliquer your custom key. For detailed instructions on how to défini this up in Kameleoon, refer to this article.
  • Bucketing logic: Once a clé de bucketing personnalisée is fourni à travers the addData() method, all hash calculations for assigning users to variations will use this newVisitorCode (your custom key) au lieu du default visitorCode. Using the newVisitorCode means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
  • Data suivi et analytics: It’s crucial to note that while the newVisitorCode (your custom key) is utilisé for bucketing decisions, all subsequent data (tracking events et conversions, par exemple) is envoyé et associated avec le original visitorCode. This separation ensures that your analytics accurately reflect individual user journeys et interactions dans your experiment’s broader context, even when bucketing is performed at a higher level (like an account) ou across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.

Prérequis techniques

To effectively use a clé de bucketing personnalisée:
  • Le key must be a string.
  • It must be unique pour le entity you intend to bucket (par exemple, if en utilisant a userId, chaque user’s ID should be unique).
  • Le key must be available to le SDK at the exact moment le feature flag decision is evaluated for that user ou request.

Conditions de ciblage

Le Kameleoon SDKs support a variety of predefined targeting conditions that vous pouvez use to target users in your campaigns. For the list of conditions supported by this SDK, see use visit history to target users. Vous pouvez également use your own external data to target users.

Journalisation

Le SDK generates logs to reflect various internal processes et issues.

Niveaux de journal

Le SDK supports configuring limiting logging by a log level.
import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/nodejs-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });

// The `NONE` log level does not allow logging.
client.setLogLevel(LogLevel.NONE);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.NONE);


// The `ERROR` log level only allows logging issues that may affect the SDK's main behaviour.
client.setLogLevel(LogLevel.ERROR);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.ERROR);

// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
client.setLogLevel(LogLevel.WARNING);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.WARNING);

// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
client.setLogLevel(LogLevel.INFO);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.INFO);

// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);

Gestion personnalisée des journaux

Le SDK writes its logs vers le console output by default. This behaviour can be overridden.
Journalisation limiting by a log level is performed apart du log gestion logic.
import { KameleoonClient, KameleoonLogger, IExternalLogger, LogLevel } from '@kameleoon/nodejs-sdk';

export class CustomLogger implements IExternalLogger {
  // `log` method accepts logs from the SDK
  public log(level: LogLevel, message: string): void {
    // Custom log handling logic here. For example:
    switch (level) {
      case LogLevel.DEBUG:
        console.debug(message);
        break;
      case LogLevel.INFO:
        console.info(message);
        break;
      case LogLevel.WARNING:
        console.warn(message);
        break;
      case LogLevel.ERROR:
        console.error(message);
        break;
    }
  }
}

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    logger: new CustomLogger(),
  },
});

// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);

Informations de domaine

You provide a domain as the domain in KameleoonClient configuration, which is utilisé for storing Kameleoon visitor code in cookies. Providing a domain is important when working avec le getVisitorCode et setLegalConsent methods. Le domain you provide is stored in le cookie as the Domain= key.

Définition du domaine

Le domain you provide lets l’URL address use le cookie. Par exemple, if your domain is www.example.com, le cookie is uniquement available from a www.example.com URL. Pages avec le app.example.com domain can’t use le cookie. For more flexibility avec subdomains, vous pouvez spécifier a domain starting avec a .. For instance, domain .example.com permet le cookie to function on les deux app.example.com et login.example.com.
You can’t use regular expressions, special symbols, protocol, ou port numbers dans le domain. De plus, a specific list of subdomains cannot be utilisé avec le prefix ..
Here’s a small domain cheat sheet:
DomainAllowed URLsDisallowed URLs
www.example.comwww.example.comapp.example.com
example.com.com
.example.com = example.comexample.comotherexample.com
www.example.com
app.example.com
login.example.com
https://www.example.com⛔ bad domain⛔ bad domain
www.example.com:4408⛔ bad domain⛔ bad domain
.localhost.com = localhost⛔ bad domain⛔ bad domain

Développement sur localhost

localhost is always considered a bad domain, making it hard to test le domaine when developing on localhost. There are two ways to avoid this issue:
  • Don’t spécifier the domain field in le SDK client while testing. This prevents localhost issues (le cookie will be défini on any domain).
  • Créez a local domain for localhost. Par exemple :
    • Navigate to /etc/hosts on Linux ou to c:\Windows\System32\Drivers\etc\hosts on Windows
    • Open hosts avec file super user ou administrator rights
    • Ajoutez a domain vers le localhost port, par exemple: 127.0.0.1 app.com
    • Now, vous pouvez run your app locally on app.com:{my_port} et spécifier .app.com as your domain

Dépendances externes

Le SDK’s external dependencies use the dependency injection pattern, letting you provide your own implementations for certain parts of an SDK.
In the NodeJS SDK, some external dependencies have default implementations, while others must be fourni by l’utilisateur, whether en utilisant dedicated Kameleoon implementations ou custom implementations.
Here’s the list of available external dependencies:
DependencyInterfaceRequis/FacultatifAPI UsedDescription
storageIExternalStorageFacultatifServer memoryUsed for storing all du existing et collected SDK data
eventSourceIExternalEventSourceRequis-Used for receiving Server Sent Events for Real Time Updates capabilities
requesterIExternalRequesterRequis-Used for performing all network requests
visitorCodeManagerIExternalVisitorCodeManagerRequis-Used for storing et synchronizing visitor code
loggerILoggerFacultatifCustom implementationUsed for custom gestion of logs from le SDK. Lets users définir how logs are processed et where they output.
Vous pouvez également implémenter visitorCodeManager en utilisant the IExternalNextJSVisitorCodeManager, IExternalDenoVisitorCodeManager, ou IExternalCustomVisitorCodeManager interfaces for NextJS, Deno, ou custom visitor code manager implementations, respectively.
Dépendances externes provide developers flexibility to adapt et use the NodeJS SDK in any environment. There are un nombre of npm packages Kameleoon fournit for frequently utilisé environments. Vous pouvez install the packages manually, ou by en utilisant the SDK installation tool (recommended). These are the Kameleoon-provided external dependencies for NodeJS SDK:
  • @kameleoon/nodejs-event-source - based on eventsource library (can be utilisé for NodeJS/Deno/NextJS SSR)
  • @kameleoon/nodejs-requester - based on node-fetch library (can be utilisé for NodeJS/Deno/NextJS SSR)
  • @kameleoon/nodejs-visitor-code-manager - implémenté avec server memory storage
  • @kameleoon/deno-visitor-code-manager - implémenté en utilisant Deno request/response cookies
  • @kameleoon/nextjs-visitor-code-manager - implémenté en utilisant NextJS SSR headers cookie ou NextJS SSR request/response
Vous pouvez facultatifly implémenter external dependencies on your own. Le following example implémente external dependencies. To import an interface from an SDK, créer a class that implémente it et pass the instantiated class to le SDK.

Stockage

import { IExternalStorage, KameleoonClient } from '@kameleoon/nodejs-sdk';

// --- External Storage implementation ---
// - JavaScript `Map` is used as an example storage
const storage = new Map();

class MyStorage<T> implements IExternalStorage<T> {
  public read(key: string): T | null {
    // - Read data using `key`
    const data = storage.get(key);

    // - Return `null` if there's no data
    if (!data) {
      return null;
    }

    // - Return obtained data
    return data;
  }

  public write(key: string, data: T): void {
    // - Write data using `key`
    storage.set(key, data);
  }
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    storage: new MyStorage(),
  },
});

EventSource

import {
  IExternalEventSource,
  KameleoonClient,
  EventSourceOpenParametersType,
} from '@kameleoon/nodejs-sdk';

// --- External EventSource implementation ---
// - Example uses dummy `EventSource` class
class MyEventSource implements IExternalEventSource {
  private eventSource?: EventSource;

  public open({
    eventType,
    onEvent,
    url,
  }: EventSourceOpenParametersType): void {
    // - Initialize `EventSource` (use any event source of your choice here)
    const eventSource = new EventSource(url);

    this.eventSource = eventSource;
    // - Add event listener with provided event type and event callback
    this.eventSource.addEventListener(eventType, onEvent);
  }

  public close(): void {
    // - Clean up open event source
    if (this.eventSource) {
      this.eventSource.close();
    }
  }

  public onError(callback: (error: Event) => void): void {
    // - Set error callback
    if (this.eventSource) {
      this.eventSource.onerror = callback;
    }
  }
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    eventSource: new MyEventSource(),
  },
});

VisitorCodeManager

visitorCodeManager implementation for NodeJS/NextJS SSR:
import {
  IExternalVisitorCodeManager,
  SetDataParametersType,
  GetDataParametersType,
  KameleoonClient,
  KameleoonUtils,
} from '@kameleoon/nodejs-sdk';

// --- External Visitor Code Manager implementation ---
// - Example uses server `request` and `response`
class MyVisitorCodeManager implements IExternalVisitorCodeManager {
  public getData({ request, key }: GetDataParametersType): string | null {
    // - Get cookie from server request
    const cookieString = request.headers.cookie;

    // - Return `null` if no cookie was found
    if (!cookieString) {
      return null;
    }

    // - Parse cookie using the provided `key`
    return KameleoonUtils.getCookieValue(cookieString, key);
  }

  public setData({
    visitorCode,
    response,
    domain,
    maxAge,
    key,
    path,
  }: SetDataParametersType): void {
    // - Set cookie to request using provided parameters
    let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;

    if (domain) {
      resultCookie += `; Domain=${domain}`;
    }

    response.setHeader('Set-Cookie', resultCookie);
  }
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    visitorCodeManager: new MyVisitorCodeManager(),
  },
});
visitorCodeManager implementation for Deno:
import {
  IExternalDenoVisitorCodeManager,
  SetDenoDataParametersType,
  GetDenoDataParametersType,
  KameleoonClient,
  KameleoonUtils,
} from '@kameleoon/nodejs-sdk';

// --- External Visitor Code Manager implementation ---
// - Example uses server `request` and `response`
class MyVisitorCodeManager implements IExternalDenoVisitorCodeManager {
  public getData({ request, key }: GetDenoDataParametersType): string | null {
    // - Get cookie from server request
    const cookieString = request.headers.get('cookie');

    // - Return `null` if no cookie was found
    if (!cookieString) {
      return null;
    }

    // - Parse cookie using the provided `key`
    return KameleoonUtils.getCookieValue(cookieString, key);
  }

  public setData({
    visitorCode,
    response,
    domain,
    maxAge,
    key,
    path,
  }: SetDenoDataParametersType): void {
    // - Set cookie to request using provided parameters
    let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;

    if (domain) {
      resultCookie += `; Domain=${domain}`;
    }

    response.headers.set('Set-Cookie', resultCookie);
  }
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    visitorCodeManager: new MyVisitorCodeManager(),
  },
});
visitorCodeManager implementation for NextJS Server Actions:
import {
  IExternalNextJSVisitorCodeManager,
  SetNextJSDataParametersType,
  GetNextJSDataParametersType,
  KameleoonClient,
} from '@kameleoon/nodejs-sdk';

// --- External Visitor Code Manager implementation ---
// - Example uses server `cookies` object imported from "next/headers"
class MyVisitorCodeManager implements IExternalNextJSVisitorCodeManager {
  public getData({ cookies, key }: GetNextJSDataParametersType): string | null {
    // - Get cookie from server request by provided `key`
    const cookie = cookies().get(key);

    if (cookie) {
      return cookie.value;
    }

    // - Return `null` if no cookie was found
    return null;
  }

  public setData({
    visitorCode,
    cookie,
    domain,
    maxAge,
    key,
    path,
  }: SetNextJSDataParametersType): void {
    // - Set cookie to request using provided parameters
    cookies().set(key, visitorCode, {
      path,
      domain,
      maxAge,
    });
  }
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    visitorCodeManager: new MyVisitorCodeManager(),
  },
});
Custom visitorCodeManager implementation avec arbitrary parameters:
import {
  IExternalCustomVisitorCodeManager,
  SetDataCustomParametersType,
  GetDataCustomParametersType,
  KameleoonClient,
} from '@kameleoon/nodejs-sdk';

// --- External Visitor Code Manager implementation ---
// - Example uses custom arbitrary `input` and `output` objects
class MyVisitorCodeManager implements IExternalCustomVisitorCodeManager {
  public getData({ input, key }: GetDataCustomParametersType): string | null {
    // - Get visitor code from `input` object
    //   `input` is of type `unknown`, so you can provide any structure.
    //   In Example, we assume `input` is a `Map` object.
    const visitorCode = input.get(key);

    if (visitorCode) {
      return visitorCode;
    }

    // - Return `null` if no visitor code was found
    return null;
  }

  public setData({
    visitorCode,
    output,
    domain,
    maxAge,
    key,
    path,
  }: SetDataCustomParametersType): void {
    // - Set visitor code as a cookie to `output` object using provided parameters.
    let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;

    if (domain) {
      resultCookie += `; Domain=${domain}`;
    }

    // - `output` is of type `unknown`, so you can provide any structure.
    //   In Example, we assume `output` is a `Map` object.
    output.set(key, resultCookie);
  }
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    visitorCodeManager: new MyVisitorCodeManager(),
  },
});

Requester

import {
  RequestType,
  IExternalRequester,
  KameleoonResponseType,
  SendRequestParametersType,
  KameleoonClient,
} from '@kameleoon/nodejs-sdk';

// --- External Requester Implementation
export class MyRequester implements IExternalRequester {
  public async sendRequest({
    url,
    parameters,
  }: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
    // - Using native NodeJS `fetch` (for v18+)
    return await fetch(url, parameters);
  }
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
  siteCode: 'my_site_code',
  externals: {
    requester: new MyRequester(),
  },
});

Utilitaires

Le SDK has un ensemble de utility methods that vous pouvez use to simplify development. All methods are représenté as static members du KameleoonUtils class.

simulateSuccessRequest

Utilisez le simulateSuccessRequest method to simulate a successful request vers le Kameleoon server. Cette méthode can be useful for custom Requester implementations when a developer needs to simulate a successful request.
import {
  KameleoonUtils,
  IExternalRequester,
  SendRequestParametersType,
  RequestType,
  KameleoonResponseType,
} from '@kameleoon/nodejs-sdk';

// - Example of `Requester` with disabled tracking
class Requester implements IExternalRequester {
  public async sendRequest({
    url,
    parameters,
    requestType,
  }: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
    if (requestType === RequestType.Tracking) {
      return KameleoonUtils.simulateSuccessRequest<RequestType.Tracking>(
        requestType,
        null,
      );
    }

    return await fetch(url, parameters);
  }
}
Arguments
NameTypeDescription
requestType (requis)RequestTypeA type of request
data (requis)SimulateRequestDataType[RequestType]A type of request data, which is different depending on RequestType
Le SimulateRequestDataType data type is défini as follows:
  • RequestType.Tracking - null
  • RequestType.ClientConfiguration - ClientConfigurationDataType
  • RequestType.RemoteData - JSONType
Valeur de retour
TypeDescription
Promise<KameleoonResponseType>retourne une promesse avec la requête’s response

getCookieValue

Utilisez le getCookieValue method to parse a common cookie string (key_1=value_1; key_2=value_2; ...), et obtenir la valeur of a specific cookie key. Cette méthode is useful when working avec a custom implementation of VisitorCodeManager.
import { KameleoonUtils } from '@kameleoon/nodejs-sdk';

const cookies = 'key_1=value_1; key_2=value_2';
const key = 'key_1';

const value = KameleoonUtils.getCookieValue(cookies, key); // = `value_1`
Arguments
NameTypeDescription
cookie (requis)stringCookie string in form key_1=value_1; key_2=value_2
key (requis)stringString representation of une clé to find une valeur by
Valeur de retour
TypeDescription
`stringnull`retourne une chaîne avec a cookie value, ou null if la clé was not found

Référence

Il s’agit de la full reference documentation pour le Kameleoon JavaScript SDK.

Initialisation

initialize()

An asynchronous method for initializing KameleoonClient that récupère Kameleoon SDK data either from le serveur ou a local source if les données is encore up-to-date ou le mettre à jour interval has not yet elapsed.
import {
  KameleoonError,
  KameleoonClient,
  KameleoonException,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  try {
    await client.initialize();
  } catch (err) {
    if (err instanceof KameleoonError) {
      switch (err.type) {
        case KameleoonException.StorageWrite:
        // -- Handle error case
        case KameleoonException.ClientConfiguration:
        // -- Handle error case
        default:
          break;
      }
    }
  }
}

init();
Valeur de retour
TypeDescription
Promise<boolean>A promise resolved to un booléen indicating le SDK’s successful initialization. Generally, initialize() will throw une erreur if an unhandled issue occurs, so the boolean value will almost always be true et may not provide much useful information.
Exceptions levées
TypeDescription
KameleoonException.StorageWriteCouldn’t mettre à jour storage data
KameleoonException.ClientConfigurationCouldn’t récupérer client configuration from Kameleoon API
KameleoonException.MaximumRetriesReachedMaximum retries reached, request failed

Feature flags et variations

getVariation()

  • 📨 Sends Tracking Data to Kameleoon (selon le track parameter)
Retrieves the Variation assigned to a given visitor for a specific feature flag. Cette méthode prend featureKey as a obligatoire argument et track as an facultatif argument. Le track argument is facultatif et defaults to true. It retourne the assigned Variation for le visiteur. If le visiteur is not associated avec any feature flag rules, la méthode retourne the default Variation pour le given feature flag. Ensure that proper error gestion is implémenté in your code to manage potential exceptions.
Le default variation refers to la variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In autre words, it is the fallback variation appliqué to all users who are not targeted by specific rules. It’s représenté as la variation dans le “Ensuite, for everyone else…” section in a management interface.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code
  const visitorCode = client.getVisitorCode();

  // -- Get variation with tracking
  const variation = client.getVariation({
    visitorCode,
    featureKey: 'my_feature_key',
  });

  // -- Get variation without tracking
  const variation = client.getVariation({
    visitorCode,
    featureKey: 'my_feature_key',
    track: false,
  });

  // -- An Example variation:
  // {
  //  key: 'variation_key',
  //  id: 123,
  //  experimentId: 456,
  //  variables: Map {
  //    'variable_key' => {
  //      key: 'variable_key',
  //      type: VariableType.BOOLEAN,
  //      value: true,
  //    }
  //  },
  // }
}

init();
Arguments
An object of type GetVariationParamsType avec le following properties:
NameTypeDescriptionDefault
visitorCode (requis)stringUnique identifier of le visiteur.
featureKey (requis)stringKey du feature you want to expose to a visitor.
suivre (facultatif)booleanAn facultatif parameter to enable ou disable suivi du feature evaluation.true
Valeur de retour
TypeDescription
VariationAn assigned Variation to a given visitor for a specific feature flag.
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed it’s initialize call.
KameleoonException.VisitorCodeEmptyLe visitor code is empty.
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters).
KameleoonException.FeatureFlagConfigurationNotFoundException indicating that la requêteed feature key wasn’t found dans le internal configuration of le SDK. This usually means that le feature flag is not activated dans le Kameleoon app (but code implementing the feature is déjà deployed in l’application).
KameleoonException.FeatureFlagEnvironmentDisabledException indicating that feature flag is disabled for le visiteur’s current environment (par exemple, production, staging, ou development).

getVariations()

  • 📨 Sends Tracking Data to Kameleoon (selon le track parameter)
  • 🎯 Events: EventType.Evaluation
Retrieves a map of Variation objects assigned to a given visitor across all feature flags. Cette méthode iterates over all available feature flags et retourne the assigned Variation for chaque flag associated avec le spécifié visitor. It takes visitorCode as a obligatoire argument, while onlyActive et track are facultatif.
  • If onlyActive is défini to true, la méthode getVariations() will return feature flags variations fourni l’utilisateur is not bucketed avec le off variation.
  • Le track parameter controls whether ou not la méthode will suivre la variation assignments. Par défaut, it is défini to true. If défini to false, the suivi will be disabled.
Le retourné map consists of feature flag keys as keys et their corresponding Variation as values. If no variation is assigned for a feature flag, la méthode retourne the default Variation for that flag. Proper error gestion should be implémenté to manage potential exceptions.
Le default variation refers to la variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In autre words, it is the fallback variation appliqué to all users who are not targeted by specific rules. It’s représenté as la variation dans le “Ensuite, for everyone else…” section in a management interface.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code
  const visitorCode = client.getVisitorCode();

  // -- Get all feature flag variations with tracking
  const variations = client.getVariations({
    visitorCode,
  });

  // -- Get active feature flag variations with tracking
  const variations = client.getVariations({
    visitorCode,
    onlyActive: true,
  });

  // -- Get active feature flag variations without tracking
  const variations = client.getVariations({
    visitorCode,
    onlyActive: true,
    track: false,
  });

  // -- An Example variations:
  // Map {
  // 'feature_key' => {
  //    key: 'variation_key',
  //    id: 123,
  //    experimentId: 456,
  //    variables: Map {
  //      'variable_key' => {
  //        key: 'variable_key',
  //        type: VariableType.BOOLEAN,
  //        value: true,
  //      }
  //    },
  //   }
  // }
}

init();
Arguments
An object of type GetVariationsParamsType avec le following properties:
NameTypeDescriptionDefault
visitorCode (requis)stringUnique identifier of le visiteur.
onlyActive (facultatif)booleanAn facultatif parameter indicating whether to return variations for active (true) ou all (false) feature flags.false
suivre (facultatif)booleanAn facultatif parameter to enable ou disable suivi du feature evaluation.true
Valeur de retour
TypeDescription
Map<string, Variation>Map that contient the assigned Variation objects of le feature flags en utilisant la clés du corresponding features.
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed it’s initialize call.
KameleoonException.VisitorCodeEmptyLe visitor code is empty.
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters).

isFeatureFlagActive()

  • 📨 Sends Tracking Data to Kameleoon (selon le track parameter)
  • 🎯 Events: EventType.Evaluation
Le isFeatureFlagActive() method retourne un booléen indicating whether le visiteur avec visitorCode has an active featureKey. Cette méthode vérifie for targeting, finds la variation for le visiteur, et saves it to storage. Le method également envoie a suivi request. Cette méthode has an additional overload that lets you pass a track parameter, which disables the suivi of feature evaluation.
A visitor must be targeted for feature flags to activate.
Kameleoon uses suivi to count sessions et visitors lorsque vous appel certain methods, tel que isFeatureFlagActive(), getVariation() ou getVariations().Utilisez le default true value pour le track parameter lorsque vous expose visitors to a variation et need to count them. Définissez the track parameter to false uniquement si vous appel these methods avant you expose visitors.Par exemple, si vous appel getVariations() to récupérer all variations avant you expose visitors, défini the track parameter to false. This définition prevents Kameleoon from prematurely counting a session. Vous pouvez alors déclencher suivi later lorsque vous explicitly expose le visiteur.Kameleoon envoie suivi data chaque second by default. Vous pouvez configurer this interval up to five seconds en utilisant the suivi interval configuration option. Kameleoon groups suivi events into a single session as long as the interval entre events is less than 30 minutes. If more than 30 minutes elapse entre suivi events, Kameleoon counts l’événements as separate sessions. A visit appears in your reports 30 minutes après the last recorded event in la session.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code using server `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });

  // -- Add CustomData with index `0` containing visitor id to check the targeting
  client.addData(visitorCode, new CustomData(0, 'visitor_id'));

  // -- Check if the feature flag is active for visitor
  const isActive = client.isFeatureFlagActive(visitorCode, 'my_feature_key');

  // -- Check if the feature flag is active for visitor without tracking
  const isActive = client.isFeatureFlagActive({ visitorCode, featureKey: 'my_feature_key', track: false});
}

init();
Le isFeatureFlagActive() method evaluates the served variant, not the master flag state. Si vous exclude rules, la méthode uses the Ensuite, for everyone else serve default state. Si vous select Off for this default state, la méthode always retourne false even lorsque le master feature flag is On.
Arguments
There are two overloads available for this method:
  1. Two parameters overload:
This overload is deprecated et will be supprimé dans le next major version. Please use the new overload avec un objet parameter.
NameTypeDescription
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters length
featureKey (requis)stringa unique key for feature flag
  1. Object parameter overload of type IsFeatureFlagActiveParamsType:
NameTypeDescriptionDefault
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length-
featureKey (requis)stringa unique key for a feature flag-
suivre (facultatif)booleanun booléen indicator of whether to suivre the feature evaluationtrue
Valeur de retour
TypeDescription
booleanun booléen indicator of whether le feature flag avec featureKey is active for le visiteur avec visitorCode
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found for fourni featureKey
KameleoonException.FeatureFlagVariableNotFoundNo feature variable were found for fourni visitorCode et variableKey
KameleoonException.DataInconsistencyAllocated variation was found, mais there is no feature flag avec le according featureKey.

setForcedVariation()

Le method permet you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. Ceci est especially valuable for controlled expériences where the usual evaluation logic is not requis ou must be skipped. It can également be helpful in scenarios like debugging ou custom testing. When a forced variation is set, it remplace Kameleoon’s real-time evaluation logic. Processes like segmentation, targeting conditions, et algorithmic calculations are skipped. To preserve segmentation et targeting conditions pendant an expérience, défini forceTargeting=false instead.
Simulated variations always take precedence dans le execution order. If a simulated variation calculation is triggered, it will be fully processed et completed first.
A forced variation is treated the même as an evaluated variation. It is suivi in analytics et stored in l’utilisateur context like any standard evaluated variation, ensuring consistency in reporting. Le method may throw exceptions under certain conditions (e.g., invalid parameters, user context, ou internal issues). Proper exception gestion is essential to ensure that your application remains stable et resilient.
It’s important to distinguish forced variations from simulated variations:
  • Forced variations: Are specific to an individual expérience.
  • Simulated variations: Affect the overall feature flag result.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code
  const visitorCode = client.getVisitorCode();

  // -- Forcing the variation "on" for the "featureKey1" feature flag for the visitor.
  client.setForcedVariation({
    visitorCode: visitorCode,
    experimentId: 9516,
    variationKey: 'on',
    forceTargeting: false,
  });

  // -- Resetting the forced variation for the "featureKey1" feature flag for the visitor.
  client.setForcedVariation({
    visitorCode: visitorCode,
    experimentId: 9516,
    variationKey: null,
  });
}

init();
Arguments
An object of type SetForcedVariationParametersType avec le following properties:
NameTypeDescriptionDefault
visitorCode (requis)stringUnique identifier of le visiteur.
experimentId (requis)numberExperiment Id that will be targeted et selected pendant the evaluation process.
variationKey (requis)`stringnull`Variation Key corresponding to a Variation that should be forced as the retourné value for l’expérience. If la valeur is null, the forced variation will be reset.
forceTargeting (facultatif)booleanIndicates whether targeting for l’expérience should be forced et skipped (true) ou appliqué as dans le standard evaluation process (false).true
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeEmptyLe visitor code is empty.
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters).
KameleoonException.InitializationIndicates that le SDK is not yet fully initialized.
KameleoonException.FeatureFlagExperimentNotFoundException indicating that la requêteed expérience id has not been found in le SDK’s internal configuration. Ceci est usually normal et means that the rule’s corresponding expérience has not yet been activated on Kameleoon’s side.
KameleoonException.FeatureFlagVariationNotFoundException indicating that la requêteed variation key(id) has not been found dans le internal configuration of le SDK. Ceci est usually normal et means that la variation’s corresponding expérience has not yet been activated on Kameleoon’s side.
KameleoonException.StorageReadCouldn’t read storage data.
KameleoonException.StorageWriteCouldn’t mettre à jour storage data.
In most cases, uniquement the basic error, KameleoonException, needs to be handled, as demonstrated in l’exemple. Cependant, if different types of errors require a response, gérer chaque one separately based on specific requirements. De plus, for enhanced reliability, general language errors can be géré by incluant Error.

evaluateAudiences()

  • 📨 Sends Tracking Data to Kameleoon
Cette méthode evaluates visitors against all available Audiences Explorer segments et suit those who match. evaluateAudiences() should be appelé after all relevant visitor data has been défini ou updated, et just before getting a feature variation ou checking a feature flag. This approach ensures that le visiteur is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria. After en appelant this method, vous pouvez perform a detailed analysis of segment performance in Audiences Explorer.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code
  const visitorCode = client.getVisitorCode();

  client.evaluateAudiences(visitorCode);
}

init();
Arguments
NameTypeDescription
visitorCode (requis)stringUnique identifier of le visiteur.
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed it’s initialize call.
KameleoonException.VisitorCodeEmptyLe visitor code is empty.
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters).
In most cases, uniquement the basic error, KameleoonException, needs to be handled, as demonstrated in l’exemple. Cependant, if different types of errors require a response, gérer chaque one separately based on specific requirements. De plus, for enhanced reliability, general language errors can be géré by incluant Error.

getDataFile()

To evaluate all feature flags, use getVariations(). Cette méthode is more efficient than en appelant DataFile et iterating à travers flags avec getVariation().
Retourne the current SDK configuration as a DataFile object.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

const dataFile = client.getDataFile();
Valeur de retour
TypeDescription
DataFileLe DataFile contenant le SDK configuration

Données du visiteur

getVisitorCode()

Le getVisitorCode method récupère a visitor code from la requête’s cookie dans le headers. If le visiteur code does not exist, la méthode generates a new random visitor code, ou uses a fourni defaultVisitorCode value. It alors définit the new visitor code in a cookie in la réponse headers. Cette méthode utilizes Node.js’s native types for request et response, specifically IncomingMessage et ServerResponse, imported du http module. Cependant, if you’re en utilisant the Express framework, Deno, ou Next.js super server-rendering methods, like getServerProps, le types for request et response will differ. Vous pouvez resolve this issue en utilisant type casting, which will yield identical results.
When en utilisant getVisitorCode() avec Deno, Next.js SSR, Node, ou Express, ensure that you’ve implémenté the correct external dependencies.
Le getVisitorCode() method permet you to défini simulated variations for a visitor. When cookies (from a request ou document) contain la clé kameleoonSimulationFFData, the standard evaluation process is bypassed. Instead, la méthode directly retourne a Variation basé sur le fourni data.Vous pouvez appliquer simulations in two ways:
  • Automatically (recommended): If en utilisant Kameleoon Web Experimentation ou le SDK in Hybrid mode, le cookie is créé automatically when simulating a variant’s display en utilisant the Simulation Panel.
  • Manually: Définissez the kameleoonSimulationFFData cookie manually.
It’s important to distinguish simulated variations from forced variations:
  • Simulated variations: Affect the overall feature flag result.
  • Forced variations: Are specific to an individual expérience.
⚙️ Manual setupPlease ensure the kameleoonSimulationFFData cookie follows this format:
  • kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates la variation avec varId of expérience expId pour le given featureKey.
  • kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined dans le Ensuite, for everyone else in Production, serve section) pour le given featureKey.
⚠️ To ensure proper functionality, le cookie value must be encoded as a URI component en utilisant une méthode tel que encodeURIComponent.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code using native `NodeJS/NextJS/Deno` `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });

  // -- Get visitor code using `Express`/`Deno`/`NextJS` SSR methods' `request`, `response`, and optionally providing
  //    default visitor code
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
    defaultVisitorCode: 'my_default_visitor_code',
  });

  // -- Get visitor code using `NextJS` server side actions
  //    (`cookies` imported from "next/headers")
  const visitorCode = client.getVisitorCode({
    cookies,
  });

  // -- Get visitor code using custom `VisitorCodeManager` implementation
  //    `myInput` and `myOutput` are custom input and output parameters with arbitrary types.
  //    According types should be defined in `VisitorCodeManager` implementation.
  const visitorCode = client.getVisitorCode({
    input: myInput,
    output: myOutput,
  });
}

init();
Arguments
Le parameters object is overloaded avec two types:
  • Type GetVisitorCodeParametersType (for NodeJS/Express/NextJS SSR methods), contenant the following fields:
NameTypeDescription
request (requis)IncomingMessageserver request
response (requis)ServerResponseserver response
defaultVisitorCode (facultatif)stringvisitor code to be utilisé if is no visitor code in le cookies
  • Type GetNextJSVisitorCodeParametersType (for NextJS SSR server actions), contenant the following fields:
NameTypeDescription
cookies (requis)typeof 'next/headers' cookiesNextJS server actions headers cookie
defaultVisitorCode (facultatif)stringvisitor code to be utilisé if is no visitor code available in le cookies
  • Type GetDenoVisitorCodeParametersType (for Deno), contenant the following fields:
NameTypeDescription
request (requis)DenoMessageserver request
response (requis)DenoMessageserver response
defaultVisitorCode (facultatif)stringdefault visitor code that le SDK uses when there is no visitor code in le cookies
  • Type GetCustomVisitorCodeParametersType (for custom VisitorCodeManager implementation), contenant the following fields:
NameTypeDescription
input (requis)unknownarbitrary input object from which you want to read le visiteur code
output (requis)unknownarbitrary output object to which you want to write le visiteur code
defaultVisitorCode (facultatif)stringvisitor code to be utilisé in case there is no visitor code in le cookies
Si vous don’t provide a defaultVisitorCode et there is no visitor code stored in a cookie, le visiteur code will be randomly generated.
Valeur de retour
TypeDescription
stringresult visitor code
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel
KameleoonException.VisitorCodeMaxLengthLe maximum visitor code length was exceeded (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty

addData()

Utilisez le addData() method to ajouter targeting data to storage so autre methods can utilize this information to determine whether to target the current visitor. Le addData() method does not return any value, et does not directly interact avec le Kameleoon back-end servers. Instead, all data la méthode collects is saved for future transmission en utilisant the flush() method. This approach minimizes the number of server calls, as data is generally grouped into a single server appel that is activated par le flush() method. De plus, the trackConversion() method transmits any previously associated data. Le getFeatureFlagVariationKey() et getFeatureFlagVariable() methods transmit data when an experimentation rule is triggered.
Each visitor can uniquement have one instance of associated data for most data types; however, CustomData is an exception, as visitors can have one instance of associated CustomData for chaque customDataIndex.
Vérifiez the list of supported conditions to voir la data types vous pouvez use for targeting.
import {
  KameleoonClient,
  BrowserType,
  CustomData,
  Browser,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Create Kameleoon Data Types
  const browserData = new Browser(BrowserType.Chrome);
  const customData = new CustomData(0, 'my_data');

  // -- Add a single data item (tracked by default)
  client.addData('my_visitor_code', browserData);

  // -- Add multiple data items (tracked by default)
  client.addData('my_visitor_code', browserData, customData);

  // -- Add multiple data items from array (tracked by default)
  const dataArr = [browserData, customData];
  client.addData('my_visitor_code', ...dataArr);

  // -- Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
  client.addData({visitorCode: 'my_visitor_code', track: false, data: dataArr});
}

init();
Arguments
NameTypeDescriptionValeur par défaut
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters.
suivre (facultatif)booleanSpecifies whether the ajouté data is eligible for tracking. When défini to false, les données is stored locally et utilisé uniquement for targeting evaluation; it is not envoyé vers le Kameleoon Data API.true
kameleoonData (facultatif)KameleoonDataType[]number of instances of any type of KameleoonData, can be ajouté solely in array ou as sequential arguments
  • kameleoonData is a variadic argument: it can be passed as one ou plusieurs arguments (voir la example).
  • Le custom data’s index ou ID can be found in your Kameleoon account. Notez que this index starts at 0, meaning the first custom data you créer for a given site will be assigned 0 as its ID, rather than 1.
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.StorageWriteCouldn’t mettre à jour storage data
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel
Vérifiez the data types reference for more details on how to manage different data types.

flush()

flush() takes the Kameleoon data associated avec le visiteur et schedules les données to be envoyé avec le next suivi request. Le time du next suivi request is défini in le SDK Configuration’s trackingInterval parameter. Vous pouvez ajouter visitor data en utilisant the addData() et getRemoteVisitorData() methods.Le SDK will envoyer all of its stored data vers le remote Kameleoon servers si vous don’t spécifier a visitorCode. De plus, if there were any suivi requests that previously failed et were stored locally in offline mode, le SDK will attempt to envoyer those stored requests avant processing the latest request.
Si vous avez besoin de envoyer suivi requests immediately, use flushInstant() — the asynchronous version of flush that retourne Promise<void>. Vous pouvez await it lorsque vous need delivery guarantees (par exemple, avant ending a request/response cycle), ou appel it sans await as a fire-and-forget request:
  • await client.flushInstant(visitorCode) envoie suivi requests immediately for a specific visitor et waits for completion
  • await client.flushInstant() envoie suivi requests immediately for all visitors et waits for completion
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code using server `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });

  const customData = new CustomData(0, 'my_data');
  client.addData(visitorCode, customData);

  // -- Flush added custom data for visitor
  client.flush(visitorCode);

  // -- Instantly flush added custom data for visitor
  client.flush({ visitorCode, instant: true });

  // -- Flush data for all the visitors
  client.flush();

  // -- Instantly flush data for all the visitors
  client.flush({ instant: true });
}

init();
Arguments
NameTypeDescriptionDefault
visitorCode (facultatif)stringunique visitor identification string, can’t exceed 255 characters, if not passed, all data will be flushed (sent vers le remote Kameleoon servers).-
Or un objet avec le type FlushParamsType, containing:
NameTypeDescriptionDefault
visitorCode (facultatif)stringunique visitor identification string, can’t exceed 255 characters, if not passed, all data will be flushed (sent vers le remote Kameleoon servers).-
instant (facultatif)booleanBoolean flag indicating whether les données should be envoyé instantly (true) ou selon le scheduled suivi interval (false).-
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel

getRemoteData()

Le getRemoteData() method récupère data that is stored on a remote Kameleoon server for a spécifié site code. For instance, vous pouvez use this method to access user preferences, historical data, ou any autre information pertinent to your application’s logic. By storing this data on our highly scalable servers en utilisant our Data API, vous pouvez efficiently manage large volumes of data et récupérer it for chaque of your visitors ou users.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Get remote data
  const jsonData = await getRemoteData('my_data_key');

  const data = JSON.parse(jsonData);
}

init();
Arguments
NameTypeDescription
key (requis)stringthe unique key avec which the récupéré data is associated
Valeur de retour
TypeDescription
JSONTypepromise avec data récupéré for specific key
Exceptions levées
TypeDescription
KameleoonException.RemoteDataCouldn’t récupérer data from Kameleoon server

getRemoteVisitorData()

Le getRemoteVisitorData() method is an asynchronous function that récupère Kameleoon Visits Data for a specific visitorCode du Kameleoon Data API. Cette méthode stores les données so that it can be accessed when making targeting decisions.Le data obtained à travers this method is crucial lorsque vous want to:
  • Access data collected from multiple devices.
  • Review a user’s history, incluant pages visited pendant previous sessions.
  • Utilize client-side data, tel que data layer variables et objectifs that are uniquement applicable sur le front end.
For a better understanding of potential use cases, please read this article.
Par défaut, getRemoteVisitorData() récupère the latest stored custom data avec scope=Visitor et attaches it to le visiteur sans the need to appel la méthode addData(). This feature is particularly useful for synchronizing custom data across multiple devices.
import {
  KameleoonClient,
  KameleoonDataType,
  VisitorDataFiltersType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Get remote visitor data and add it to storage.
  const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
    visitorCode: 'my_visitor_code',
  });

  // -- Get remote visitor data without adding it to storage.
  const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
    visitorCode: 'my_visitor_code',
    shouldAddData: false,
  });

  // -- Get remote visitor data without adding it to storage,
  //    and customizing filters for retrieving visits data.
  const filters: VisitorDataFiltersType = {
    currentVisit: true,
    previousVisitAmount: 10,
    customData: true,
    geolocation: true,
    conversions: true,
  };

  const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
    visitorCode: 'my_visitor_code',
    shouldAddData: false,
    filters,
  });
}

init();
Arguments
An object avec le type RemoteVisitorDataParamsType, containing:
NameTypeDescriptionValeur par défaut
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length-
shouldAddData (facultatif)booleanboolean flag identifying whether the récupéré custom data should be ajouté to storage automatically (without en appelant addData afterwards)true
filters (facultatif)VisitorDataFiltersTypefilters for specifying what data should be récupéré from visits, by default, uniquement customData is récupéré du current et latest previous visit{ previousVisitAmount: 1, currentVisit: true customData: true }, autre filters parameters are défini to false
Valeur de retour
TypeDescription
KameleoonDataType[]promise avec list of Kameleoon Data récupéré
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.RemoteDataCouldn’t récupérer data from Kameleoon server
KameleoonException.VisitAmountVisit amount must be un nombre entre 1 et 25
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel
Utilisation des paramètres dans getRemoteVisitorData()
Le getRemoteVisitorData() method fournit flexibility by letting you définir various parameters when retrieving visitor data. Cette méthode can target data based on objectifs, expériences, ou variations, et le même approach applique to all data types.Par exemple, si vous souhaitez récupérer data on visitors who completed l’objectif “Order transaction,” vous pouvez spécifier parameters dans le getRemoteVisitorData() method to refine your targeting. If you’re interested in users who converted on l’objectif pendant their last five visits, vous pouvez défini the previousVisitAmount parameter to 5 et conversions to true.Le flexibility shown in this example is not limited to objectif data. Vous pouvez use parameters dans the getRemoteVisitorData() method to récupérer data on a variety of visitor behaviors.
Here is the list of available VisitorDataFiltersType filters:
NameTypeDescriptionDefault
previousVisitAmount (facultatif)numberNumber of previous visits from which to récupérer data. Number entre 1 et 251
currentVisit (facultatif)booleanIf true, current visit data will be récupérétrue
customData (facultatif)booleanIf true, custom data will be retrieved.true
pageViews (facultatif)booleanIf true, page data will be retrieved.false
geolocation (facultatif)booleanIf true, geolocation data will be retrieved.false
device (facultatif)booleanIf true, device data will be retrieved.false
browser (facultatif)booleanIf true, browser data will be retrieved.false
operatingSystem (facultatif)booleanIf true, operating system data will be retrieved.false
conversions (facultatif)booleanIf true, conversion data will be retrieved.false
expériences (facultatif)booleanIf true, expérience data will be retrieved.false
kcs (facultatif)booleanIf true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on.false
visitorCode (facultatif)booleanIf true, Kameleoon will récupérer the visitorCode du most recent visit et use it pour le current visit. This retrieval is necessary si vous souhaitez ensure that le visiteur, identified by their visitorCode, always receives the même variation across visits for Expérimentation cross-device.true
personalization (facultatif)booleanIf true, personalization data will be retrieved. Ceci est requis pour le personalization conditionfalse
cbs (facultatif)booleanIf true, Contextual Bandit score data will be retrieved.false

getVisitorWarehouseAudience()

Le getVisitorWarehouseAudience method is asynchronous et récupère all audience data related to a visitor from your data warehouse. To use this method, you’ll need to provide a visitorCode et a warehouseKey, which typically correspond to your internal user ID. Le customDataIndex parameter refers vers le custom data Kameleoon uses to target your visitors. Pour plus de détails, reportez-vous à the warehouse targeting documentation.
import {
  KameleoonClient,
  KameleoonDataType,
  CustomData,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor warehouse audience data using `warehouseKey`
  //    and add it to storage.
  const customData: CustomData = await getVisitorWarehouseAudience({
    visitorCode: 'my_visitor',
    customDataIndex: 10,
    warehouseKey: 'my_key',
  });

  // -- Get visitor warehouse audience data using `visitorCode`
  //    and add it to storage.
  const customData: CustomData = await getVisitorWarehouseAudience({
    visitorCode: 'my_visitor',
    customDataIndex: 10,
  });
}

init();
Arguments
Paramètres object consisting of:
NameTypeDescription
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length
customDataIndex (requis)numbernumber representing the custom data’s index you want to use to target your Warehouse Audiences
warehouseKey (facultatif)stringunique key identifying the warehouse data (usually your internal user ID)
Valeur de retour
TypeDescription
Promise<CustomData | null>promise contenant CustomData avec le associated warehouse data, ou null if there was no data
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.RemoteDataCouldn’t récupérer data from Kameleoon server

setLegalConsent()

When gestion legal consent, it’s important you use the getVisitorCode method du KameleoonClient class, plutôt que le deprecated method from KameleoonUtils. Notez que this method does not require the domain as an argument. Instead, vous devriez pass the domain vers le KameleoonClient constructor. Reportez-vous à la example ci-dessus for clarification.
Le method setLegalConsent determines whether a visitor has fourni legal consent for their personal data’s use. Si vous défini the legalConsent parameter to false, it restricts le types of data vous pouvez include in suivi requests. This measure ensures that you comply avec legal et regulatory requirements while responsibly managing visitor data. For more information on personal data, reportez-vous à la consent management policy.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
});

async function init(): Promise<void> {
  await client.initialize();

  const visitorCode = client.getVisitorCode();
  client.setLegalConsent({
    visitorCode,
    consent: true,
    response, // or cookies or output, depending on the environment
  });
}

init();
Arguments
Le parameters object is overloaded avec les types suivants:
  • Type SetLegalConsentParametersType (for NodeJS/Express/NextJS SSR methods), contenant the following fields:
NameTypeDescription
visitorCode (requis)stringunique visitor identification string. Can’t exceed 255 characters in length
consent (requis)booleanun booléen value representing the legal consent status. true indicates le visiteur has given legal consent, false indicates le visiteur has never fourni ou withdrawn legal consent
response (requis)ServerResponseserver response
  • Type SetNextJSLegalConsentParametersType (for NextJS SSR server actions), contenant the following fields:
NameTypeDescription
visitorCode (requis)stringunique visitor identification string. Can’t exceed 255 characters in length
consent (requis)booleanun booléen value representing the legal consent status. true indicates le visiteur has given legal consent, false indicates le visiteur has never fourni ou withdrawn legal consent
cookies (requis)typeof 'next/headers' cookiesNextJS server actions headers cookie
  • Type SetDenoLegalConsentParametersType (for Deno), contenant the following fields:
NameTypeDescription
visitorCode (requis)stringunique visitor identification string. Can’t exceed 255 characters in length
consent (requis)booleanun booléen value representing the legal consent status. true indicates le visiteur has given legal consent, false indicates le visiteur has never fourni ou withdrawn legal consent
response (requis)DenoMessageserver response
  • Type SetCustomLegalConsentParametersType (for custom VisitorCodeManager implementation), contenant the following fields:
NameTypeDescription
visitorCode (requis)stringunique visitor identification string. Can’t exceed 255 characters in length
consent (requis)booleanun booléen value representing the legal consent status. true indicates le visiteur has given legal consent, false indicates le visiteur has never fourni ou withdrawn legal consent
output (requis)unknownarbitrary output object to which you want to write le visiteur code
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeMaxLengthLe visitor code length exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
Comportement de révocation du consentement
Lorsque vous appel setLegalConsent() avec consent=false, le SDK does not supprimer the kameleoonVisitorCode cookie. Instead, it stops extending le cookie’s expiration date, allowing le cookie to persist until it naturally expires. If your compliance requirements demand the immediate removal of le cookie file upon opt-out, vous devez supprimer it manually en utilisant your framework’s native cookie management methods. Le SDK will not supprimer le fichier automatically.

Objectifs et analyses tierces

trackConversion()

  • 📨 Sends Tracking Data to Kameleoon
Utilisez ce method to suivre a conversion for a specific goal et user. Cette méthode nécessite visitorCode et goalId. De plus, this method également accepts an facultatif revenue, negative et metadata arguments. Le visitorCode is usually identical vers le one that was utilisé when triggering l’expérience.Le trackConversion() method doesn’t return any value. Cette méthode is non-blocking as le serveur appel is made asynchronously.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code using server `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });

  // -- Track conversion
  client.trackConversion({
    visitorCode,
    revenue: 20000,
    goalId: 123,
    metadata: [new CustomData(0, 'value')],
    negative: true,
  });
}

init();
Arguments
Paramètres object consisting of:
NameTypeDescriptionDefault
visitorCode (requis)stringUnique identifier of le visiteur.
goalId (requis)numberID of l’objectif.
negative (facultatif)booleanDefines si le revenue is positive ou negative.false
revenue (facultatif)numberRevenue of la conversion.0
metadata (facultatif)CustomData[]Metadata of la conversion. Must be défini beforehand dans le Kameleoon App.undefined
metadatune valeurs are accessible à travers raw data exports et le résultats page.Si le metadata parameter is provided, Kameleoon will use these spécifié values pour le current conversion instead of what was previously collected en utilisant the addData() method. If le paramètre is omitted, Kameleoon will use the last suivi values for those CustomData prior to la conversion et dans the même visit.Kameleoon will uniquement consider the metadatune valeurs that are explicitly passed as parameters vers le trackConversion() method.In l’exemple below, Kameleoon will associate la conversion uniquement avec le custom datune valeur explicitly fourni as a parameter (here: index 5 avec la valeur ‘Amex Credit Card’).
kameleoonClient.addData(visitorCode, new CustomData(5, 'Credit Card'), new CustomData(9, 'Express Delivery'));
kameleoonClient.trackConversion({
    visitorCode,
    goalId: 1000,
    metadata: [new CustomData(5, 'Amex Credit Card')]
});
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters).
KameleoonException.VisitorCodeEmptyLe visitor code is empty.
KameleoonException.StorageWriteCouldn’t mettre à jour storage data.

getEngineTrackingCode()

Kameleoon integrates avec plusieurs analytics solutions, incluant Mixpanel, Google Analytics 4, et Segment. To suivre server-side expériences correctly, appel the getEngineTrackingCode() method après le visiteur déclenche an expérience. Le SDK retourne JavaScript queue commands for l’expériences that le visiteur déclenché pendant the previous five seconds. Lorsque vous insert this code into la page, Engine.js processes the commands et envoie the exposure events à travers the active analytics integration. Refer to hybrid experimentation pour plus d’informations on implementing this method.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Trigger feature experiment
  // -- E.g., result `variationKey` id is `200`, and implicit experiment id is `100`
  client.getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });

  // -- Get tracking code
  const engineCode = client.getEngineTrackingCode('visitor_code');

  // -- Result engine code will look like this
  // `
  // window.kameleoonQueue = window.kameleoonQueue || [];
  // window.kameleoonQueue.push(['Experiments.assignVariation', 100, 200, true]);
  // window.kameleoonQueue.push(['Experiments.trigger', 100, true]);
  // `
}

init();
  • To use this feature, implémenter les deux the NodeJS SDK et Kameleoon Engine.js. Because Engine.js is utilisé uniquement for suivi in this flow, vous pouvez install the asynchronous tag avant the closing </body> tag.
  • Vous pouvez insert the retourné suivi code directly into an HTML <script> tag.
<html lang="en">
  <body>
    <script>
      const engineTrackingCode = `
        window.kameleoonQueue = window.kameleoonQueue || [];
        window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
        window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
        window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
        window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
      `;
      const script = document.createElement('script');

      script.textContent = engineTrackingCode;
      document.body.appendChild(script);
    </script>

  </body>
</html>
In this example, 123456 et 234567 are expérience IDs, et 7890 et 8901 are variation IDs. In your implementation, le SDK generates these values dans le retourné suivi code.
Arguments
NameTypeDescription
visitorCode (requis)stringUnique identifier of le visiteur.
Valeur de retour
TypeDescription
stringJavaScript code to insert into la page.
Exceptions levées
TypeDescription
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty

Events

onEvent()

Le onEvent() method fires un callback when a specific event is triggered. Le callback function accesses les données associated avec l’événement. Le SDK methods in this documentation note which event types they trigger, if any.
Vous pouvez uniquement assign one callback to chaque EventType.
import {
  KameleoonClient,
  EventType,
  EvaluationEventDataType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Define logic that will execute on SDK event
  client.onEvent(EventType.Evaluation, (eventData: EventDataType) => {
    // -- My Logic
  });
}

init();
Events
Events are défini dans le EventType enum. Le eventData parameter will have a different type basé sur le event type.
TypeeventData typeDescription
EventType.EvaluationEvaluationEventDataTypeTriggered when le SDK evaluates any variation for a feature flag. Le event is déclenché regardless of le résultat variation
EventType.ConfigurationUpdateConfigurationUpdateEventDataTypeTriggered when le SDK receives a configuration mettre à jour from le serveur (when en utilisant real-time streaming)
Arguments
NameTypeDescription
event (requis)EventTypea type of l’événement to associate the callback action avec
callback (requis)(eventData: EventDataType<EventType>) => voidun callback function avec le eventData parameter that is appelé when a configuration mettre à jour occurs
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel

Types de données

Kameleoon Types de données are helper classes utilisé for storing data in predefined forms. During the flush() execution, le SDK collects all data et envoie it along avec le suivi request. Data available in le SDK is not available for targeting et reporting dans le Kameleoon app until you ajouter les données (par exemple, by en utilisant the addData() method). See use visit history to target users pour plus d’informations.
Si vous êtes en utilisant Kameleoon in hybrid mode, vous pouvez appel getRemoteVisitorData() to automatically fill all data that Kameleoon previously collected.

Browser

Browser contient browser information.
Each visitor can uniquement have one Browser. Adding a second Browser overwrites the first one.
NameTypeDescription
browser (requis)BrowserTypepredefined browser type (Chrome, InternetExplorer, Firefox, Safari, Opera, Other)
version (facultatif)numberversion of le navigateur, floating point number représente major et minor version of le navigateur
import { KameleoonClient, BrowserType, Browser } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add new browser data to client
  const browser = new Browser(BrowserType.Chrome, 86.1);
  client.addData('my_visitor_code', browser);
}

init();

UniqueIdentifier

UniqueIdentifier data is utilisé for unique visitor identification. Si vous ajouter UniqueIdentifier for a visitor, visitorCode is utilisé as the unique visitor identifier, which is useful for Expérimentation cross-device. Linking a UniqueIdentifier to a visitor informs le SDK that this visitor is associated avec un autre visitor. Le UniqueIdentifier parameter can be beneficial in certain edge cases. Par exemple, si vous can’t access the anonymous visitorCode initially assigned to a visitor mais have an internal ID linked à travers session merging, this parameter is useful.
Each visitor can uniquement have one UniqueIdentifier. Adding un autre UniqueIdentifier overwrites the first one.
NameTypeDescription
value (requis)booleanvalue that spécifie if le visiteur is associated avec un autre visitor, fourni false will imply that le visiteur is not associated avec any autre visitor
import { KameleoonClient, UniqueIdentifier } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add a unique identifier to a visitor
  client.addData('my_visitor_code', new UniqueIdentifier(true));
}

init();

Conversion

Le Conversion data défini stored ici peut être utilisé pour filter expérience et personalization reports by any objectif associated avec it.
  • Each visitor can have multiple Conversion objects.
  • Vous pouvez find the goalId dans le Kameleoon app.
ConversionParametersType conversionParamètres - un objet avec conversion parameters described below
NameTypeDescriptionDefault
goalId (requis)numberID of l’objectif.
revenue (facultatif)floatRevenue of la conversion0
negative (facultatif)booleanDefines si le revenue is positive ou negative.false
metadata (facultatif)CustomData[]Metadata of la conversion.undefined
import {
  KameleoonClient,
  ConversionParametersType,
  Conversion,
  CustomData,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Defined conversion parameters
  const conversionParameters: ConversionParametersType = {
    goalId: 123,
    revenue: 10000,
    negative: true,
    metadata: [new CustomData(0, 'value')],
  };

  // -- Add new conversion data to client
  const conversion = new Conversion(conversionParameters);
  client.addData('my_visitor_code', conversion);
}

init();
Cookie contient information about le cookie stored on le visiteur’s device. Le NodeJS SDK doesn’t require a request ou response to extract le cookie. Instead, ajouter le cookie manually en utilisant Cookie data.
Each visitor can uniquement have one Cookie. Adding a second Cookie overwrites the first one.
NameTypeDescription
cookie (requis)CookieType[]A list of CookieType objects consisting of cookie keys et values
import { KameleoonClient, CookieType, Cookie } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add new cookie data to client
  const cookieData: CookieType[] = [
    { key: 'key_1', value: 'value_1' },
    { key: 'key_2', value: 'value_2' },
  ];
  const cookie = new Cookie(cookieData);
  client.addData('my_visitor_code', cookie);
}

init();
Méthodes
Cookie data has a static utility method, fromString, that can help you créer a cookie by parsing une chaîne that contient valid cookie data. Le method accepts string as a parameter, et retourne an initialized Cookie instance.
import { Cookie } from '@kameleoon/nodejs-sdk';

const cookieString = 'key_1=value_1; key_2=value_2';
const cookie: Cookie = Cookie.fromString(cookieString);

// -- The result cookie will contain the following cookie array
// [
//    { key: 'key_1', value: 'value_1' },
//    { key: 'key_2', value: 'value_2' },
// ]

GeolocationData

GeolocationData contient le visiteur’s geolocation details.
Each visitor can uniquement have one GeolocationData. Adding a second GeolocationData overwrites the first one.
An object parameter avec le type GeolocationInfoType contient the following fields:
NameTypeDescription
country (requis)stringLe visitor’s country
region (facultatif)stringLe visitor’s region
city (facultatif)stringLe visitor’s city
postalCode (facultatif)stringLe visitor’s postal code
coordinates (facultatif)[number, number]Coordinates array tuple of two location values (longitude et latitude). Coordinate number représente decimal degrees
import {
  KameleoonClient,
  GeolocationData,
  GeolocationInfoType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add geolocation data
  const geolocationInfo: GeolocationInfoType = {
    country: 'France',
    region: 'Île-de-France',
    city: 'Paris',
    postalCode: '75008',
    coordinates: [48.8738, 2.295],
  };
  const geolocationData = new GeolocationData(geolocationInfo);
  client.addData('my_visitor_code', geolocationData);
}

init();

CustomData

CustomData permet any type of data to be easily associated avec chaque visitor. It can alors be utilisé as a targeting condition in segments ou as a filter/breakdown in expérience reports. To learn more about custom data, veuillez consulter this article. To maintain the custom data in future visits, le SDK envoie CustomData avec le Visitor scope avec le next suivi request. Vous pouvez défini the scope dans le custom data dashboard.
NameTypeDescriptionDefault
index/name (requis)number/stringIndex ou Name du custom data. Either index ou name must be provided to identify les données.
overwrite (facultatif)booleanFlag to explicitly control how la valeurs are stored et how they appear in reports. See moretrue
value (requis)string[]Le custom datune valeur. It must be stringified to match the string type. Remarque : value is variadic.
  • Each visitor is permis uniquement one CustomData for chaque unique index. Adding un autre CustomData avec le même index will replace the existing one.
  • Le custom data ‘index’ can be found dans le Custom Data dashboard under the “INDEX” column.
  • To prevent le SDK from envoi data avec le selected index to Kameleoon servers for privacy reasons, enable the option: Utilisez ce data uniquement locally for targeting purposes when creating custom data.
  • Adding a CustomData instance créé avec a name when le SDK instance is not initialized ou le nom is not registered, will result in les données being ignored.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  const dataItemOne = 'abc';
  const dataItemTwo = JSON.stringify(100);
  const dataItemThree = JSON.stringify({ a: 200, b: 300 });

  const customDataIndex = 0;

  // -- Create custom data using single parameter
  const customData = new CustomData(customDataIndex, dataItemOne);

  // -- Create custom data using overwrite flag
  const customData = new CustomData(customDataIndex, false, dataItemOne);

  // -- Create custom data using name instead of index
  const customData = new CustomData('customDataName', dataItemOne);

  // -- Create custom data using variadic number of parameters
  const customData = new CustomData(customDataIndex, dataItemOne, dataItemTwo);

  // -- Create custom data using an array of values
  const dataList = [dataItemOne, dataItemTwo, dataItemThree];
  const customData = new CustomData(customDataIndex, ...dataList);

  // -- Create custom data using overwrite flag
  const customData = new CustomData(customDataIndex, false, ...dataList);

  // -- Create custom data using name instead of index
  const customData = new CustomData('customDataName', false, ...dataList);

  // -- Add custom data
  client.addData('my_visitor_code', customData);
}

init();

Device

Device contient information about your device.
Each visitor can uniquement have one Device. Adding a second Device overwrites the first one.
NameTypeDescription
deviceType (requis)DeviceTypepossible types for device type (PHONE, TABLET, DESKTOP)
import { KameleoonClient, DeviceType, Device } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add device data
  const device = new Device(DeviceType.Desktop);
  client.addData('my_visitor_code', device);
}

init();

OperatingSystem

OperatingSystem contient information about le visiteur’s operating system.
Each visitor can uniquement have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.
NameTypeDescription
operatingSystem (requis)OperatingSystemTypepossible types for device type: WINDOWS_PHONE, WINDOWS, ANDROID, LINUX, MAC, IOS
import {
  KameleoonClient,
  OperatingSystem,
  OperatingSystemType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add operating system data
  const operatingSystem = new OperatingSystem(OperatingSystemType.Windows);
  client.addData('my_visitor_code', operatingSystem);
}

init();

PageView

PageView contient information about your web page.
Each visitor can have one PageView per unique URL. Adding a PageView avec le même URL notifies le SDK that le visiteur revisited la page.
PageViewParametersType pageViewParamètres - un objet avec page view parameters described below
NameTypeDescription
urlAddress (requis)stringurl address of la page to suivre
title (requis)stringtitle du web page
referrer (facultatif)number[]an facultatif parameter contenant une liste de referrers indices, has no default value
Vous pouvez find the referrer’s index ou ID in your Kameleoon account. Notez que this index starts at 0, meaning the first acquisition channel you créer for a given site will be assigned 0 as its ID, not 1.
import {
  KameleoonClient,
  PageViewParametersType,
  PageView,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Define page view parameters
  const pageViewParameters: PageViewParametersType = {
    urlAddress: 'www.example.com',
    title: 'my example',
    referrers: [123, 456],
  };

  // -- Add page view data
  const pageView = new PageView(pageViewParameters);
  client.addData('my_visitor_code', pageView);
}

init();

UserAgent

UserAgent stores information on le visiteur’s user-agent. Server-side expériences are more vulnerable to bot traffic than client-side expériences. To address this, Kameleoon uses the IAB/ABC International Spiders et Bots List to identify known bots et spiders. Kameleoon également uses the UserAgent field to filter out bots et autre unwanted traffic that could otherwise skew your conversion metrics. Pour plus de détails, consultez the help article on bot filtering. Si vous use internal bots, we suggest you pass la valeur curl/8.0 of l’utilisateurAgent to exclude them from our analytics.
A visitor can uniquement have one UserAgent. Adding a second UserAgent overwrites the first one.
NameTypeDescription
value (requis)stringvalue utilisé for comparison
Server-side expériences are more vulnerable to bot traffic than client-side expériences. To address this, Kameleoon uses the IAB/ABC International Spiders et Bots List to identify known bots et spiders. We recommend that you pass l’utilisateur agent to be filtered by Kameleoon when running server-side expériences for chaque visitor browsing your website, to avoid counting bots in your analytics.Si vous use internal bots, we suggest that you pass la valeur curl/8.0 of l’utilisateurAgent to exclude them from our analytics.
import { KameleoonClient, UserAgent } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add user agent data
  const userAgent = new UserAgent('my_unique_value');
  client.addData('my_visitor_code', userAgent);
}

init();

ApplicationVersion

ApplicationVersion représente the semantic version number of your application.
A visitor can have uniquement one ApplicationVersion. Adding a second instance will overwrite the first one.
NameTypeDescription
version (facultatif)stringLe mobile application version. Ce champ must follow semantic versioning. Accepted formats are major, major.minor, ou major.minor.patch.
import { KameleoonClient, ApplicationVersion } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Add application version
  const applicationVersion = new ApplicationVersion('1.2');
  client.addData('my_visitor_code', applicationVersion);
}

init();

Types retournés

DataFile

Le DataFile contient le SDK configuration details. It can be extended avec additional information if requis by clients. Si vous need more details, please contact your Customer Success Manager.
NameTypeDescription
featureFlagsMap<string, FeatureFlag>A map of FeatureFlag objects, keyed by feature flag keys.
dateModifiednumberLe timestamp (in milliseconds) indicating lorsque le DataFile was last modified.
import { FeatureFlag } from '@kameleoon/nodejs-sdk';

// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
const featureFlags: Map<string, FeatureFlag> = dataFile.featureFlags;

// Retrieves the last modification timestamp of the DataFile.
// The value is a number representing milliseconds since the Unix epoch.
const dateModified: number = dataFile.dateModified;

FeatureFlag

Le FeatureFlag représente un ensemble de properties that définir a feature flag itself — par exemple, its Variations, Rules, environment status, et autre related details. It can be extended avec additional information if requis by clients. Si vous need more details, please contact your Customer Success Manager.
NameTypeDescription
environmentEnabledbooleanIndicating whether le feature flag is activé dans le current environment.
defaultVariationKeystringLe key du default variation associated avec le feature flag.
variationsMap<string, Variation>A map of Variation objects, keyed by variation keys.
rulesRule[]A list of Rule objects
import { Variation, Rule } from '@kameleoon/nodejs-sdk';

// Check whether the feature flag is enabled in the current environment
const isEnvironmentEnabled: boolean = featureFlag.environmentEnabled;

// Retrieve the key of the default variation
const defaultVariationKey: string = featureFlag.defaultVariationKey;

// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation> = featureFlag.variations;

// Retrieve all targeting rules associated with the feature flag
const rules: Rule[] = featureFlag.rules;

Rule

Le Rule représente un ensemble de properties that définir a rule itself — par exemple, its Variations. It can be extended avec additional information if requis by clients. Si vous need more details, please contact your Customer Success Manager.
NameTypeDescription
variationsMap<string, Variation>A map of Variation objects, keyed by variation keys.
import { Variation } from '@kameleoon/nodejs-sdk';

// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation>  = rule.variations;

Variation

Variation contient information about the assigned variation to le visiteur (or the default variation, if no specific assignment exists).
NameTypeDescription
namestringname of la variation.
keystringkey of la variation.
idnumber ou nullid of la variation ou null if le visiteur landed sur le default variation.
experimentIdnumber ou nullid of l’expérience ou null if le visiteur landed sur le default variation.
variablesMap<string, Variable>map of variables for la variation, where key is the variable key et value is the variable object.
  • Ensure that your code gère the case where id ou experimentId may be null, indicating a default variation.
  • Le variables map might be empty if no variables are associated avec la variation.
// Retrieving the variation name
const variationName = variation.name;

// Retrieving the variation key
const variationKey = variation.key;

// Retrieving the variation id
const variationId = variation.id;

// Retrieving the experiment id
const experimentId = variation.experimentId;

// Retrieving the variables map
const variables = variation.variables;

Variable

Variable contient information about a variable associated avec le assigned variation.
NameTypeDescription
keystringLe unique key identifying the variable.
typestringLe type du variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS.
valueanyLe value du variable, which can be of les types suivants: boolean, number, String, Record<string, any>, any[].
// Retrieving the variables map
const variables = variation.variables;

// Variable type can be retrieved for further processing
const type = variables.get('isDiscount')?.type || '';

// Retrieving the variable value by key
const isDiscount = variables.get('isDiscount')?.value || false;

// Variable value can be of different types
const title = variables.get('title')?.value || '';

Aides Edge

These helper methods are primarily intended for short-lived ou edge-style runtimes where le SDK may need explicit revalidation entre requests.

refreshDataFileIfStale()

Le refreshDataFileIfStale() method déclenche a data file revalidation uniquement lorsque le current configuration is stale. If les données file is encore valid et le last mettre à jour happened less than the configuré updateInterval ago, la méthode retourne false et no mettre à jour request is made. If les données file is stale, la méthode waits pour le revalidation request to finish et retourne true when la requête was performed. Returning true means that the vérifier was executed, mais la configuration itself may encore remain unchanged, par exemple when le serveur reports that the current data file is déjà up to date.
In a typical long-lived Node.js runtime, en utilisant this method is generally not recommended, because le SDK déjà keeps les données file fresh automatically pendant initialization et normal runtime execution. It can encore be helpful in edge-style environments tel que Cloudflare Workers, where runtime behavior is more short-lived et revalidation may need to be déclenché explicitly.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Revalidate the data file only if the current configuration is stale
  const dataFileRevalidated = await client.refreshDataFileIfStale();
}

init();
Valeur de retour
TypeDescription
Promise<boolean>true if an mettre à jour request was performed, false si le current data file is encore valid et no request was made.

Méthodes obsolètes

These methods are deprecated et will be supprimé dans le next major update.

getFeatureFlagVariationKey()

Utilisez le getVariation method instead.
Le getFeatureFlagVariationKey() method récupère la variation key pour le spécifié visitorCode dans le corresponding feature flag. Cette méthode inclut a targeting check, finding the appropriate variation exposed to le visiteur, saving it to storage, et envoi a suivi request.
If a user has not been previously assigned a variation key for le feature flag, le SDK will randomly determine a variation basé sur le feature flag’s rules. If l’utilisateur is déjà linked to le feature flag, le SDK will return their previously assigned variation key. If l’utilisateur does not meet any du spécifié rules, the default value défini in Kameleoon’s feature flag delivery rules will be returned. This default value is not always a variation key—it can également be un booléen ou un autre data type, selon le feature flag’s configuration.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code using server `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });

  // -- Add CustomData with index `0` containing visitor id to check the targeting
  client.addData(new CustomData(0, 'visitor_id'));

  // -- Get visitor feature flag variation key
  const variationKey = client.getFeatureFlagVariationKey(
    visitorCode,
    'my_feature_key',
  );
}

init();
Arguments
NameTypeDescription
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length
featureKey (requis)stringa unique key for a feature flag
Valeur de retour
TypeDescription
stringune chaîne contenant the variable key for le visiteur’s allocated feature flag.
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant initialize was completed for kameleoonClient
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found pour le spécifié featureKey
KameleoonException.FeatureFlagEnvironmentDisabledFeature flag is disabled pour le current environment

getVisitorFeatureFlags()

Utilisez le getVariations method instead.
Le getVisitorFeatureFlags() method retourne une liste de feature flags that are active for le visiteur avec le spécifié visitorCode, ensuring that le visiteur is allocated one of la variations.
  • 🚫 Doesn’t envoyer Tracking Data to Kameleoon
  • 🎯 Events: EventType.Evaluation (for chaque feature flag)
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code using server `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });

  // -- Get active feature flags for visitor
  const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}

init();
Cette méthode uniquement collects le visiteur’s active feature flags, meaning le résultat excludes all feature flags for which le visiteur is assigned the off (default ou control) variation.Par exemple :
// -- `getVisitorFeatureFlags` doesn't trigger feature experiments;
//    it only returns feature flags where visitors didn't get the `off` variation.
client.getVisitorFeatureFlags('my_visitor').forEach(({ key }) => {
  // -- `getFeatureFlagVariationKey` triggers a feature experiment,
  //    as `off` is already filtered out - visitors will never take part
  //    in an experiment where the `off` variation was allocated.
  client.getFeatureFlagVariationKey('my_visitor', key);
});
Utilisez getFeatureFlags lorsque vous need all of le visiteur’s feature flags:
// -- Both `off` and other variations are processed as expected.
client.getFeatureFlags('my_visitor').forEach(({ key }) => {
  client.getFeatureFlagVariationKey('my_visitor', key);
});
Arguments
NameTypeDescription
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length
Valeur de retour
TypeDescription
FeatureFlagType[]list of feature flags, chaque feature flag item contient id et key
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.StorageReadError while reading storage data

getActiveFeatureFlags()

  • 🚫 Doesn’t envoyer Tracking Data to Kameleoon
  • 🎯 Events: EventType.Evaluation (for chaque feature flag)
Utilisez le getVariations method instead.
Le getActiveFeatureFlags() method retourne a Map, where la clé représente the feature key, et la valeur contient detailed information about le visiteur’s variation et its variables.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code
  const visitorCode = client.getVisitorCode();

  // -- Get active feature flags for visitor
  //    with detailed variation and variables data
  const activeFeatures = client.getActiveFeatureFlags(visitorCode);

  // -- Result example:
  // Map {
  //   'feature-key-one' => {
  //     id: 100,
  //     key: 'variation-key-one',
  //     experimentId: 200,
  //     variables: [
  //      { key: 'variable_bool', type: VariableType.Boolean, value: true },
  //     ]
  //   },
  //   'feature-key-two' => {
  //     id: null, // -> `null` because it is default variation
  //     key: 'default-variation-key',
  //     experimentId: null, // -> `null` because it is default variation
  //     variables: []
  //   }
  // }
}

init();
Cette méthode uniquement collects le visiteur’s active feature flags, meaning le résultat excludes all feature flags for which le visiteur is assigned the off (default ou control) variation.Voir la getVisitorFeatureFlags method’s CAUTION section for more details.
Arguments
NameTypeDescription
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length
Valeur de retour
TypeDescription
Map<string, KameleoonVariationType>a map of feature flags, where key is feature key et value is detailed information about le visiteur’s variation et its variables
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.StorageReadError while reading storage data
KameleoonException.NumberParseCouldn’t parse Number value
KameleoonException.JSONParseCouldn’t parse JSON value

getFeatureFlagVariable()

Utilisez le getVariation method instead.
Le getFeatureFlagVariable() method récupère a variable for le visiteur basé sur le visitorCode dans the identified feature flag. Cette méthode inclut a targeting check, determines the appropriate variation for le visiteur, saves it to storage, et envoie a suivi request.
import {
  KameleoonClient,
  VariableType,
  JSONType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

 // -- Get visitor code using server `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });


  // -- Get feature variable
  const result = client.getFeatureFlagVariable({
    visitorCode,
    featureKey: 'my_feature_key'
    variableKey: 'my_variable_key'
  });

  // -- Infer the type of a variable by its `type`
  switch (result.type) {
    case VariableType.BOOLEAN:
      const myBool: boolean = result.value;
      break;
    case VariableType.NUMBER:
      const myNum: number = result.value;
      break;
    case VariableType.JSON:
      const myJson: JSONType = result.value;
      break;
    case VariableType.STRING:
    case VariableType.JS:
    case VariableType.CSS:
      const myStr: string = result.value;
      break;
    default:
      break;
  }
}

init();
Arguments
Paramètres object of type GetFeatureFlagVariableParamsType contenant the following fields:
NameTypeDescription
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length
featureKey (requis)stringa unique key for a feature flag
variableKey (requis)stringvariable’s key for a feature flag avec fourni featureKey, can be found in Kameleoon
Valeur de retour
TypeDescription
FeatureFlagVariableTypeis a variable object contenant type et value fields. Vous pouvez vérifier the type field against the VariableType enum. Par exemple, si le type is VariableType.BOOLEAN, the value is a boolean type.
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant initialize was completed for kameleoonClient
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found pour le spécifié featureKey
KameleoonException.FeatureFlagEnvironmentDisabledFeature flag is disabled pour le current environment
KameleoonException.JSONParseCouldn’t parse JSON value
KameleoonException.NumberParseCouldn’t parse Number value

getFeatureFlagVariables()

Utilisez le getVariation method instead.
Le getFeatureFlagVariables() method récupère une liste de variable values for a spécifié visitor et feature flag. Cette méthode vérifie if l’utilisateur is targeted, identifies le visiteur’s assigned variation, stores it, et envoie a suivi request.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Get visitor code using server `request` and `response`
  const visitorCode = client.getVisitorCode({
    request: req,
    response: res,
  });

  // -- Get a list of variables for the visitor under `visitorCode` in the feature flag
  const variables = client.getFeatureFlagVariables(
    visitorCode,
    'my_feature_key',
  );
}

init();
Arguments
NameTypeDescription
visitorCode (requis)stringunique visitor identification string, can’t exceed 255 characters in length
featureKey (requis)stringa unique key for le feature flag
Valeur de retour
TypeDescription
FeatureVariableResultType[]une liste de variable objects contenant key, type et value fields. Vous pouvez vérifier the type field against the VariableType enum. Par exemple, si le type is VariableType.BOOLEAN alors value will be a boolean type.
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel
KameleoonException.VisitorCodeMaxLengthLe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyLe visitor code is empty
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found pour le spécifié featureKey
KameleoonException.FeatureFlagVariationNotFoundNo feature variation was found pour le spécifié visitorCode et variationKey
KameleoonException.FeatureFlagEnvironmentDisabledFeature flag is disabled pour le current environment
KameleoonException.JSONParseCouldn’t parse JSON value
KameleoonException.NumberParseCouldn’t parse Number value

onConfigurationUpdate()

Utilisez le onEvent method avec EventType.ConfigurationUpdate instead.
Le onConfigurationUpdate() method fires un callback upon client configuration update.
Cette méthode is uniquement applicable to server-sent events for real-time updates.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});


async function init(): Promise<void> {
  await client.initialize();

  // -- Define logic that will execute on client configuration update
  client.onConfigurationUpdate(() => {
    // -- My Logic
  });
}

init();
Arguments
NameTypeDescription
callback (requis)() => voidcallback function avec no parameters that will be appelé upon configuration mettre à jour
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel

getFeatureFlags()

Utilisez le getDataFile() method instead.
🚫 Doesn’t envoyer Tracking Data to Kameleoon Le getFeatureFlags() method récupère une liste de feature flags that are stored in le client configuration.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';

const client = new KameleoonClient({
  siteCode: 'my_site_code',
  credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
  externals: {
    visitorCodeManager: new KameleoonVisitorCodeManager(),
    eventSource: new KameleoonEventSource(),
    requester: new KameleoonRequester(),
  },
});

async function init(): Promise<void> {
  await client.initialize();

  // -- Get all feature flags
  const featureFlags = client.getFeatureFlags();
}

init();
Valeur de retour
TypeDescription
FeatureFlagType[]list of feature flags, chaque feature flag item contient id et key
Exceptions levées
TypeDescription
KameleoonException.InitializationMethod was executed avant the kameleoonClient completed its initialize appel