React 16.8.0+
Guide du développeur
Suivez cette section pour intégrer le SDK dans votre application et en apprendre davantage sur son utilisation.Premiers pas
Cette section vous guide à travers l’installation et la configuration du SDK pour la première fois.Installation
L’outil d’installation du SDK Kameleoon est la méthode recommandée pour installer le SDK. Cet installateur de SDK vous aide à installer le SDK de votre choix, à générer un exemple de code de base et à configurer les dépendances externes si nécessaire. Pour démarrer l’outil d’installation du SDK, installez-le et exécutez-le globalement :npx:
Créer le client Kameleoon
Pour commencer, créez un point d’entrée pour le SDK React en créant le client Kameleoon au niveau supérieur de votre application. Créez une instance deKameleoonClient en utilisant la fonction createClient(), importée du package kameleoon.
- TypeScript
- JavaScript
Encapsuler l’application dans le Kameleoon Provider
La deuxième étape consiste à connecter le client Kameleoon précédemment créé aKameleoonProvider en passant le client configuré a KameleoonProvider:
- TS
- JS
- NextJS (TS)
- NextJS (JS)
- NextJS with externals(TS)
- NextJS with externals(JS)
KameleoonProvider
Utilisez ce provider au niveau racine en encapsulant votre application pour obtenir un accès àKameleoonClient. This ensures your app ne fait pas flicker due to flag changes at startup time.
Props
KameleoonProviderSSR
Utilisez ce provider au niveau racine en encapsulant votre application pour obtenir un accès àKameleoonClient.
KameleoonProviderSSR diffère de KameleoonProvider car il crée une KameleoonClient instance à l’intérieur du contexte lors de la première requête du client. This empêche le risque de créer le client côté serveur. C’est recommandé pour une utilisation dans les systèmes basés sur le SSR, tel que Next.js with SSR.
Props
Await for le client initialization
KameleoonClient initialization is done asynchronously afin de assurez-vous that Kameleoon API call was successful for that hook useInitialize is used. Vous pouvez utiliser async/await, Promise.then() or any other method to handle asynchronous client initialization.
- TypeScript
- JavaScript
Activating a feature flag
Assigning a unique ID to a utilisateur
To assign a unique ID to a utilisateur, vous pouvez utiliser thegetVisitorCode() method. If a visiteur code n’existe pas (depuis le cookie des en-têtes de la requête), la méthode generates a random unique ID or uses a defaultVisitorCode that you would have generated. The ID est est ensuite placé in le cookie des en-têtes de la réponse.
Si vous êtes using Kameleoon in Hybrid mode, calling the getVisitorCode() method ensures that the unique ID (visiteur code) is shared between l’application fichier engine.js (previously named, kameleoon.js) and le SDK.
Retrieving a flag configuration
To implement a feature flag in your code, vous devez first create the feature flag in your Kameleoon account. To determine the status or variation of a feature flag for a specific utilisateur, vous devriez utilisez lagetVariation() or isFeatureFlagActive() method to retrieve the configuration basé sur the featureKey.
The getVariation() method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for l’utilisateur by checking the feature rules, assigning the variation, and returning it basé sur the featureKey and visitorCode.
The isFeatureFlagActive() method peut être used si vous voulez retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or ciblage options.
If your feature flag has associated variables (tel que specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which provides détails about the assigned variation and its associated expérience. Cette méthode checks whether l’utilisateur is targeted, finds le visiteur’s assigned variation, and saves it to storage. When track=true, le SDK will send the exposure événement to the specified expérience on the next suivi request, qui est automatically triggered basé sur le SDK’s tracking_interval_millisecond. Par défaut, this interval is set to 1000 milliseconds (1 second).
The getVariation() method allows you to control whether suivi is done. If track=false, no exposure événements sera sent by le SDK. This is useful if vous préférez ne pas suivre données through le SDK and instead rely on client-side suivi managed by the Kameleoon engine, par exemple. De plus, setting track=false is helpful when en utilisant la fonction getVariations() method, where you might only need the variations for all flags without triggering any suivi événements. Si vous voulez en savoir plus sur le fonctionnement du suivi, view cet article
Adding données points to target a utilisateur or filter / breakdown visits in reports
To target a utilisateur, ensure you’ve added relevant données points to their profil before retrieving the feature variation or checking if the flag est actif. Utilisez laaddData() method to add these données points to de l’utilisateur profil.
To retrieve données points collected on other devices or to access past utilisateur données (collected client-side when using Kameleoon in Hybrid mode), utilisez la getRemoteVisitorData() method. Cette méthode asynchronously fetches données from the servers. C’est important to call getRemoteVisitorData() before retrieving the variation or checking if the feature flag est actif, as this données might be required to assign a utilisateur to a given variation.
To learn more about available ciblage conditions, consultez la section detailed article on the subject.
De plus, les données points you add to le visiteur profil sera available when analyzing your expériences, allowing you to filter and break down your résultats by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of données points on le client-side, making it easy to break down your résultats basé sur these pre-collected données points. Consultez la section complète list here.
Si vous avez besoin de track additional données points beyond what’s automatically collected, vous pouvez utiliser Kameleoon’s Custom Data feature. Custom Données allows you to capture and analyze specific informations relevant to your expériences. Don’t forget to call the flush() method to send the collected données to Kameleoon servers for analysis.
To ensure your résultats are accurate, c’est recommended to filter out bots by en utilisant la fonction
UserAgent données type.Suivi objectif conversions
When a utilisateur complètes a desired action (tel que making a purchase), c’est recorded as a conversion. To track conversions, utilisez latrackConversion() method and provide the required visitorCode and goalId parameters.
The conversion suivi request sera sent along with the next scheduled suivi request, which le SDK sends at regular intervals (defined by tracking_interval_millisecond). If you préférez envoyer la requête immédiatement, utilisez la flush() method with le paramètre instant=true.
Sending événements to analytics solutions
To track conversions and send exposure événements to your customer analytics solution, vous devez first implement Kameleoon in Hybrid mode. Then, utilisez lagetEngineTrackingCode() method.
The getEngineTrackingCode() method retrieves the unique suivi code required to send exposure événements to your analytics solution. Using cette méthode allows you to record événements and send them to your desired analytics platform.
React Native considerations
React Native on
android platform ne support Real Time Update feature.@kameleoon/react-native-storage- built usingreact-native-mmkvlibrary@kameleoon/react-native-event-source- built usingreact-native-event-source-tslibrary@kameleoon/react-native-visitor-code-manager- built on top ofreact-native-mmkvlibrary@kameleoon/react-native-platform-analyzer- built usingreact-nativelibrary- optional
@kameleoon/react-native-secure-prng- built usingreact-native-get-random-valueslibrary
- TypeScript
- JavaScript
Using a custom bucketing key
Par défaut, Kameleoon uses a unique, anonymous visiteur ID (visitorCode) to assign utilisateurs to feature flag variations. This ID is typically generated and stored on de l’utilisateur device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). Cependant, in certain scenarios vous pouvez need to ensure all utilisateurs of the same organization consultez la section same variant of a feature flag.
The Custom Bucketing Key option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon’s assignment logic uses your specified key au lieu de the default visitorCode.
Use cases
Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:- Account-level or organizational expériences: For B2B products or scenarios where you want to assign all utilisateurs from the same organization to the same variation, vous pouvez utiliser an identifier like an
accountId. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.
Technical détails
Lorsque vous configuré a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your application’s données:- Providing the custom key: You provide your custom identifier to the Kameleoon SDK en utilisant la fonction
addData()method. In cette méthode, vous allez pass your chosen custom bucketing key as aCustomDataobject. Here,newVisitorCoderefers to the identifier you wish to use for your bucketing (par exemple, the newuserIdoraccountId).
- Bucketing logic: Once a custom bucketing key is provided through the
addData()method, all hash calculations for assigning utilisateurs to variations will use thisnewVisitorCode(your custom key) au lieu de the defaultvisitorCode. Using thenewVisitorCodemeans that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present. - Données suivi and analytics: C’est crucial to notez que while the
newVisitorCode(your custom key) is utilisé pour bucketing decisions, all subsequent données (suivi événements and conversions, par exemple) is sent and associated with the originalvisitorCode. This separation ensures that your analytics accurately reflect individual utilisateur journeys and interactions within your expérience’s broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Votre original visiteur données remains intact for comprehensive reporting.
Technical requirementes
To effectively use a custom bucketing key:- The key doit étre a
string. - It doit étre unique for the entity you intend to bucket (par exemple, if using a
userId, each utilisateur’s ID devrait étre unique). - The key doit étre available to le SDK at the exact moment the feature flag decision is evaluated for that utilisateur or request.
Ciblage conditions
The Kameleoon SDKs support a variety of predefined ciblage conditions that vous pouvez utiliser to target utilisateurs in your campaigns. For la liste des conditions supported by this SDK, see use visit history to target utilisateurs. Vous pouvez également use your own external données to target utilisateurs.Logging
The SDK generates logs to reflect various internal processes and issues.Log levels
The SDK supports configuring limiting logging by a log level.- TypeScript
- JavaScript
Custom handling of logs
The SDK writes its logs to the console output par défaut. This behaviour peut être overridden.Logging limiting by a log level is performed apart from the log handling logic.
- TypeScript
- JavaScript
Domain informations
You provide a domain as thedomain in KameleoonClient [configuration], qui est utilisé pour storing Kameleoon visiteur code in cookies. This is important when working with the getVisitorCode and setLegalConsent methods. The domain you provide is stored in the cookie as the Domain= key.
Setting the domain
The domain you provide indicates the URL address can utilisez la cookie. Par exemple, if your domain iswww.example.com. the cookie is only available from a www.example.com URL. That means that pages with the app.example.com domain can’t utilisez la cookie.
To be more flexible around subdomains, vous pouvez prefix a domain with .. Par exemple, the domain .example.com allows the cookie to function on both app.example.com and login.example.com.
Vous pouvez’t use regular expressions, special symbols, protocol, or port numbers in the
domain.
De plus, a specific liste de subdomains ne sont pas allowed to be used with the prefix ..Developing on localhost
localhost est unlways considered a bad domain, making it hard to test the domain when developing on localhost.
There are two ways to avoid this issue:
- Don’t specify the
domainchamp in le SDK client while testing. This empêchelocalhostissues (the cookie sera set on any domain). - Create a local domain for
localhost. Par exemple:- Navigate to
/etc/hostson Linux or toc:\Windows\System32\Drivers\etc\hostson Windows - Open
hostswith fichier super utilisateur or administrator rights - Add a domain to the localhost port, par exemple:
127.0.0.1 app.com - Now vous pouvez run your app locally on
app.com:{my_port}and specify.app.comas your domain
- Navigate to
External dependencies
SDK external dependencies utilisez la dependency injection pattern to give you the ability to provide your own implementations for certain parts of an SDK.In the React SDK, all external dependencies have default implementations, which use a native browser API so there’s no need to provide them unless another API est requis for specific use cases.
L’exemple suivant implements external dependencies. To import an interface from an SDK, create a class that implements it and pass the instantiated class to le SDK.
Storage
- TypeScript
- JavaScript
EvenementSource
- TypeScript
- JavaScript
VisitorCodeManager
- TypeScript
- JavaScript
Requester
- TypeScript
- JavaScript
Pseudo Random Number Generator
Pseudo Random Number Generator (PRNG) est un dependency that generates random floating point number between0 and 1 (similar to Math.random).
Default Kameleoon implementation relies on Browser’s crypto or Math.random function if crypto n’est pas available.
Those API are very secure and reliable, cependant in some edge cases (especially in some React Native engines) you might want to provide your own implementation or use a dedicated Kameleoon package for React Native - @kameleoon/react-native-secure-prng
- TypeScript
- JavaScript
Erreur Handling
Almost every React SDK callback qui est returned by hooks may throw an erreur at some point, these erreurs ne sont pas just caveats but rather deliberately predefinedKameleoonErrors
that extend native JavaScript Error class providing useful messages and special type champ with a type KameleoonException.
KameleoonException est un enum containing all possible erreur types.
To know exactly what type of KameleoonException the callbacks may throw, vous pouvez check Throws section of le hooks description on this page or just hover over the callback in your IDE to see jsdocs description.
Overall handling the erreurs considered a good practice to make your application more stable and avoid technical issues.
- TypeScript
- JavaScript
Cross-device experimentation
To support visiteurs who access an app from multiple devices, Kameleoon allows the synchronization of previously collected visiteur données across each of du visiteur devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed informations on how Kameleoon handles données across devices are available in the article on cross-device experimentation.Synchronizing données personnalisées across devices
Although custom mapping synchronization est utilisé pour align visiteur données across devices, it n’est pas always necessary. Below are two scenarios where custom mapping sync n’est pas required: Same utilisateur ID across devices If the same utilisateur ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. C’est enough to call thegetRemoteVisitorData() method lorsque vous want to sync les données collected between multiple devices.
Multi-server instances with consistent IDs
In complex setups involving multiple servers (par exemple, distributed server instances), where the same utilisateur ID est unvailable across servers, synchronization between servers (with getRemoteVisitorData()) is sufficient without additional custom mapping sync.
Customers who need additional données can consultez the getRemoteVisitorData() method description for further guidance. In the below code, c’est assumed that the same unique identifier (in this case, the visitorCode, which can also be referred to as userId) is used consistently between the two devices for accurate données retrieval.
Si vous voulez sync collected données in real time, vous devez choose the scope Visiteur for your données personnalisées.
- TypeScript
- JavaScript
Device One
Device Two
Using données personnalisées for session merging
- SDK Version 9
- SDK Version 10
Cross-device experimentation allows you to combine a visiteur’s history across each of their devices (history reconciliation). One of the powerful features that history reconciliation provides est le ability to merge different visiteurs sessions into one. To reconcile visit history, vous pouvez utiliser
CustomData to provide a unique identifier for le visiteur.Follow the activating cross-device history reconciliation guide to set up your données personnalisées on the Kameleoon platformLorsque vousr données personnalisées is set up, vous pouvez utiliser it in your code to merge a visiteur’s session.
Sessions with the same identifier will always consultez la section same expérience variation and sera displayed as a single visiteur in the Visitor view of your expérience’s résultat pages.The SDK configuration ensures that associated sessions always consultez la section same variation of the expérience.Before using other methods assurez-vous to let SDK know that le visiteur est un unique identifier by adding UniqueIdentifier données to a visiteurVoici un exemple of how to use données personnalisées for session merging. Dans cet exemple, we have an application with a login page. Since we don’t know l’utilisateur ID at the moment of login, we use an anonymous visiteur identifier generated by the getVisitorCode method. After l’utilisateur logs in, we can associate the anonymous visiteur with l’utilisateur ID and use it as a unique identifier for le visiteur.- TypeScript
- JavaScript
Login Page
Application Page
Utilities
SDK has a set of utility methods that peut être utilisé pour simplify the development process. All la méthodes are represented as static members ofKameleoonUtils class.
simulateSuccessRequest
MethodsimulateSuccessRequest est utilisé pour simulate a successful request to the Kameleoon server. It peut être useful for custom Requester implementations when developer needs to simulate a successful request, par exemple disabling suivi.
- TypeScript
- JavaScript
Arguments
Données type
SimulateRequestDataType is defined as follows:
RequestType.Tracking-nullRequestType.ClientConfiguration-ClientConfigurationDataTypeRequestType.RemoteData-JSONType
Valeur de retour
getCookieValue
MethodgetCookieValue est utilisé pour parse a common cookie string (key_1=value_1; key_2=value_2; ...) and get la valeur of a specific cookie key. C’est useful when working with a custom implementation of VisitorCodeManager.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Référence
C’est le full référence documentation for the React SDK.Initialization
This section provides la méthodes you use to create and initialize the Kameleoon Client in your application.initialize()
- SDK Version 9
- SDK Version 10
An asynchronous
initialize function, collected with useInitialize hook, that’s utilisé pour KameleoonClient initialization by fetching Kameleoon SDK related données from server or by retrieving données from local source if données is up-to-date or update interval has not been reached.-
If le SDK configuration could not be retrieved but il y a an older configuration available in SDK storage, le SDK uses the older configuration as a fallback and the
initializene fait pas throw an erreur. - SDK supports an offline mode.
- TypeScript
- JavaScript
Valeur de retour
Exceptions thrown
isInitialized()
TheisInitialized function, collected with the useInitialize hook, est un small utility method that checks if le SDK initialization has completed. Par exemple, this peut être useful when dealing with a deeply nested component tree, because it allows you to quickly check le SDK readiness without having to manage a global state, or pass the initialization résultat using component props.
- TypeScript
- JavaScript
Valeur de retour
Aboolean value. Renvoie true if SDK was successfully initialized, sinon renvoie false.
createClient()
To get started, vous devez create an entry point for React SDK by creating a Kameleoon Client at the top level of your application en utilisant la fonctioncreateClient() function importé depuis kameleoon package.
An instance de KameleoonClient is created using createClient() function.
- TypeScript
- JavaScript
Arguments
An object of typeSDKParameters containing:
Configuration Parameters
- SDK Version 9
- SDK Version 10
Valeur de retour
Assurez-vous not to use several client instances in one application as it n’est pas fully supported yet and may overwrite the local storage configuration and cause unintended behavior (bugs).
Feature flags and variations
This section provides la méthodes you use to retrieve and manage the feature flags and variations assigned to le visiteur.getVariation()
- 📨 Sends Suivi Données to Kameleoon (depending on the
trackparameter)
Variation assigned to a given visiteur for a specific feature flag.
Cette méthode takes featureKey as a mandatory argument and track as une optional argument. The track argument est optionnel and defaults to true.
It renvoie le assigned Variation for le visiteur. If le visiteur n’est pas associated with any feature flag rules, la méthode renvoie le default Variation for the given feature flag.
Ensure that proper erreur handling is implemented in your code to manage potential exceptions.
The default variation refers to the variation assigned to a visiteur when they ne pas match any predefined delivery rules for a feature flag. In other words, it est le fallback variation applied to all utilisateurs who ne sont pas targeted by specific rules. C’est represented as the variation in the “Then, for everyone else…” section in a management interface.
- TypeScript
- JavaScript
Arguments
An object of typeGetVariationParamsType with the following properties:
Valeur de retour
Exceptions thrown
getVariations()
- 📨 Sends Suivi Données to Kameleoon (depending on the
trackparameter) - 🎯 Événements:
EventType.Evaluation
Method is obtained using
useFeatureFlag hook.Variation objects assigned to a given visiteur across all feature flags.
Cette méthode iterates over all available feature flags and renvoie le assigned Variation for each flag associated with the specified visiteur. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.
- If
onlyActiveis set totrue, la méthodegetVariations()will return feature flags variations provided l’utilisateur n’est pas bucketed with theoffvariation. - The
trackparameter controls whether or not la méthode will track the variation assignments. Par défaut, c’est set totrue. If set tofalse, the suivi sera disabled.
Variation as values. If no variation est unssigned for a feature flag, la méthode renvoie le default Variation for that flag.
Proper erreur handling devrait étre implemented to manage potential exceptions.
The default variation refers to the variation assigned to a visiteur when they ne pas match any predefined delivery rules for a feature flag. In other words, it est le fallback variation applied to all utilisateurs who ne sont pas targeted by specific rules. C’est represented as the variation in the “Then, for everyone else…” section in a management interface.
- TypeScript
- JavaScript
Arguments
An object of typeGetVariationsParamsType with the following properties:
Valeur de retour
Exceptions thrown
isFeatureFlagActive()
- 📨 Sends Suivi Données to Kameleoon (depending on the
trackparameter) - 🎯 Événements:
EventType.Evaluation
isFeatureFlagActive(), used with the useFeatureFlag hook, determines whether a visiteur identified by visitorCode has the specified featureKey active. Cette méthode checks the ciblage conditions, identifies the variation for le visiteur, and saves this informations to storage. De plus, le hook sends a suivi request.
There est unlso an overload for cette méthode that includes a track parameter, allowing you to disable the suivi of the feature evaluation.
Visiteur doit étre targeted to has feature flag active
Kameleoon uses suivi to count sessions and visiteurs lorsque vous call certain methods, tel que
isFeatureFlagActive(), getVariation() or getVariations().Utilisez la default true value for the track parameter lorsque vous expose visiteurs to a variation and need to count them. Set the track parameter to false only if you call these methods before you expose visiteurs.Par exemple, if you call getVariations() to retrieve all variations before you expose visiteurs, set the track parameter to false. This setting empêche Kameleoon from prematurely counting a session. Vous pouvez then trigger suivi later lorsque vous explicitly expose le visiteur.Kameleoon sends suivi données every second par défaut. Vous pouvez configuré this interval up to five seconds en utilisant la fonction suivi interval configuration option. Kameleoon groups suivi événements into a single session as long as the interval between événements is less than 30 minutes. If more than 30 minutes elapse between suivi événements, Kameleoon counts the événements as separate sessions. A visit appears in your reports 30 minutes after the last recorded événement in the session.- TypeScript
- JavaScript
Arguments
There are two overloads available for cette méthode:- Two parameters overload:
- Object parameter overload of type
IsFeatureFlagActiveParamsType:
Valeur de retour
Exceptions thrown
setForcedVariation()
The method allows you to programmatically assign a specificVariation to a utilisateur, bypassing the standard evaluation process. This is especially valuable for controlled expériences where the usual evaluation logic n’est pas required or doit étre skipped. It can also be helpful in scenarios like debugging or custom testing.
When a forced variation is set, it overrides Kameleoon’s real-time evaluation logic. Processes like segmentation, ciblage conditions, and algorithmic calculations are skipped. To preserve segmentation and ciblage conditions during an expérience, set forceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it sera fully processed and completed first.
- TypeScript
- JavaScript
Arguments
An object of typeSetForcedVariationParametersType with the following properties:
Exceptions thrown
In most cases, only the basic erreur,
KameleoonException, needs to be handled, as demonstrated in l’exemple. Cependant, if different types of erreurs require une réponse, handle each one separately basé sur specific requirements. De plus, for enhanced reliability, general language erreurs peut être handled by including Error.evaluateAudiences()
- 📨 Sends Suivi Données to Kameleoon
evaluateAudiences() devrait étre called after all relevant visiteur données has been set or updated, and just before getting a feature variation or checking a feature flag. Thest unpproach ensures that le visiteur is evaluated against the most current données available, allowing for accurate audience assignment basé sur all criteria.
After calling cette méthode, vous pouvez perform a detailed analysis of segment performance in Audiences Explorer.
- TypeScript
- JavaScript
Arguments
Exceptions thrown
In most cases, only the basic erreur,
KameleoonException, needs to be handled, as demonstrated in l’exemple. Cependant, if different types of erreurs require une réponse, handle each one separately basé sur specific requirements. De plus, for enhanced reliability, general language erreurs peut être handled by including Error.getDataFichier()
Renvoie le current SDK configuration as aDataFile object.
- TypeScript
- JavaScript
Valeur de retour
Visiteur données
This section provides la méthodes you use to manage visiteur données.getVisitorCode()
getVisitorCode method collected from useVisitorCode hook obtains a visiteur code from the browser cookie. If le visiteur code n’existe pas yet, la fonction generates a random visiteur code (or uses the defaultVisitorCode value if you provided one) and sets the new visiteur code in a cookie.
The
getVisitorCode() method allows you to set simulated variations for a visiteur. When cookies (from a request or document) contain la clé kameleoonSimulationFFData, the standard evaluation process is bypassed. Instead, la méthode directly renvoie un Variation basé sur the provided données.Vous pouvez apply simulations in two ways:- Automatically (recommended): If using Kameleoon Web Experienceation or le SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display en utilisant la fonction Simulation Panel.
- Manually: Set the
kameleoonSimulationFFDatacookie manually.
- Simulated variations: Affect the overall feature flag résultat.
- Forced variations: Are specific to an individual expérience.
kameleoonSimulationFFData cookie follows this format:kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates the variation withvarIdof expérienceexpIdfor the givenfeatureKey.kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined in the Then, for everyone else in Production, serve section) for the givenfeatureKey.
encodeURIComponent.- TypeScript
- JavaScript
Arguments
If you don’t provide a
defaultVisitorCode and il y a no visiteur code stored in a cookie, le visiteur code sera randomly generated.Valeur de retour
Exceptions thrown
addData()
TheaddData function, used with the useData hook, collects ciblage données to store for other hooks to determine if the current visiteur is targeted.
- The
addData()function ne fait pas return any value and ne fait pas interact with Kameleoon back-end servers on its own. Instead, all the declared données is saved for future transmission via the flush method .Thest unpproach helps reduce the number of server calls made, as les données is typically grouped into a single server call triggered by the execution of flush.
-
userAgentdonnées will not be stored in storage like other données, and it sera sent with every suivi request for bot filtration. - Check la liste des supported conditions to know what données types peut être utilisé pour ciblage
- TypeScript
- JavaScript
Arguments
-
kameleoonDatais variadic argument it peut être passé en tant que one or several arguments (see l’exemple) -
The index or ID of the données personnalisées peut être found in your Kameleoon account. C’est important to notez que this index starts at
0, which means that the first données personnalisées you create for a given site sera assigned0as its ID, not1.
Exceptions thrown
Consultez la section Données types référence pour plus de détails of how to manage different données types.
flush()
- SDK Version 9
- SDK Version 10
flush() takes the Kameleoon données associated with le visiteur and schedules les données to be sent with the next suivi request. The time of the next suivi request is defined by SDK Configuration trackingInterval parameter. Visiteur données peut être added using addData and getRemoteVisiteurDonnees methods.If you don’t specify a visitorCode, le SDK flushes all of its stored données to the remote Kameleoon servers. If any previously failed suivi requests were stored locally during offline mode, le SDK attempts to send the stored requests before executing the latest request.- TypeScript
- JavaScript
Arguments
Or an object with the type FlushParamsType, containing:
Exceptions thrown
getRemoteDonnees()
Asynchronous methodgetRemoteData, collected with the useData hook, renvoie un données stored for specified site code on a remote Kameleoon server.
Par exemple, vous pouvez utiliser cette fonction to retrieve utilisateur preferences, historical données, or any other données relevant to your application’s logic. By storing this données on our highly scalable servers using our [Données API], vous pouvez efficiently manage massive amounts of données and retrieve it for each of your visiteurs or utilisateurs.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions thrown
getRemoteVisiteurDonnees()
- SDK Version 9
- SDK Version 10
getRemoteVisitorData() est un asynchronous method for retrieving Kameleoon Visits Données for the visitorCode from the Kameleoon Données API. The method adds les données to storage for other methods to use when making ciblage decisions.Données obtained using cette méthode plays an important role lorsque vous want to:- use données collected from other devices.
- access a utilisateur’s history, tel que previously visited pages during past visits.
- use données that is only accessible on le client-side, like donneeslayer variables and objectifs that only convert on the front-end.
- TypeScript
- JavaScript
Arguments
An object with the typeRemoteVisitorDataParamsType containing:Valeur de retour
Exceptions thrown
Using parameters in getRemoteVisiteurDonnees()
ThegetRemoteVisitorData() method offers flexibility by allowing you to define various parameters when retrieving données on visiteurs. Whether you’re ciblage basé sur objectifs, expériences, or variations, the same approach applies across all données types.Par exemple, let’s say you want to retrieve données on visiteurs who completed a objectif “Order transaction”. Vous pouvez specify parameters within the getRemoteVisitorData() method to refine your ciblage. For instance, si vous voulez target only utilisateurs who converted on the objectif in their last five visits, vous pouvez définir the previousVisitAmount parameter to 5 and conversions to true.The flexibility shown dans cet exemple n’est pas limited to objectif données. Vous pouvez utiliser parameters within the getRemoteVisitorData() method to retrieve données on a variety of visiteur behaviors.Here is la liste des available
VisitorDataFiltersType filters:getVisitorWarehouseDonnees()
Asynchronous methodgetVisitorWarehouseAudience collected with useData hook retrieves all audience données associated with le visiteur in your données warehouse en utilisant la fonction specified visitorCode and warehouseKey. The warehouseKey is typically your internal utilisateur ID. The customDataIndex parameter corresponds to the Kameleoon données personnalisées that Kameleoon uses to target your visiteurs. Consultez the warehouse ciblage documentation for additional détails.
- TypeScript
- JavaScript
Arguments
Parameters object consisting of:Valeur de retour
Exceptions thrown
setLegalConsent()
MethodsetLegalConsent, collected with useVisitorCode hook, specifies whether le visiteur has given legal consent to use personal données. Setting the legalConsent parameter to false limits the types of données that vous pouvez include in suivi requests. This helps you adhere to legal and regulatory requirements while responsibly managing visiteur données. Vous pouvez trouver more informations on personal données in the consent management policy.
- Consent informations is in sync between the Kameleoon Engine (application fichier engine.js) and the React SDK. This synchronization means that once consent is set on either the Engine or le SDK, c’est automatically set for both. This feature eliminates the need for manual consent handling and ensures that SDKs operate in compliance with utilisateur preferences.
- When handling legal consent, c’est important to use
getVisitorCodemethod. De plus,getVisitorCodene fait pas acceptdomainas an argument. Instead, pass it to thecreateClientfunction.
- TypeScript
- JavaScript
Arguments
Exceptions thrown
Consent revocation behavior
Lorsque vous callsetLegalConsent() with consent=false, le SDK ne fait pas delete the kameleoonVisitorCode cookie. Instead, it stops extending the cookie’s expiration date, allowing the cookie to persist until it naturally expires.
If your compliance requirements demand the immediate removal of the cookie fichier upon opt-out, vous devez delete it manually using your framework’s native cookie management methods. The SDK will not remove le fichier automatically.
Objectifs and third-party analytics
This section provides la méthodes you use to track when a visiteur action achieve one of you objectifs (a conversion).trackConversion()
- SDK Version 9
- SDK Version 10
- 📨 Sends Suivi Données to Kameleoon
trackConversion() function, used with the useData hook creates and adds Conversion données to le visiteur with specified parameters and executes flush().Use cette méthode to track a conversion for a specific objectif and utilisateur. Cette méthode requires visitorCode and goalId. En plus, cette méthode also accepts une optional revenue, negative and metadata arguments. The visitorCode is usually identical to the one that was used when triggering the expérience.The trackConversion() method ne return any value. Cette méthode is non-blocking as the server call is made asynchronously.- TypeScript
- JavaScript
Arguments
Parameters object consisting of:Les valeurs de métadonnées sont accessibles via les exports de données brutes et la page de résultats.Si le paramètre
metadata est fourni, Kameleoon utilisera les valeurs spécifiées pour la conversion actuelle au lieu de celles précédemment collectées via la méthode addData(). Si le paramètre est omis, Kameleoon utilisera les dernières valeurs suivies pour ces CustomData avant la conversion et au cours de la même visite.Kameleoon ne prendra en compte que les valeurs de métadonnées explicitement passées en paramètres à la méthode trackConversion().Dans l’exemple ci-dessous, Kameleoon associera la conversion uniquement à la valeur de données personnalisées explicitement fournie en paramètre (ici : index 5 avec la valeur ‘Amex Credit Card’).- TypeScript
- JavaScript
Exceptions thrown
getEngineSuiviCode()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side expériences correctly, call thegetEngineTrackingCode() method after le visiteur triggers an expérience. The SDK renvoie JavaScript queue commands for the expériences that le visiteur triggered during the previous five seconds. Lorsque vous insert this code into the page, Engine.js processes the commands and sends the exposure événements through the active analytics intégration.
Consultez hybrid experimentation pour plus d’informationss on implementing cette méthode.
- TypeScript
- JavaScript
-
To use this feature, implement both the React SDK and Kameleoon Engine.js. Because Engine.js is used only for suivi in this flow, vous pouvez install the asynchronous tag before the closing
</body>tag. -
Vous pouvez insert the returned suivi code directly into an HTML
<script>tag.
123456 and 234567 are expérience IDs, and 7890 and 8901 are variation IDs. In your implementation, le SDK generates these values in the returned suivi code.Arguments
Valeur de retour
Exceptions thrown
Événements
This section provides la méthodes you use to handle événements.- SDK Version 10
onEvenement()
MethodonEvent, collected with the useInitialize hook, fires a callback when a specific événement is triggered. The callback function has access to les données associated with the événement. The SDK methods in this documentation note which événement types they can trigger, if any.- TypeScript
- JavaScript
Vous pouvez only assign one callback to each
EventType.Événements
Événements are defined in theEventType enum. Depending on the événement type, the eventData parameter will have a different type.Arguments
Exceptions thrown
Sending exposure événements to external tools
Kameleoon offers built-in integrations with various analytics and CDP solutions, tel que Mixpanel, Google Analytics 4, Segment…. To ensure that vous pouvez track and analyze your server-side expériences, Kameleoon provides une méthodegetEngineTrackingCode() that renvoie le JavasScript code to be inserted in your page to automatically send the exposure événements to the analytics solution you are using. The SDK builds a suivi code for your active analytics solution basé sur the expériences that le visiteur has triggered in the last 5 seconds.
Pour plus d’informationss about hybrid experimentation, please consultez this documentation.To benefit from this feature, vous allez need to implement both the React SDK and our Kameleoon JavaScript tag. We recommend you implement the [Kameleoon asynchronous tag], which vous pouvez install before your closing
<body> tag in your HTML page, as it sera only utilisé pour suivi purposes.Données types
Kameleoon Données types are helper classes utilisé pour storing données in storage in predefined forms. During the flush execution, le SDK collects all les données and sends it along with the suivi request. Données available in le SDK n’est pas available for ciblage and reporting in the Kameleoon app until you add les données. Par exemple, by en utilisant la fonctionaddData() method.
See use visit history to target utilisateurs pour plus d’informationss.
Si vous êtes using hybrid mode, vous pouvez appeler
getRemoteVisitorData() to automatically fill all données that Kameleoon has collected previously.Browser
Since React SDK
10.11.0, Browser est unutomatically detected basé sur the User-Agent string. Cependant, vous pouvez still manually override it if needed.Each visiteur can only have one
Browser. Adding a second Browser overwrites the first one.- TypeScript
- JavaScript
UniqueIdentifier
UniqueIdentifier données is used as marker for unique visiteur identification.
If you add UniqueIdentifier for a visiteur, visitorCode is used as the unique visiteur identifier, qui est useful for Cross-device experimentation. Associating a UniqueIdentifier with a visiteur notify SDK that le visiteur is linked to another visiteur.
The UniqueIdentifier can also be useful in other edge-case scenarios, tel que lorsque vous can’t access the anonymous visitorCode that was originally assigned to le visiteur, but you do have access to an internal ID that is connected to the anonymous visiteur using session merging capabilities.
Each visiteur can only have one
UniqueIdentifier. Adding another UniqueIdentifier overwrites the first one.- TypeScript
- JavaScript
Conversion
TheConversion données set stored here peut être utilisé pour filter expérience and personalization reports by any objectif associated with it.
ConversionParametersType conversionParameters - an object with conversion parameters described below
- TypeScript
- JavaScript
Cookie
Cookie contains informations about the cookie stored on du visiteur device.
-
Generally, the React SDK will attempt to use a
localStoragecookie for the conditions. If not possible, SDK can useCookiedonnées as an alternative. -
Each visiteur can only have one
Cookie. Adding a secondCookieoverwrites the first one.
- TypeScript
- JavaScript
Méthodes
Cookie données has a static utility method fromString that vous pouvez utiliser to create a cookie instantly by parsing a string that contains valid cookie données.
The method accepts string as parameter and renvoie un initialized Cookie instance.
- TypeScript
- JavaScript
GeolocationDonnees
GeolocationData contains du visiteur geolocation détails
Each visiteur can only have one
GeolocationData. Adding a second GeolocationData overwrites the first one.GeolocationInfoType containing the following champs:
- TypeScript
- JavaScript
CustomData
To retain données personnalisées for future visits, le SDK transmitsCustomData with a Visitor scope during the next suivi request. Vous pouvez configuré the scope in les données settings on the données personnalisées dashboard.
CustomData allows you to associate any type of données with each visiteur easily. This données can then be used as a ciblage condition in segments or as a filter or breakdown in expérience reports.
Pour plus d’informationss about données personnalisées, please consultez this article.
-
Each visiteur est unllowed only one
CustomDatafor each uniqueindex. Adding anotherCustomDatawith the sameindexwill replace the existing one. - The données personnalisées ‘index’ peut être found in the Custom Données dashboard under the “INDEX” column.
- To prevenement le SDK from sending données with the selected index to Kameleoon servers for privacy reasons, enable l’option: Use this données only locally for ciblage purposes when creating données personnalisées.
-
Adding a
CustomDatainstance created with un nom when le SDK instance n’est pas initialized or le nom n’est pas registered, will résultat in les données being ignored.
- TypeScript
- JavaScript
Device
Since React SDK
10.11.0, Device est unutomatically detected basé sur the User-Agent string. Cependant, vous pouvez still manually override it if needed.React Native: Support for this feature is currently experienceal and may require adjustments to work correctly. In React Native, the Device est unutomatically detected basé sur the DPI from react-native.Dimensions.Each visiteur can only have one
Device. Adding a second Device overwrites the first one.- TypeScript
- JavaScript
OperatingSystem
Since React SDK
10.11.0, OperatingSystem est unutomatically detected basé sur the User-Agent string. Cependant, vous pouvez still manually override it if needed.React Native: Support for this feature is currently experienceal and may require adjustments to work correctly. In React Native, the OperatingSystem est unutomatically detected basé sur the react-native.Platform.OperatingSystem contains du visiteur operating system informations.
Each visiteur can only have one
OperatingSystem. Adding a second OperatingSystem overwrites the previous one.- TypeScript
- JavaScript
PageView
Since React SDK
10.11.0, PageView est unutomatically detected basé sur the window.location?.href and document.title. Cependant, vous pouvez still manually override it if needed.React Native: Support for this feature is currently experienceal and may require adjustments to work correctly.Each visiteur can have one
PageView per unique URL. Adding a PageView with the same URL as an existing one will notify SDK that le visiteur revisited pagePageViewParametersType pageViewParameters - an object with page view parameters described below
- TypeScript
- JavaScript
UserAgent
Store informations on l’utilisateur-agent of le visiteur. 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 and Bots List to identify known bots and spiders. Kameleoon also uses theUserAgent champ to filter out bots and other unwanted traffic that could sinon skew your conversion metrics. Pour plus de détails, consultez la section help article on bot filtering.
If you use internal bots, we suggest that you pass la valeur curl/8.0 of l’userAgent to exclude them from our analytics.
A visiteur can only have one
UserAgent. Adding a second UserAgent overwrites the first one.- TypeScript
- JavaScript
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
- TypeScript
- JavaScript
Returned Types
DonneesFichier
TheDataFile contains le SDK configuration détails.
It peut être extended with additional informations if required by clients. If you need more détails, please contact your Customer Success Manager.
- TypeScript
- JavaScript
FeatureFlag
TheFeatureFlag represents a set of properties that define a feature flag itself — par exemple, its Variations, Rules, environnement status, and other related détails.
It peut être extended with additional informations if required by clients. If you need more détails, please contact your Customer Success Manager.
- TypeScript
- JavaScript
Rule
TheRule represents a set of properties that define a rule itself — par exemple, its Variations.
It peut être extended with additional informations if required by clients. If you need more détails, please contact your Customer Success Manager.
- TypeScript
- JavaScript
Variation
Variation contains informations about the assigned variation to le visiteur (or the default variation, if no specific assignment exists).
- Ensure that your code handles the case where
idorexperimentIdpeut êtrenull, indicating a default variation. - The
variablesmap might be empty if no variables are associated with the variation.
- TypeScript
- JavaScript
Variable
Variable contains informations about a variable associated with the assigned variation.
- TypeScript
- JavaScript
Deprecated methods
getFeatureFlagVariationKey()
- 📨 Sends Suivi Données to Kameleoon
- 🎯 Événements:
EventType.Evaluation
Utilisez la
getVariation method.getFeatureFlagVariationKey(), qui est used with the useFeatureFlag hook, retrieves the variation key for a visiteur identified by their visitorCode. This process includes checking the ciblage criteria, identifying the appropriate variation assigned to le visiteur, storing this informations, and sending a suivi request.
If a utilisateur has never been associated with a feature flag, le SDK will randomly return a variation key according to the rules of that feature flag. If l’utilisateur est unlready linked to the feature flag, le SDK will identify the previously assigned variation key. If l’utilisateur ne fait pas meet any of the specified rules, le SDK will return the valeur par défaut defined in Kameleoon’s feature flag delivery rules. It’s important to notez que the valeur par défaut may not always be a variation key; it could also be a boolean value or another données type, depending on how the feature flag is configured.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions thrown
getVisitorFeatureFlags()
- 🚫 Doesn’t send Suivi Données to Kameleoon
- 🎯 Événements:
EventType.Evaluation(for each feature flag)
Utilisez la
getVariations method.getVisitorFeatureFlags method, utilized with the useFeatureFlag hook, renvoie un liste de active feature flags that target le visiteur associated with the visitorCode (le visiteur must have one of the allocated variations).
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions thrown
getActiveFeatureFlags()
- 🚫 Doesn’t send Suivi Données to Kameleoon
- 🎯 Événements:
EventType.Evaluation(for each feature flag)
Utilisez la
getVariations method.getActiveFeatureFlags method, collected with the useFeatureFlag hook, renvoie un Map, where key is feature key and value is detailed informations about du visiteur variation and c’est variables
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions thrown
getFeatureFlagVariable()
- 📨 Sends Suivi Données to Kameleoon
- 🎯 Événements:
EventType.Evaluation
Utilisez la
getVariation method.getFeatureFlagVariable method, collected with useFeatureFlag hook, renvoie un variable for le visiteur under visitorCode in the found feature flag, this includes ciblage check, finding the according variation exposed to le visiteur and saving it to storage along with sending suivi request.
- TypeScript
- JavaScript
Arguments
Parameters object of typeGetFeatureFlagVariableParamsType containing the following champs:
Valeur de retour
Exceptions thrown
getFeatureFlagVariables()
- 📨 Sends Suivi Données to Kameleoon
- 🎯 Événements:
EventType.Evaluation(for each feature flag)
Utilisez la
getVariations method.getFeatureFlagVariables method, collected with the useFeatureFlag, hook renvoie un liste de variables for le visiteur under visitorCode in the found feature flag, this includes ciblage check, finding the according variation exposed to le visiteur and saving it to storage along with sending suivi request.
- TypeScript
- JavaScript
Arguments
Valeur de retour
Exceptions thrown
onConfigurationUpdate()
Utilisez la
onEvent method with EventType.ConfigurationUpdate instead.onConfigurationUpdate collected with useInitialize hook fires a callback on client configuration update.
Ce hook only works for server sent événements of real time update
- TypeScript
- JavaScript
Arguments
Exceptions thrown
getFeatureFlags()
🚫 Doesn’t send Suivi Données to Kameleoon ThegetFeatureFlags method collected with the useFeatureFlag hook renvoie un liste de feature flags stored in le client configuration.
- TypeScript
- JavaScript