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 :npx:
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 nouveauKameleoonClient.
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.
- TypeScript
- JavaScript
Arguments
Exceptions levées
Paramètres de configuration
- SDK Version 4
- SDK Version 5
Mode de compatibilité
Utilisez le SDK parametercompatibility 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 therequestTimeoutparameter inSDKConfigurationTypeunavailable et prevent le SDK from en utilisantAbortControllerfor request cancellation, even dans default10_000ms timeout. Supports Node version 14 et higher.Compatibility.Node12- compatibility avec this version implies the même limitations as theNode14mode 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 thegetVisitorCode() 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 thegetVariation() 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 leaddData() 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 thetrackConversion() 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 thegetEngineTrackingCode() 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éthodeKameleoonClient 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.
- TypeScript
- JavaScript
Intégration avec les fournisseurs Edge
- SDK Version 4
- SDK Version 5
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 thegetRemoteVisitorData() 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.
- TypeScript
- JavaScript
Device One
Device Two
Utilisation des données personnalisées pour la fusion de sessions
- SDK Version 4
- SDK Version 5
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.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.- TypeScript
- JavaScript
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.
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 aCustomDataobject. Here,newVisitorCoderefers vers le identifier you wish to use for your bucketing (par exemple, the newuserIdouaccountId).
- 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 thisnewVisitorCode(your custom key) au lieu du defaultvisitorCode. Using thenewVisitorCodemeans 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 originalvisitorCode. 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.- TypeScript
- JavaScript
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.
- TypeScript
- JavaScript
Informations de domaine
You provide a domain as thedomain 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 iswww.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 ..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
domainfield in le SDK client while testing. This preventslocalhostissues (le cookie will be défini on any domain). - Créez a local domain for
localhost. Par exemple :- Navigate to
/etc/hostson Linux ou toc:\Windows\System32\Drivers\etc\hostson Windows - Open
hostsavec file super user ou administrator rights - Ajoutez a domain vers le
localhostport, par exemple:127.0.0.1 app.com - Now, vous pouvez run your app locally on
app.com:{my_port}et spécifier.app.comas your domain
- Navigate to
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.
Vous pouvez également implémenter
visitorCodeManager en utilisant the IExternalNextJSVisitorCodeManager, IExternalDenoVisitorCodeManager, ou IExternalCustomVisitorCodeManager interfaces for NextJS, Deno, ou custom visitor code manager implementations, respectively.@kameleoon/nodejs-event-source- based oneventsourcelibrary (can be utilisé for NodeJS/Deno/NextJS SSR)@kameleoon/nodejs-requester- based onnode-fetchlibrary (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 SSRheaderscookie ou NextJS SSR request/response
Stockage
- TypeScript
- JavaScript
EventSource
- TypeScript
- JavaScript
VisitorCodeManager
visitorCodeManager implementation for NodeJS/NextJS SSR:
- TypeScript
- JavaScript
visitorCodeManager implementation for Deno:
- TypeScript
- JavaScript
visitorCodeManager implementation for NextJS Server Actions:
- TypeScript
- JavaScript
visitorCodeManager implementation avec arbitrary parameters:
- TypeScript
- JavaScript
Requester
- TypeScript
- JavaScript
Utilitaires
Le SDK has un ensemble de utility methods that vous pouvez use to simplify development. All methods are représenté as static members duKameleoonUtils class.
- SDK Version 4
- SDK Version 5
simulateSuccessRequest
Utilisez lesimulateSuccessRequest 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.
- TypeScript
- JavaScript
Arguments
Le
SimulateRequestDataType data type is défini as follows:
RequestType.Tracking-nullRequestType.ClientConfiguration-ClientConfigurationDataTypeRequestType.RemoteData-JSONType
Valeur de retour
getCookieValue
Utilisez legetCookieValue 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.
- TypeScript
- JavaScript
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 initializingKameleoonClient 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.
- TypeScript
- JavaScript
Valeur de retour
Exceptions levées
Feature flags et variations
getVariation()
- 📨 Sends Tracking Data to Kameleoon (selon le
trackparameter)
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.
- TypeScript
- JavaScript
Arguments
An object of typeGetVariationParamsType avec le following properties:
Valeur de retour
Exceptions levées
getVariations()
- 📨 Sends Tracking Data to Kameleoon (selon le
trackparameter) - 🎯 Events:
EventType.Evaluation
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
onlyActiveis défini totrue, la méthodegetVariations()will return feature flags variations fourni l’utilisateur is not bucketed avec leoffvariation. - Le
trackparameter controls whether ou not la méthode will suivre la variation assignments. Par défaut, it is défini totrue. If défini tofalse, the suivi will be disabled.
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.
- TypeScript
- JavaScript
Arguments
An object of typeGetVariationsParamsType avec le following properties:
Valeur de retour
Exceptions levées
isFeatureFlagActive()
- 📨 Sends Tracking Data to Kameleoon (selon le
trackparameter) - 🎯 Events:
EventType.Evaluation
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.- TypeScript
- JavaScript
Arguments
There are two overloads available for this method:- Two parameters overload:
- Object parameter overload of type
IsFeatureFlagActiveParamsType:
Valeur de retour
Exceptions levées
setForcedVariation()
Le method permet you to programmatically assign a specificVariation 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.
- TypeScript
- JavaScript
Arguments
An object of typeSetForcedVariationParametersType 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
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.
- TypeScript
- JavaScript
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()
Retourne the current SDK configuration as aDataFile object.
- TypeScript
- JavaScript
Valeur de retour
Données du visiteur
getVisitorCode()
LegetVisitorCode 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
kameleoonSimulationFFDatacookie manually.
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual expérience.
kameleoonSimulationFFData cookie follows this format:kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates la variation avecvarIdof expérienceexpIdpour le givenfeatureKey.kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined dans le Ensuite, for everyone else in Production, serve section) pour le givenfeatureKey.
encodeURIComponent.- TypeScript
- JavaScript
Arguments
Le parameters object is overloaded avec two types:- Type
GetVisitorCodeParametersType(forNodeJS/Express/NextJS SSR methods), contenant the following fields:
- Type
GetNextJSVisitorCodeParametersType(forNextJS SSR server actions), contenant the following fields:
- Type
GetDenoVisitorCodeParametersType(forDeno), contenant the following fields:
- Type
GetCustomVisitorCodeParametersType(for customVisitorCodeManagerimplementation), 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 leaddData() 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.
Vérifiez the list of supported conditions to voir la data types vous pouvez use for targeting.
- TypeScript
- JavaScript
Arguments
-
kameleoonDatais 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 assigned0as its ID, rather than1.
Exceptions levées
Vérifiez the data types reference for more details on how to manage different data types.
flush()
- SDK Version 4
- SDK Version 5
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.- TypeScript
- JavaScript
Arguments
Or un objet avec le type FlushParamsType, containing:
Exceptions levées
getRemoteData()
LegetRemoteData() 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.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions levées
getRemoteVisitorData()
- SDK Version 4
- SDK Version 5
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.
- TypeScript
- JavaScript
Arguments
An object avec le typeRemoteVisitorDataParamsType, containing:Valeur de retour
Exceptions levées
Utilisation des paramètres dans getRemoteVisitorData()
LegetRemoteVisitorData() 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()
LegetVisitorWarehouseAudience 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.
- TypeScript
- JavaScript
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.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.
- TypeScript
- JavaScript
Arguments
Le parameters object is overloaded avec les types suivants:- Type
SetLegalConsentParametersType(forNodeJS/Express/NextJS SSR methods), contenant the following fields:
- Type
SetNextJSLegalConsentParametersType(forNextJS SSR server actions), contenant the following fields:
- Type
SetDenoLegalConsentParametersType(forDeno), contenant the following fields:
- Type
SetCustomLegalConsentParametersType(for customVisitorCodeManagerimplementation), contenant the following fields:
Exceptions levées
Comportement de révocation du consentement
Lorsque vous appelsetLegalConsent() 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()
- SDK Version 4
- SDK Version 5
- 📨 Sends Tracking Data to Kameleoon
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.- TypeScript
- JavaScript
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’).- TypeScript
- JavaScript
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 thegetEngineTrackingCode() 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.
- TypeScript
- JavaScript
-
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.
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
- SDK Version 5
onEvent()
LeonEvent() 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.- TypeScript
- JavaScript
Events
Events are défini dans leEventType 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 theflush() 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.- TypeScript
- JavaScript
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.- TypeScript
- JavaScript
Conversion
LeConversion data défini stored ici peut être utilisé pour filter expérience et personalization reports by any objectif associated avec it.
ConversionParametersType conversionParamètres - un objet avec conversion parameters described below
- TypeScript
- JavaScript
Cookie
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.- TypeScript
- JavaScript
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.
- TypeScript
- JavaScript
GeolocationData
GeolocationData contient le visiteur’s geolocation details.
Each visitor can uniquement have one
GeolocationData. Adding a second GeolocationData overwrites the first one.GeolocationInfoType contient the following fields:
- TypeScript
- JavaScript
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
CustomDatafor chaque uniqueindex. Adding un autreCustomDataavec le mêmeindexwill 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
CustomDatainstance 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.
- TypeScript
- JavaScript
Device
Device contient information about your device.Each visitor can uniquement have one
Device. Adding a second Device overwrites the first one.- TypeScript
- JavaScript
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.- TypeScript
- JavaScript
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.
- TypeScript
- JavaScript
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.- TypeScript
- JavaScript
ApplicationVersion
ApplicationVersion représente the semantic version number of your application.
- TypeScript
- JavaScript
Types retournés
DataFile
LeDataFile 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.
- TypeScript
- JavaScript
FeatureFlag
LeFeatureFlag 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.
- TypeScript
- JavaScript
Rule
LeRule 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.
- TypeScript
- JavaScript
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
idouexperimentIdmay benull, indicating a default variation. - Le
variablesmap might be empty if no variables are associated avec la variation.
- TypeScript
- JavaScript
Variable
Variable contient information about a variable associated avec le assigned variation.
- TypeScript
- JavaScript
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()
LerefreshDataFileIfStale() 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.
- TypeScript
- JavaScript
Valeur de retour
Méthodes obsolètes
getFeatureFlagVariationKey()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation
Utilisez le
getVariation method instead.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.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions levées
getVisitorFeatureFlags()
Utilisez le
getVariations method instead.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)
- TypeScript
- JavaScript
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.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.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions levées
getFeatureFlagVariable()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation
Utilisez le
getVariation method instead.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.
- TypeScript
- JavaScript
Arguments
Paramètres object of typeGetFeatureFlagVariableParamsType contenant the following fields:
Valeur de retour
Exceptions levées
getFeatureFlagVariables()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation(for chaque feature flag)
Utilisez le
getVariation method instead.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.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions levées
onConfigurationUpdate()
Utilisez le
onEvent method avec EventType.ConfigurationUpdate instead.onConfigurationUpdate() method fires un callback upon client configuration update.
Cette méthode is uniquement applicable to server-sent events for real-time updates.
- TypeScript
- JavaScript
Arguments
Exceptions levées
getFeatureFlags()
Utilisez le
getDataFile() method instead.getFeatureFlags() method récupère une liste de feature flags that are stored in le client configuration.
- TypeScript
- JavaScript