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. Exemple Next.js : Pour des exemples d’intégration du SDK NodeJS avec Next.js, notamment App Router, Pages Router, middleware et server actions, consultez le dépôt de starter kits Next.js.
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 :
Ou exécutez-le directement avec npx:
Lors de l’utilisation de Deno, fournissez les dépendances manuellement dans deno.json:
deno.json

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.
Arguments
Exceptions levées
Paramètres de configuration
Option 1 (Recommended): Utilisez JSON.stringify()
Option 2: Raw JSON string (escape special characters)
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.

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
Device Two

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
Application Page

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:
  • 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.

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.

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:

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:
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

EventSource

VisitorCodeManager

visitorCodeManager implementation for NodeJS/NextJS SSR:
visitorCodeManager implementation for Deno:
visitorCodeManager implementation for NextJS Server Actions:
Custom visitorCodeManager implementation avec arbitrary parameters:

Requester

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.
Arguments
Le SimulateRequestDataType data type is défini as follows:
  • RequestType.Tracking - null
  • RequestType.ClientConfiguration - ClientConfigurationDataType
  • RequestType.RemoteData - JSONType
Valeur de retour

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.
Arguments
Valeur de retour

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.
Valeur de retour
Exceptions levées

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.
Arguments
An object of type GetVariationParamsType avec le following properties:
Valeur de retour
Exceptions levées

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.
Arguments
An object of type GetVariationsParamsType avec le following properties:
Valeur de retour
Exceptions levées

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.
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.
  1. Object parameter overload of type IsFeatureFlagActiveParamsType:
Valeur de retour
Exceptions levées

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.
Arguments
An object of type SetForcedVariationParametersType avec le following properties:
Exceptions levées
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.
Arguments
Exceptions levées
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.
Valeur de retour

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.
Arguments
Le parameters object is overloaded avec two types:
  • Type GetVisitorCodeParametersType (for NodeJS/Express/NextJS SSR methods), contenant the following fields:
  • Type GetNextJSVisitorCodeParametersType (for NextJS SSR server actions), contenant the following fields:
  • Type GetDenoVisitorCodeParametersType (for Deno), contenant the following fields:
  • Type GetCustomVisitorCodeParametersType (for custom VisitorCodeManager implementation), contenant the following fields:
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
Exceptions levées

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.
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
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
Arguments
Or un objet avec le type FlushParamsType, containing:
Exceptions levées

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.
Arguments
Valeur de retour
Exceptions levées

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.
Arguments
An object avec le type RemoteVisitorDataParamsType, containing:
Valeur de retour
Exceptions levées
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:

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.
Arguments
Paramètres object consisting of:
Valeur de retour
Exceptions levées

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.
Arguments
Le parameters object is overloaded avec les types suivants:
  • Type SetLegalConsentParametersType (for NodeJS/Express/NextJS SSR methods), contenant the following fields:
  • Type SetNextJSLegalConsentParametersType (for NextJS SSR server actions), contenant the following fields:
  • Type SetDenoLegalConsentParametersType (for Deno), contenant the following fields:
  • Type SetCustomLegalConsentParametersType (for custom VisitorCodeManager implementation), contenant the following fields:
Exceptions levées
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.
Arguments
Paramètres object consisting of:
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’).
Exceptions levées

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.
  • 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.
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
Valeur de retour
Exceptions levées

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.
Events
Events are défini dans le EventType enum. Le eventData parameter will have a different type basé sur le event type.
Arguments
Exceptions levées

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.

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.

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

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:

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

Device

Device contient information about your device.
Each visitor can uniquement have one Device. Adding a second Device overwrites the first one.

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.

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

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

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.

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.

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.

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.

Variation

Variation contient information about the assigned variation to le visiteur (or the default variation, if no specific assignment exists).
  • 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.

Variable

Variable contient information about a variable associated avec le assigned variation.

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.
Valeur de retour

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.
Arguments
Valeur de retour
Exceptions levées

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)
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 :
Utilisez getFeatureFlags lorsque vous need all of le visiteur’s feature flags:
Arguments
Valeur de retour
Exceptions levées

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.
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
Valeur de retour
Exceptions levées

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.
Arguments
Paramètres object of type GetFeatureFlagVariableParamsType contenant the following fields:
Valeur de retour
Exceptions levées

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.
Arguments
Valeur de retour
Exceptions levées

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.
Arguments
Exceptions levées

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.
Valeur de retour
Exceptions levées