React 16.8.0+
Developer guide
Follow this section to integrate the SDK into your application and learn more about using the SDK.Getting started
This section walks you through installing and configurating the SDK for the first time.Installation
The Kameleoon SDK Installation tool is the preferred way to install the SDK. This SDK Installer helps you to install the SDK of your choice, generate a basic code sample, and configure external dependencies if needed. To start the SDK Installation tool, install and run it globally:npx:
Create the Kameleoon Client
To get started to create an entry point for React SDK by creating Kameleoon Client on the top level of your application. Create an instance ofKameleoonClient using the createClient() function, imported from the kameleoon package.
- TypeScript
- JavaScript
Wrap the application in the Kameleoon Provider
The second step is connecting the previously created Kameleoon Client toKameleoonProvider by passing the configured client to KameleoonProvider:
- TS
- JS
- NextJS (TS)
- NextJS (JS)
- NextJS with externals(TS)
- NextJS with externals(JS)
KameleoonProvider
Use this provider on root level by wrapping your app to gain an access toKameleoonClient. This ensures your app does not flicker due to flag changes at startup time.
Props
| Name | Type | Description |
|---|---|---|
| children (required) | ReactNode | child elements of the provider |
| client (required) | KameleoonClient | KameleoonClient instance created by createClient() |
KameleoonProviderSSR
Use this provider on root level by wrapping your app to gain an access toKameleoonClient.
KameleoonProviderSSR differs from KameleoonProvider in that it creates a KameleoonClient instance inside the context on the first client request. This prevents the risk of creating the client on the server side. It is recommended for use in SSR-based systems, such as Next.js with SSR.
Props
| Name | Type | Description |
|---|---|---|
| children (required) | ReactNode | child elements of the provider |
| sdkParameters (required) | SDKParameters | SDKParameters settings for creating an instance of KameleoonClient |
Await for the client initialization
KameleoonClient initialization is done asynchronously in order to make sure that Kameleoon API call was successful for that hook useInitialize is used. You can use 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 user
To assign a unique ID to a user, you can use thegetVisitorCode() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode that you would have generated. The ID is then set in a response headers cookie.
If you are using Kameleoon in Hybrid mode, calling the getVisitorCode() method ensures that the unique ID (visitor code) is shared between the application file engine.js (previously named, kameleoon.js) and the SDK.
Retrieving a flag configuration
To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account. To determine the status or variation of a feature flag for a specific user, you should use thegetVariation() or isFeatureFlagActive() method to retrieve the configuration based on 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 the user by checking the feature rules, assigning the variation, and returning it based on the featureKey and visitorCode.
The isFeatureFlagActive() method can be used if you want to 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 targeting options.
If your feature flag has associated variables (such as specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s tracking_interval_millisecond. By default, this interval is set to 1000 milliseconds (1 second).
The getVariation() method allows you to control whether tracking is done. If track=false, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting track=false is helpful when using the getVariations() method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article
Adding data points to target a user or filter / breakdown visits in reports
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use theaddData() method to add these data points to the user’s profile.
To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the getRemoteVisitorData() method. This method asynchronously fetches data from the servers. It is important to call getRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.
To learn more about available targeting conditions, see the detailed article on the subject.
Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here.
If you need to track additional data points beyond what’s automatically collected, you can use Kameleoon’s Custom Data feature. Custom Data allows you to capture and analyze specific information relevant to your experiments. Don’t forget to call the flush() method to send the collected data to Kameleoon servers for analysis.
To ensure your results are accurate, it’s recommended to filter out bots by using the
UserAgent data type.Tracking goal conversions
When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use thetrackConversion() method and provide the required visitorCode and goalId parameters.
The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by tracking_interval_millisecond). If you prefer to send the request immediately, use the flush() method with the parameter instant=true.
Sending events to analytics solutions
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use thegetEngineTrackingCode() method.
The getEngineTrackingCode() method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.
React Native considerations
React Native on
android platform doesn’t 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
By default, Kameleoon uses a unique, anonymous visitor ID (visitorCode) to assign users to feature flag variations. This ID is typically generated and stored on the user’s device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the 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 instead of 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 experiments: For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an
accountId. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.
Technical details
When you configure a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your application’s data:- Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the
addData()method. In this method, you will pass your chosen custom bucketing key as aCustomDataobject. Here,newVisitorCoderefers to the identifier you wish to use for your bucketing (for example, the newuserIdoraccountId).
- Bucketing logic: Once a custom bucketing key is provided through the
addData()method, all hash calculations for assigning users to variations will use thisnewVisitorCode(your custom key) instead of 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. - Data tracking and analytics: It’s crucial to note that while the
newVisitorCode(your custom key) is used for bucketing decisions, all subsequent data (tracking events and conversions, for example) is sent and associated with the originalvisitorCode. This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment’s broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.
Technical requirements
To effectively use a custom bucketing key:- The key must be a
string. - It must be unique for the entity you intend to bucket (for example, if using a
userId, each user’s ID should be unique). - The key must be available to the SDK at the exact moment the feature flag decision is evaluated for that user or request.
Targeting conditions
The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions supported by this SDK, see use visit history to target users. You can also use your own external data to target users.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 by default. This behaviour can be overridden.Logging limiting by a log level is performed apart from the log handling logic.
- TypeScript
- JavaScript
Domain information
You provide a domain as thedomain in KameleoonClient [configuration], which is used for storing Kameleoon visitor 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 use the cookie. For example, 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 use the cookie.
To be more flexible around subdomains, you can prefix a domain with .. For example, the domain .example.com allows the cookie to function on both app.example.com and login.example.com.
You can’t use regular expressions, special symbols, protocol, or port numbers in the
domain.
Additionally, a specific list of subdomains are not allowed to be used with the prefix ..| Domain | Allowed URLs | Disallowed URLs |
|---|---|---|
www.example.com | ✅www.example.com | ❌ app.example.com |
✅ example.com | ❌ .com | |
.example.com = example.com | ✅ example.com | ❌ otherexample.com |
✅ www.example.com | ||
✅ app.example.com | ||
✅ login.example.com | ||
https://www.example.com | ⛔ bad domain | ⛔ bad domain |
www.example.com:4408 | ⛔ bad domain | ⛔ bad domain |
.localhost.com = localhost | ⛔ bad domain | ⛔ bad domain |
Developing on localhost
localhost is always 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
domainfield in the SDK client while testing. This preventslocalhostissues (the cookie will be set on any domain). - Create a local domain for
localhost. For example:- Navigate to
/etc/hostson Linux or toc:\Windows\System32\Drivers\etc\hostson Windows - Open
hostswith file super user or administrator rights - Add a domain to the localhost port, for example:
127.0.0.1 app.com - Now you can run your app locally on
app.com:{my_port}and specify.app.comas your domain
- Navigate to
External dependencies
SDK external dependencies use the 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 is required for specific use cases.
| Dependency | Interface | API Used | Description |
|---|---|---|---|
storage (optional) | IExternalStorage | Browser localStorage | Used for storing all the existing and collected SDK data |
requester (optional) | IExternalRequester | Browser fetch | Used for performing all the network requests |
eventSource (optional) | IExternalEventSource | Browser EventSource | Used for receiving Server Sent Events for Real Time Update capabilities |
visitorCodeManager (optional) | IExternalVisitorCodeManager | Browser cookie | Used for storing and synchronizing visitor code |
prng (optional) | IExternalPRNG | Math.random or Browser crypto.getRandomValues | Used to generate unique IDs for tracking events |
logger (optional) | ILogger | Custom implementation | Used for custom handling of logs from the SDK. Allows to define how logs are processed and where they are output. |
platformAnalyzer (optional) | IPlatformAnalyzer | React Native API | Automatically detects the platform and attaches this information to the visitor data. Designed specifically for React Native. |
Storage
- TypeScript
- JavaScript
EventSource
- TypeScript
- JavaScript
VisitorCodeManager
- TypeScript
- JavaScript
Requester
- TypeScript
- JavaScript
Pseudo Random Number Generator
Pseudo Random Number Generator (PRNG) is a 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 is not available.
Those API are very secure and reliable, however 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
Error Handling
Almost every React SDK callback which is returned by hooks may throw an error at some point, these errors are not just caveats but rather deliberately predefinedKameleoonErrors
that extend native JavaScript Error class providing useful messages and special type field with a type KameleoonException.
KameleoonException is an enum containing all possible error types.
To know exactly what type of KameleoonException the callbacks may throw, you can check Throws section of the hooks description on this page or just hover over the callback in your IDE to see jsdocs description.
Overall handling the errors considered a good practice to make your application more stable and avoid technical issues.
- TypeScript
- JavaScript
Cross-device experimentation
To support visitors who access an app from multiple devices, Kameleoon allows the synchronization of previously collected visitor data across each of the visitor’s devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the article on cross-device experimentation.Synchronizing custom data across devices
Although custom mapping synchronization is used to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required: Same user ID across devices If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call thegetRemoteVisitorData() method when you want to sync the data collected between multiple devices.
Multi-server instances with consistent IDs
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with getRemoteVisitorData()) is sufficient without additional custom mapping sync.
Customers who need additional data can refer to the getRemoteVisitorData() method description for further guidance. In the below code, it is 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 data retrieval.
If you want to sync collected data in real time, you need to choose the scope Visitor for your custom data.
- TypeScript
- JavaScript
Device One
Device Two
Using custom data for session merging
- SDK Version 9
- SDK Version 10
Cross-device experimentation allows you to combine a visitor’s history across each of their devices (history reconciliation). One of the powerful features that history reconciliation provides is the ability to merge different visitors sessions into one. To reconcile visit history, you can use
CustomData to provide a unique identifier for the visitor.Follow the activating cross-device history reconciliation guide to set up your custom data on the Kameleoon platformWhen your custom data is set up, you can use it in your code to merge a visitor’s session.
Sessions with the same identifier will always see the same experiment variation and will be displayed as a single visitor in the Visitor view of your experiment’s result pages.The SDK configuration ensures that associated sessions always see the same variation of the experiment.Before using other methods make sure to let SDK know that the visitor is a unique identifier by adding UniqueIdentifier data to a visitorHere’s an example of how to use custom data for session merging. In this example, we have an application with a login page. Since we don’t know the user ID at the moment of login, we use an anonymous visitor identifier generated by the getVisitorCode method. After the user logs in, we can associate the anonymous visitor with the user ID and use it as a unique identifier for the visitor.- TypeScript
- JavaScript
Login Page
Application Page
Utilities
SDK has a set of utility methods that can be used to simplify the development process. All the methods are represented as static members ofKameleoonUtils class.
simulateSuccessRequest
MethodsimulateSuccessRequest is used to simulate a successful request to the Kameleoon server. It can be useful for custom Requester implementations when developer needs to simulate a successful request, for example disabling tracking.
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| requestType (required) | RequestType | A type of request |
| data (required) | SimulateRequestDataType[RequestType] | A type of request data, which is different depending on RequestType |
SimulateRequestDataType is defined as follows:
RequestType.Tracking-nullRequestType.ClientConfiguration-ClientConfigurationDataTypeRequestType.RemoteData-JSONType
Return value
| Type | Description |
|---|---|
Promise<KameleoonResponseType> | returns a promise with the response of the request |
getCookieValue
MethodgetCookieValue is used to parse a common cookie string (key_1=value_1; key_2=value_2; ...) and get the value of a specific cookie key. It’s useful when working with a custom implementation of VisitorCodeManager.
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| cookie (required) | string | Cookie string in a form key_1=value_1; key_2=value_2 |
| key (required) | string | String representation of a key to find a value by |
Return value
| Type | Description | |
|---|---|---|
| `string | null` | returns a string with a cookie value or null if the key was not found |
Reference
This is the full reference documentation for the React SDK.Initialization
This section provides the methods 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 used for KameleoonClient initialization by fetching Kameleoon SDK related data from server or by retrieving data from local source if data is up-to-date or update interval has not been reached.-
If the SDK configuration could not be retrieved but there is an older configuration available in SDK storage, the SDK uses the older configuration as a fallback and the
initializedoes not throw an error. - SDK supports an offline mode.
- TypeScript
- JavaScript
Return value
| Type | Description |
|---|---|
Promise<boolean> | a promise resolved to a boolean indicating a successful sdk initialization. Generally initialize will throw an error if the something that can not be handled will happen, so the boolean value will almost always be true and won’t give as much useful information. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.StorageWrite | Couldn’t update storage data |
KameleoonException.ClientConfiguration | Couldn’t retrieve client configuration from Kameleoon API |
KameleoonException.MaximumRetriesReached | Maximum retries reached, request failed |
isInitialized()
TheisInitialized function, collected with the useInitialize hook, is a small utility method that checks if the SDK initialization has completed. For example, this can be useful when dealing with a deeply nested component tree, because it allows you to quickly check the SDK readiness without having to manage a global state, or pass the initialization result using component props.
- TypeScript
- JavaScript
Return value
Aboolean value. Returns true if SDK was successfully initialized, otherwise returns false.
createClient()
To get started, you need to create an entry point for React SDK by creating a Kameleoon Client at the top level of your application using thecreateClient() function imported from kameleoon package.
An instance of KameleoonClient is created using createClient() function.
- TypeScript
- JavaScript
Arguments
An object of typeSDKParameters containing:
| Name | Type | Description |
|---|---|---|
| siteCode (required) | string | This is a unique key of the Kameleoon project you are using with the SDK. This field is mandatory. |
| configuration (optional) | Partial<SDKConfigurationType> | client’s configuration |
| externals (optional) | ExternalsType | external implementation of SDK dependencies (External dependencies) |
Configuration Parameters
- SDK Version 9
- SDK Version 10
| Name | Type | Description | Default Value |
|---|---|---|---|
| updateInterval (optional) | number | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. If left unspecified, the default interval is set to 60 minutes. Additionally, we offer a streaming mode that uses server-sent events (SSE) to push new configurations to the SDK automatically and apply new configurations in real-time, without any delays. | 60 |
| environment (optional) | Environment | string | feature flag environment | Environment.Production |
| targetingDataCleanupInterval (optional) | number | interval in minutes for cleaning up targeting data; minimum value is 1 minute | undefined (no cleanup will be performed) |
| cookieDomain (optional) | string | domain that the cookie belongs to. | undefined |
| networkDomain (optional) | string | custom domain the SDKs uses for all outgoing network requests, commonly used for proxying. The format is second_level_domain.top_level_domain (for example, example.com). If an invalid format is specified, the SDK uses the default Kameleoon value | undefined |
| requestTimeout (optional) | number | timeout in milliseconds for all SDK network requests, if timeout is exceeded request will fail immediately | 10_000 (10 seconds) |
| trackingInterval (optional) | number | Specifies the interval for tracking requests, in milliseconds. All visitors who were evaluated for any feature flag or had associated data will be included in this tracking request, which is performed once per interval. The minimum value is 1_000 ms and the maximum value is 5_000 ms | 1_000 (1 second) |
| stubMode (optional) | boolean | When set to true, the client will operate in stub mode and perform no operations. In this mode, all method calls execute no actions, ensuring that no external actions or side effects occur. | false |
| defaultDataFile (optional) | string | The defaultDataFile feature ensures the Kameleoon SDK is always READY by providing a fallback configuration when no cached data file exists. Developers can preload a valid configuration by fetching it from https://sdk-config.kameleoon.eu/v3/<sitecode> and passing it as defaultDataFile during initialization. When a dateModified timestamp (in milliseconds) is provided and is newer than the cached version, the SDK will use the default datafile instead of the cached version. If dateModified is omitted, the default datafile is only applied when no cached version exists. This ensures the SDK always has a valid configuration, whether default, cached, or updated. | undefined |
Return value
| Type | Description |
|---|---|
KameleoonClient | an instance of KameleoonClient. |
Make sure not to use several client instances in one application as it is not fully supported yet and may overwrite the local storage configuration and cause unintended behavior (bugs).
Feature flags and variations
This section provides the methods you use to retrieve and manage the feature flags and variations assigned to the visitor.getVariation()
- 📨 Sends Tracking Data to Kameleoon (depending on the
trackparameter)
Variation assigned to a given visitor for a specific feature flag.
This method takes featureKey as a mandatory argument and track as an optional argument. The track argument is optional and defaults to true.
It returns the assigned Variation for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation for the given feature flag.
Ensure that proper error handling is implemented in your code to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s 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:
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (required) | string | Unique identifier of the visitor. | |
| featureKey (required) | string | Key of the feature you want to expose to a visitor. | |
| track (optional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
| Type | Description |
|---|---|
Variation | An assigned Variation to a given visitor for a specific feature flag. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The visitor code is empty. |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters). |
KameleoonException.FeatureFlagConfigurationNotFound | Exception indicating that the requested feature key wasn’t found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
KameleoonException.FeatureFlagEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor’s current environment (for example, production, staging, or development). |
getVariations()
- 📨 Sends Tracking Data to Kameleoon (depending on the
trackparameter) - 🎯 Events:
EventType.Evaluation
Method is obtained using
useFeatureFlag hook.Variation objects assigned to a given visitor across all feature flags.
This method iterates over all available feature flags and returns the assigned Variation for each flag associated with the specified visitor. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.
- If
onlyActiveis set totrue, the methodgetVariations()will return feature flags variations provided the user is not bucketed with theoffvariation. - The
trackparameter controls whether or not the method will track the variation assignments. By default, it is set totrue. If set tofalse, the tracking will be disabled.
Variation as values. If no variation is assigned for a feature flag, the method returns the default Variation for that flag.
Proper error handling should be implemented to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s 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:
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (required) | string | Unique identifier of the visitor. | |
| onlyActive (optional) | boolean | An optional parameter indicating whether to return variations for active (true) or all (false) feature flags. | false |
| track (optional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
| Type | Description |
|---|---|
Map<string, Variation> | Map that contains the assigned Variation objects of the feature flags using the keys of the corresponding features. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The visitor code is empty. |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters). |
isFeatureFlagActive()
- 📨 Sends Tracking Data to Kameleoon (depending on the
trackparameter) - 🎯 Events:
EventType.Evaluation
isFeatureFlagActive(), used with the useFeatureFlag hook, determines whether a visitor identified by visitorCode has the specified featureKey active. This method checks the targeting conditions, identifies the variation for the visitor, and saves this information to storage. Additionally, the hook sends a tracking request.
There is also an overload for this method that includes a track parameter, allowing you to disable the tracking of the feature evaluation.
Visitor must be targeted to has feature flag active
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as
isFeatureFlagActive(), getVariation() or getVariations().Use the default true value for the track parameter when you expose visitors to a variation and need to count them. Set the track parameter to false only if you call these methods before you expose visitors.For example, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.- TypeScript
- JavaScript
Arguments
There are two overloads available for this method:- Two parameters overload:
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
| featureKey (required) | string | a unique key for feature flag |
- Object parameter overload of type
IsFeatureFlagActiveParamsType:
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length | - |
| featureKey (required) | string | a unique key for feature flag | - |
| track (optional) | boolean | a boolean indicator of whether to track the feature evaluation | true |
Return value
| Type | Description |
|---|---|
boolean | indicator of whether the feature flag with featureKey is active for visitor with visitorCode. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for the specified featureKey |
KameleoonException.DataInconsistency | Allocated variation was found but there is no feature flag with according featureKey |
setForcedVariation()
The method allows you to programmatically assign a specificVariation to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be 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, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
- TypeScript
- JavaScript
Arguments
An object of typeSetForcedVariationParametersType with the following properties:
| Name | Type | Description | Default | |
|---|---|---|---|---|
| visitorCode (required) | string | Unique identifier of the visitor. | ||
| experimentId (required) | number | Experiment Id that will be targeted and selected during the evaluation process. | ||
| variationKey (required) | `string | null` | Variation Key corresponding to a Variation that should be forced as the returned value for the experiment. If the value is null, the forced variation will be reset. | |
| forceTargeting (optional) | boolean | Indicates whether targeting for the experiment should be forced and skipped (true) or applied as in the standard evaluation process (false). | true |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeEmpty | The visitor code is empty. |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters). |
KameleoonException.Initialization | Indicates that the SDK is not yet fully initialized. |
KameleoonException.FeatureFlagExperimentNotFound | Exception indicating that the requested experiment id has not been found in the SDK’s internal configuration. This is usually normal and means that the rule’s corresponding experiment has not yet been activated on Kameleoon’s side. |
KameleoonException.FeatureFlagVariationNotFound | Exception indicating that the requested variation key(id) has not been found in the internal configuration of the SDK. This is usually normal and means that the variation’s corresponding experiment has not yet been activated on Kameleoon’s side. |
KameleoonException.StorageRead | Couldn’t read storage data. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
In most cases, only the basic error,
KameleoonException, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Error.evaluateAudiences()
- 📨 Sends Tracking Data to Kameleoon
evaluateAudiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | Unique identifier of the visitor. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The visitor code is empty. |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters). |
In most cases, only the basic error,
KameleoonException, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Error.getDataFile()
Returns the current SDK configuration as aDataFile object.
- TypeScript
- JavaScript
Return value
| Type | Description |
|---|---|
DataFile | The DataFile containing the SDK configuration |
Visitor data
This section provides the methods you use to manage visitor data.getVisitorCode()
getVisitorCode method collected from useVisitorCode hook obtains a visitor code from the browser cookie. If the visitor code doesn’t exist yet, the function generates a random visitor code (or uses the defaultVisitorCode value if you provided one) and sets the new visitor code in a cookie.
The
getVisitorCode() method allows you to set simulated variations for a visitor. When cookies (from a request or document) contain the key kameleoonSimulationFFData, the standard evaluation process is bypassed. Instead, the method directly returns a Variation based on the provided data.You can apply simulations in two ways:- Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manually: Set the
kameleoonSimulationFFDatacookie manually.
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
kameleoonSimulationFFData cookie follows this format:kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates the variation withvarIdof experimentexpIdfor 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
| Name | Type | Description |
|---|---|---|
| defaultVisitorCode (optional) | string | visitor code to be used in case there is no visitor code in cookies |
If you don’t provide a
defaultVisitorCode and there is no visitor code stored in a cookie, the visitor code will be randomly generated.Return value
| Type | Description |
|---|---|
string | result visitor code. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
addData()
TheaddData function, used with the useData hook, collects targeting data to store for other hooks to determine if the current visitor is targeted.
- The
addData()function does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission via the flush method .This approach helps reduce the number of server calls made, as the data is typically grouped into a single server call triggered by the execution of flush.
-
userAgentdata will not be stored in storage like other data, and it will be sent with every tracking request for bot filtration. - Check the list of supported conditions to know what data types can be used for targeting
- TypeScript
- JavaScript
Arguments
| Name | Type | Description | Default value |
|---|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters. | |
| track (optional) | boolean | Specifies whether the added data is eligible for tracking. When set to false, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | true |
| kameleoonData (optional) | KameleoonDataType[] | number of instances of any type of KameleoonData, can be added solely in array or as sequential arguments |
-
kameleoonDatais variadic argument it can be passed as one or several arguments (see the example) -
The index or ID of the custom data can be found in your Kameleoon account. It is important to note that this index starts at
0, which means that the first custom data you create for a given site will be assigned0as its ID, not1.
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageWrite | Couldn’t update storage data |
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |
See the Data types reference for more details of how to manage different data types.
flush()
- SDK Version 9
- SDK Version 10
flush() takes the Kameleoon data associated with the visitor and schedules the data to be sent with the next tracking request. The time of the next tracking request is defined by SDK Configuration trackingInterval parameter. Visitor data can be added using addData and getRemoteVisitorData methods.If you don’t specify a visitorCode, the SDK flushes all of its stored data to the remote Kameleoon servers. If any previously failed tracking requests were stored locally during offline mode, the SDK attempts to send the stored requests before executing the latest request.- TypeScript
- JavaScript
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (optional) | string | unique visitor identification string, can’t exceed 255 characters, if not passed, all data will be flushed (sent to the remote Kameleoon servers). | - |
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (optional) | string | unique visitor identification string, can’t exceed 255 characters, if not passed, all data will be flushed (sent to the remote Kameleoon servers). | - |
| instant (optional) | boolean | Boolean flag indicating whether the data should be sent instantly (true) or according to the scheduled tracking interval (false). | - |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |
getRemoteData()
Asynchronous methodgetRemoteData, collected with the useData hook, returns a data stored for specified site code on a remote Kameleoon server.
For example, you can use this function to retrieve user preferences, historical data, or any other data relevant to your application’s logic. By storing this data on our highly scalable servers using our [Data API], you can efficiently manage massive amounts of data and retrieve it for each of your visitors or users.
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| key (required) | string | unique key that the data you try to get is associated with |
Return value
| Type | Description |
|---|---|
JSONType | promise with data retrieved for specific key. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
getRemoteVisitorData()
- SDK Version 9
- SDK Version 10
getRemoteVisitorData() is an asynchronous method for retrieving Kameleoon Visits Data for the visitorCode from the Kameleoon Data API. The method adds the data to storage for other methods to use when making targeting decisions.Data obtained using this method plays an important role when you want to:- use data collected from other devices.
- access a user’s history, such as previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
- TypeScript
- JavaScript
Arguments
An object with the typeRemoteVisitorDataParamsType containing:| Name | Type | Description | Default Value |
|---|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length | - |
| shouldAddData (optional) | boolean | boolean flag identifying whether the retrieved custom data should be set to the storage like addData method does | true |
| filters (optional) | VisitorDataFiltersType | filters for specifying what data should be retrieved from visits, by default only customData is retrieved from the current and latest previous visit | { previousVisitAmount: 1, currentVisit: true customData: true }, other filters parameters are set to false |
Return value
| Type | Description |
|---|---|
KameleoonDataType[] | promise with list of Kameleoon Data retrieved |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
KameleoonException.VisitAmount | Visit amount must be a number between 1 and 25 |
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Using parameters in getRemoteVisitorData()
ThegetRemoteVisitorData() method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types.For example, let’s say you want to retrieve data on visitors who completed a goal “Order transaction”. You can specify parameters within the getRemoteVisitorData() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.The flexibility shown in this example is not limited to goal data. You can use parameters within the getRemoteVisitorData() method to retrieve data on a variety of visitor behaviors.Here is the list of available
VisitorDataFiltersType filters:| Name | Type | Description | Default |
|---|---|---|---|
| previousVisitAmount (optional) | number | Number of previous visits to retrieve data from. Number between 1 and 25 | 1 |
| currentVisit (optional) | boolean | If true, current visit data will be retrieved | true |
| customData (optional) | boolean | If true, custom data will be retrieved. | true |
| pageViews (optional) | boolean | If true, page data will be retrieved. | false |
| geolocation (optional) | boolean | If true, geolocation data will be retrieved. | false |
| device (optional) | boolean | If true, device data will be retrieved. | false |
| browser (optional) | boolean | If true, browser data will be retrieved. | false |
| operatingSystem (optional) | boolean | If true, operating system data will be retrieved. | false |
| conversions (optional) | boolean | If true, conversion data will be retrieved. | false |
| experiments (optional) | boolean | If true, experiment data will be retrieved. | false |
| kcs (optional) | boolean | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
| visitorCode (optional) | boolean | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variation across visits for Cross-device experimentation. | true |
| personalization (optional) | boolean | If true, personalization data will be retrieved. This is required for the personalization condition | false |
| cbs (optional) | boolean | If true, Contextual Bandit score data will be retrieved. | false |
getVisitorWarehouseData()
Asynchronous methodgetVisitorWarehouseAudience collected with useData hook retrieves all audience data associated with the visitor in your data warehouse using the specified visitorCode and warehouseKey. The warehouseKey is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. Refer to the warehouse targeting documentation for additional details.
- TypeScript
- JavaScript
Arguments
Parameters object consisting of:| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
| customDataIndex (required) | number | number representing the index of the custom data you want to use to target your Warehouse Audiences |
| warehouseKey (optional) | string | unique key to identify the warehouse data (usually, your internal user ID) |
Return value
| Type | Description |
|---|---|
Promise<CustomData | null> | promise containing CustomData with the associated warehouse data or null if there was no data |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
setLegalConsent()
MethodsetLegalConsent, collected with useVisitorCode hook, specifies whether the visitor has given legal consent to use personal data. Setting the legalConsent parameter to false limits the types of data that you can include in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.
- Consent information is in sync between the Kameleoon Engine (application file engine.js) and the React SDK. This synchronization means that once consent is set on either the Engine or the SDK, it’s automatically set for both. This feature eliminates the need for manual consent handling and ensures that SDKs operate in compliance with user preferences.
- When handling legal consent, it’s important to use
getVisitorCodemethod. Additionally,getVisitorCodedoes not acceptdomainas an argument. Instead, pass it to thecreateClientfunction.
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
| consent (required) | boolean | a boolean value representing the legal consent status. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
Consent revocation behavior
When you callsetLegalConsent() with consent=false, the SDK does not 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 file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK will not remove the file automatically.
Goals and third-party analytics
This section provides the methods you use to track when a visitor action achieve one of you goals (a conversion).trackConversion()
- SDK Version 9
- SDK Version 10
- 📨 Sends Tracking Data to Kameleoon
trackConversion() function, used with the useData hook creates and adds Conversion data to the visitor with specified parameters and executes flush().Use this method to track a conversion for a specific goal and user. This method requires visitorCode and goalId. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitorCode is usually identical to the one that was used when triggering the experiment.The trackConversion() method doesn’t return any value. This method is non-blocking as the server call is made asynchronously.- TypeScript
- JavaScript
Arguments
Parameters object consisting of:| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (required) | string | Unique identifier of the visitor. | |
| goalId (required) | number | ID of the goal. | |
| negative (optional) | boolean | Defines if the revenue is positive or negative. | false |
| revenue (optional) | number | Revenue of the conversion. | 0 |
| metadata (optional) | CustomData[] | Metadata of the conversion. Must be defined beforehand in the Kameleoon App. | undefined |
metadata values are accessible through raw data exports and the results page.If the
metadata parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the addData() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.In the example below, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).- TypeScript
- JavaScript
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The visitor code is empty. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
getEngineTrackingCode()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call thegetEngineTrackingCode() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.
Refer to hybrid experimentation for more information on implementing this method.
- TypeScript
- JavaScript
-
To use this feature, implement both the React SDK and Kameleoon Engine.js. Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing
</body>tag. -
You can insert the returned tracking code directly into an HTML
<script>tag.
123456 and 234567 are experiment IDs, and 7890 and 8901 are variation IDs. In your implementation, the SDK generates these values in the returned tracking code.Arguments
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | Unique identifier of the visitor. |
Return value
| Type | Description |
|---|---|
string | JavaScript code to insert into the page. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
Events
This section provides the methods you use to handle events.- SDK Version 10
onEvent()
MethodonEvent, collected with the useInitialize hook, fires a callback when a specific event is triggered. The callback function has access to the data associated with the event. The SDK methods in this documentation note which event types they can trigger, if any.- TypeScript
- JavaScript
You can only assign one callback to each
EventType.Events
Events are defined in theEventType enum. Depending on the event type, the eventData parameter will have a different type.| Type | eventData type | Description |
|---|---|---|
EventType.Evaluation | EvaluationEventDataType | Triggered when the SDK evaluates any variation for a feature flag. It is triggered regardless of the result variation |
EventType.ConfigurationUpdate | ConfigurationUpdateEventDataType | Triggered when the SDK receives a configuration update from the server (when using real-time streaming) |
Arguments
| Name | Type | Description |
|---|---|---|
| event (required) | EventType | a type of the event to associate the callback action with |
| callback (required) | (eventData: EventDataType<EventType>) => void | a callback function with the eventData parameter that will be called when a configuration update occurs |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |
Sending exposure events to external tools
Kameleoon offers built-in integrations with various analytics and CDP solutions, such as Mixpanel, Google Analytics 4, Segment…. To ensure that you can track and analyze your server-side experiments, Kameleoon provides a methodgetEngineTrackingCode() that returns the JavasScript code to be inserted in your page to automatically send the exposure events to the analytics solution you are using. The SDK builds a tracking code for your active analytics solution based on the experiments that the visitor has triggered in the last 5 seconds.
For more information about hybrid experimentation, please refer to this documentation.To benefit from this feature, you will need to implement both the React SDK and our Kameleoon JavaScript tag. We recommend you implement the [Kameleoon asynchronous tag], which you can install before your closing
<body> tag in your HTML page, as it will be only used for tracking purposes.Data types
Kameleoon Data types are helper classes used for storing data in storage in predefined forms. During the flush execution, the SDK collects all the data and sends it along with the tracking request. Data available in the SDK is not available for targeting and reporting in the Kameleoon app until you add the data. For example, by using theaddData() method.
See use visit history to target users for more information.
If you are using hybrid mode, you can call
getRemoteVisitorData() to automatically fill all data that Kameleoon has collected previously.Browser
Since React SDK
10.11.0, Browser is automatically detected based on the User-Agent string. However, you can still manually override it if needed.Each visitor can only have one
Browser. Adding a second Browser overwrites the first one.| Name | Type | Description |
|---|---|---|
| browser (required) | BrowserType | predefined browser type (Chrome, InternetExplorer, Firefox, Safari, Opera, Other) |
| version (optional) | number | version of the browser, floating point number represents major and minor version of the browser |
- TypeScript
- JavaScript
UniqueIdentifier
UniqueIdentifier data is used as marker for unique visitor identification.
If you add UniqueIdentifier for a visitor, visitorCode is used as the unique visitor identifier, which is useful for Cross-device experimentation. Associating a UniqueIdentifier with a visitor notify SDK that the visitor is linked to another visitor.
The UniqueIdentifier can also be useful in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
Each visitor can only have one
UniqueIdentifier. Adding another UniqueIdentifier overwrites the first one.| Name | Type | Description |
|---|---|---|
| value (required) | boolean | value that specifies if the visitor is associated with another visitor, provided false will imply that the visitor is not associated with any other visitor |
- TypeScript
- JavaScript
Conversion
TheConversion data set stored here can be used to filter experiment and personalization reports by any goal associated with it.
ConversionParametersType conversionParameters - an object with conversion parameters described below
| Name | Type | Description | Default |
|---|---|---|---|
| goalId (required) | number | ID of the goal. | |
| revenue (optional) | float | Revenue of the conversion | 0 |
| negative (optional) | boolean | Defines if the revenue is positive or negative. | false |
| metadata (optional) | CustomData[] | Metadata of the conversion. | undefined |
- TypeScript
- JavaScript
Cookie
Cookie contains information about the cookie stored on the visitor’s device.
-
Generally, the React SDK will attempt to use a
localStoragecookie for the conditions. If not possible, SDK can useCookiedata as an alternative. -
Each visitor can only have one
Cookie. Adding a secondCookieoverwrites the first one.
| Name | Type | Description |
|---|---|---|
| cookie (required) | CookieType[] | A list of CookieType objects consisting of cookie keys and values |
- TypeScript
- JavaScript
Methods
Cookie data has a static utility method fromString that you can use to create a cookie instantly by parsing a string that contains valid cookie data.
The method accepts string as parameter and returns an initialized Cookie instance.
- TypeScript
- JavaScript
GeolocationData
GeolocationData contains the visitor’s geolocation details
Each visitor can only have one
GeolocationData. Adding a second GeolocationData overwrites the first one.GeolocationInfoType containing the following fields:
| Name | Type | Description |
|---|---|---|
| country (required) | string | The country of the visitor |
| region (optional) | string | The region of the visitor |
| city (optional) | string | The city of the visitor |
| postalCode (optional) | string | The postal code of the visitor |
| coordinates (optional) | [number, number] | Coordinates array tuple of two position values (longitude and latitude). Coordinate number represents decimal degrees |
- TypeScript
- JavaScript
CustomData
To retain custom data for future visits, the SDK transmitsCustomData with a Visitor scope during the next tracking request. You can configure the scope in the data settings on the custom data dashboard.
CustomData allows you to associate any type of data with each visitor easily. This data can then be used as a targeting condition in segments or as a filter or breakdown in experiment reports.
For more information about custom data, please refer to this article.
| Name | Type | Description | Default |
|---|---|---|---|
| index/name (required) | number/string | Index or Name of the custom data. Either index or name must be provided to identify the data. | |
| overwrite (optional) | boolean | Flag to explicitly control how the values are stored and how they appear in reports. See more | true |
| value (required) | string[] | The custom data value. It must be stringified to match the string type. Note: value is variadic. |
-
Each visitor is allowed only one
CustomDatafor each uniqueindex. Adding anotherCustomDatawith the sameindexwill replace the existing one. - The custom data ‘index’ can be found in the Custom Data dashboard under the “INDEX” column.
- To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: Use this data only locally for targeting purposes when creating custom data.
-
Adding a
CustomDatainstance created with a name when the SDK instance is not initialized or the name is not registered, will result in the data being ignored.
- TypeScript
- JavaScript
Device
Since React SDK
10.11.0, Device is automatically detected based on the User-Agent string. However, you can still manually override it if needed.React Native: Support for this feature is currently experimental and may require adjustments to work correctly. In React Native, the Device is automatically detected based on the DPI from react-native.Dimensions.Each visitor can only have one
Device. Adding a second Device overwrites the first one.| Name | Type | Description |
|---|---|---|
| deviceType (required) | DeviceType | possible types for device type (PHONE, TABLET, DESKTOP) |
- TypeScript
- JavaScript
OperatingSystem
Since React SDK
10.11.0, OperatingSystem is automatically detected based on the User-Agent string. However, you can still manually override it if needed.React Native: Support for this feature is currently experimental and may require adjustments to work correctly. In React Native, the OperatingSystem is automatically detected based on the react-native.Platform.OperatingSystem contains the visitor’s operating system information.
Each visitor can only have one
OperatingSystem. Adding a second OperatingSystem overwrites the previous one.| Name | Type | Description |
|---|---|---|
| operatingSystem (required) | OperatingSystemType | possible types for device type: WINDOWS_PHONE, WINDOWS, ANDROID, LINUX, MAC, IOS |
- TypeScript
- JavaScript
PageView
Since React SDK
10.11.0, PageView is automatically detected based on the window.location?.href and document.title. However, you can still manually override it if needed.React Native: Support for this feature is currently experimental and may require adjustments to work correctly.Each visitor can have one
PageView per unique URL. Adding a PageView with the same URL as an existing one will notify SDK that the visitor revisited pagePageViewParametersType pageViewParameters - an object with page view parameters described below
| Name | Type | Description |
|---|---|---|
| urlAddress (required) | string | url address of the page to track |
| title (required) | string | title of the web page |
| referrer (optional) | number[] | an optional parameter containing a list of referrers Indices, has no default value |
- TypeScript
- JavaScript
UserAgent
Store information on the user-agent of the visitor. Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses theUserAgent field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on bot filtering.
If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.
A visitor can only have one
UserAgent. Adding a second UserAgent overwrites the first one.| Name | Type | Description |
|---|---|---|
| value (required) | string | value used for comparison |
- TypeScript
- JavaScript
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
| Name | Type | Description |
|---|---|---|
| version (optional) | string | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch. |
- TypeScript
- JavaScript
Returned Types
DataFile
TheDataFile contains the SDK configuration details.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Name | Type | Description |
|---|---|---|
| featureFlags | Map<string, FeatureFlag> | A map of FeatureFlag objects, keyed by feature flag keys. |
| dateModified | number | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
- TypeScript
- JavaScript
FeatureFlag
TheFeatureFlag represents a set of properties that define a feature flag itself — for example, its Variations, Rules, environment status, and other related details.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Name | Type | Description |
|---|---|---|
| environmentEnabled | boolean | Indicating whether the feature flag is enabled in the current environment. |
| defaultVariationKey | string | The key of the default variation associated with the feature flag. |
| variations | Map<string, Variation> | A map of Variation objects, keyed by variation keys. |
| rules | Rule[] | A list of Rule objects |
- TypeScript
- JavaScript
Rule
TheRule represents a set of properties that define a rule itself — for example, its Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Name | Type | Description |
|---|---|---|
| variations | Map<string, Variation> | A map of Variation objects, keyed by variation keys. |
- TypeScript
- JavaScript
Variation
Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
| Name | Type | Description |
|---|---|---|
| name | string | name of the variation. |
| key | string | key of the variation. |
| id | number or null | id of the variation or null if the visitor landed on the default variation. |
| experimentId | number or null | id of the experiment or null if the visitor landed on the default variation. |
| variables | Map<string, Variable> | map of variables for the variation, where key is the variable key and value is the variable object. |
- Ensure that your code handles the case where
idorexperimentIdmay benull, indicating a default variation. - The
variablesmap might be empty if no variables are associated with the variation.
- TypeScript
- JavaScript
Variable
Variable contains information about a variable associated with the assigned variation.
| Name | Type | Description |
|---|---|---|
| key | string | The unique key identifying the variable. |
| type | string | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS. |
| value | any | The value of the variable, which can be of the following types: boolean, number, String, Record<string, any>, any[]. |
- TypeScript
- JavaScript
Deprecated methods
getFeatureFlagVariationKey()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation
Use the
getVariation method.getFeatureFlagVariationKey(), which is used with the useFeatureFlag hook, retrieves the variation key for a visitor identified by their visitorCode. This process includes checking the targeting criteria, identifying the appropriate variation assigned to the visitor, storing this information, and sending a tracking request.
If a user has never been associated with a feature flag, the SDK will randomly return a variation key according to the rules of that feature flag. If the user is already linked to the feature flag, the SDK will identify the previously assigned variation key. If the user does not meet any of the specified rules, the SDK will return the default value defined in Kameleoon’s feature flag delivery rules. It’s important to note that the default value may not always be a variation key; it could also be a boolean value or another data type, depending on how the feature flag is configured.
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
| featureKey (required) | string | a unique key for feature flag |
Return value
| Type | Description |
|---|---|
string | a string containing variable key for the allocated feature flag variation for the provided visitor. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for the specified featureKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled for the current environment |
getVisitorFeatureFlags()
- 🚫 Doesn’t send Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation(for each feature flag)
Use the
getVariations method.getVisitorFeatureFlags method, utilized with the useFeatureFlag hook, returns a list of active feature flags that target the visitor associated with the visitorCode (the visitor must have one of the allocated variations).
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
Return value
| Type | Description |
|---|---|
FeatureFlagType[] | list of feature flags, each feature flag item contains id and key. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageRead | Error while reading storage data |
getActiveFeatureFlags()
- 🚫 Doesn’t send Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation(for each feature flag)
Use the
getVariations method.getActiveFeatureFlags method, collected with the useFeatureFlag hook, returns a Map, where key is feature key and value is detailed information about the visitor’s variation and it’s variables
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
Return value
| Type | Description |
|---|---|
Map<string, KameleoonVariationType> | a map of feature flags, where key is feature key and value is detailed information about the visitor’s variation and it’s variables |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length of 255 characters |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageRead | Error while reading storage data |
KameleoonException.NumberParse | Couldn’t parse Number value |
KameleoonException.JSONParse | Couldn’t parse JSON value |
getFeatureFlagVariable()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation
Use the
getVariation method.getFeatureFlagVariable method, collected with useFeatureFlag hook, returns a variable for the visitor under visitorCode in the found feature flag, this includes targeting check, finding the according variation exposed to the visitor and saving it to storage along with sending tracking request.
- TypeScript
- JavaScript
Arguments
Parameters object of typeGetFeatureFlagVariableParamsType containing the following fields:
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
| featureKey (required) | string | a unique key for feature flag |
| variableKey (required) | string | key of the variable to be found for a feature flag with the specified featureKey, can be found on Kameleoon Platform |
Return value
| Type | Description |
|---|---|
FeatureFlagVariableType | a variable object containing type and value fields. You can check the type field against VariableType enum. For example, if the type is VariableType.BOOLEAN then value will be a boolean type. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for the specified featureKey |
KameleoonException.FeatureFlagVariableNotFound | No feature variable was found for the specified visitorCode and variableKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled for the current environment |
KameleoonException.JSONParse | Couldn’t parse JSON value |
KameleoonException.NumberParse | Couldn’t parse Number value |
getFeatureFlagVariables()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation(for each feature flag)
Use the
getVariations method.getFeatureFlagVariables method, collected with the useFeatureFlag, hook returns a list of variables for the visitor under visitorCode in the found feature flag, this includes targeting check, finding the according variation exposed to the visitor and saving it to storage along with sending tracking request.
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
| featureKey (required) | string | a unique key for feature flag |
Return value
| Type | Description |
|---|---|
FeatureVariableResultType[] | a list of variable objects containing key, type and value fields. You can check the type field against VariableType enum. For example, if the type is VariableType.BOOLEAN then value will be a boolean type. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for the specified featureKey |
KameleoonException.FeatureFlagVariationNotFound | No feature variation was found for the specified visitorCode and variableKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled for the current environment |
KameleoonException.JSONParse | Couldn’t parse JSON value |
KameleoonException.NumberParse | Couldn’t parse Number value |
onConfigurationUpdate()
Use the
onEvent method with EventType.ConfigurationUpdate instead.onConfigurationUpdate collected with useInitialize hook fires a callback on client configuration update.
This hook only works for server sent events of real time update
- TypeScript
- JavaScript
Arguments
| Name | Type | Description |
|---|---|---|
| callback (required) | () => void | callback function with no parameters that will be called upon configuration update |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call |
getFeatureFlags()
🚫 Doesn’t send Tracking Data to Kameleoon ThegetFeatureFlags method collected with the useFeatureFlag hook returns a list of feature flags stored in the client configuration.
- TypeScript
- JavaScript
Return value
| Type | Description |
|---|---|
FeatureFlagType[] | list of feature flags, each feature flag item contains id and key. |
Exceptions thrown
| Type | Description |
|---|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call |