0.8.5. See the C++ SDK changelog for release notes, or the SDK changelog index for all SDKs.
SDK methods: For the full reference documentation of the C++ SDK, see the reference section.
Developer guide
This guide is designed to help you integrate the C++ SDK quickly and start evaluating feature flags in your C++ app.Getting started
Install the C++ client
The C++ SDK is a C++17 library built on top of the Kameleoon SDK Core, a native shared library (libkameleoon_ffi) written in Rust that implements the SDK behavior. Your app links the C++ library statically and loads the core library at runtime.
Requirements:
- A C++17 compiler (GCC, Clang, or MSVC) and CMake 3.16 or later.
- Rust 1.91 or later, Cargo, and
cbindgento build the SDK Core library (libkameleoon_ffi.soon Linux,libkameleoon_ffi.dylibon macOS,kameleoon_ffi.dllwith its import librarykameleoon_ffi.dll.libon Windows).
cpp/client directory with add_subdirectory() and link the Kameleoon::CppClient target. Point KAMELEOON_FFI_LIBRARY to the core library you built; the C header is generated with cbindgen, or you can pass an existing one with KAMELEOON_FFI_HEADER:
CMakeLists.txt
libkameleoon_ffiis loaded at runtime: install it to a standard library location, or ship it next to your executable. On Linux and macOS, shipping it next to the executable requires an RPATH of$ORIGINor@loader_path(for example,set_target_properties(my_app PROPERTIES INSTALL_RPATH "$ORIGIN")). On Windows, copykameleoon_ffi.dllnext to your binaries.- When you create a client, the SDK checks that the loaded
libkameleoon_ffimatches the version it was built against and throws aKameleoonExceptionwithErrorCode::Internalotherwise. Always upgrade the C++ library and the core library together. - All public SDK types live in the
kameleoonnamespace. Includekameleoon/kameleoon.hppto get the whole public API.
Additional configuration
Create a JSON configuration file (for example,client-cpp.json) to provide credentials and customize SDK behavior. You can also download a sample configuration file.
The C++ SDK can be configured either with a JSON file whose path you pass to KameleoonClientFactory::create(), or by filling a KameleoonClientConfig struct directly in code.
The following table shows the available properties that you can set:
Initialize the Kameleoon client
After you have installed the SDK and configured your credentials, create aKameleoonClient by using KameleoonClientFactory.
- Config File
- Code
The examples on this page use C++20 designated initializers (
GetVariationOptions{.track = false}) to fill the SDK’s configuration, options, and data structs. With a C++17 compiler, declare the struct and set its fields one by one instead.KameleoonClient is the main object used to evaluate feature flags, add visitor data, and send tracking requests.
Activating a feature flag
Assigning a unique ID to a user
To assign a unique ID to a user, you can use theget_visitor_code() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a default_visitor_code 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 get_visitor_code() method ensures that the app file engine.js (previously named, kameleoon.js) and the SDK share the unique ID (visitor code).
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 theget_variation() or is_feature_active() method to retrieve the configuration based on the feature_key.
The get_variation() 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 feature_key and visitor_code.
You can use the is_feature_active() method 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) get_variation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the feature flag targets the user, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK sends the exposure event to the specified experiment on the next tracking request, which it triggers automatically based on the SDK’s tracking_interval_millis. The default interval is 1000 milliseconds (1 second).
The get_variation() method allows you to control whether the SDK tracks the visitor. If track=false, the SDK sends no exposure events. This option 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 get_variations() 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 theadd_data() 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 get_remote_visitor_data() method. This method asynchronously fetches data from the servers. It’s important to call get_remote_visitor_data() before retrieving the variation or checking if the feature flag is active, because the SDK might need this data 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’s recorded as a conversion. To track conversions, use thetrack_conversion() method and provide the required visitor_code and goal_id parameters.
The SDK sends the conversion tracking request along with the next scheduled tracking request, which occurs at regular intervals (defined by tracking_interval_millis). If you prefer to send the request immediately, use the flush_instant() method.
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 theget_engine_tracking_code() method.
The get_engine_tracking_code() 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.
Error handling
Every error the SDK raises is aKameleoonException, so a single handler for that type catches every SDK failure. Handle a specific error type when your app needs to react to a particular failure, for example to fall back to your default behavior when a feature flag isn’t in the configuration or the SDK isn’t initialized yet. The reference section of each method lists the errors it can raise.
KameleoonException derives from std::runtime_error. Call code() to get the ErrorCode that tells the errors apart, and what() to get the message.
Strings passed to the SDK must be valid UTF-8. Callbacks you provide to the SDK (
CookieAccessor overrides, event handlers, and loggers) must not throw: any exception that escapes them is caught at the SDK boundary and discarded.SDK errors are expected behavior, not crashes: a feature flag that isn’t activated yet, an SDK that is still loading its configuration, or a network failure are all normal conditions. When feature evaluation fails, log the error and fall back to your default behavior so the visitor still gets a working experience.
Asynchronous operations
The network-bound operations (initialize(), flush_instant(), get_remote_data(), get_remote_visitor_data(), and get_visitor_warehouse_audience()) run on the SDK’s own worker thread. Each comes in three forms, so you can pick the one that fits the calling thread:
Completion<void> (std::function<void(std::exception_ptr)>), or a Completion<T> (std::function<void(std::exception_ptr, T)>) for operations that return a value. The SDK invokes it exactly once. You can omit the completion to run the operation fire-and-forget: failures then only appear in the SDK log.
C++20 has no built-in coroutine task type, so
co_await only works inside a coroutine whose promise type accepts the SDK’s Awaitable<T> (KAMELEOON_HAS_COROUTINES is defined by kameleoon/async.hpp when coroutines are available). By default the coroutine resumes on the SDK worker thread; call .via(executor) on the awaitable to resume on your own event loop instead. Frameworks with their own coroutine types, such as Boost.Asio, need a small adapter around the completion form; see the server example shipped with the SDK.get_visitor_code(), get_variation(), get_variations(), is_feature_active(), add_data(), track_conversion(), and flush()) are synchronous in-memory calls and need none of this.
Using a custom bucketing key
By default, Kameleoon uses a unique, anonymous visitor ID (visitor_code) 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, and 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 visitor_code.
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
account_id. 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 app’s data:- Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the
add_data()method. In this method, you will pass your chosen custom bucketing key as aCustomDataobject. Here,new_visitor_coderefers to the identifier you wish to use for your bucketing (for example, the newuser_idoraccount_id).
- Bucketing logic: Once you provide a custom bucketing key through the
add_data()method, all hash calculations for assigning users to variations use thisnew_visitor_code(your custom key) instead of the defaultvisitor_code. Using thenew_visitor_codemeans that the bucketing decision depends on 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
new_visitor_code(your custom key) is used for bucketing decisions, the SDK sends all subsequent data (tracking events and conversions, for example) and associates it with the originalvisitor_code. This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment’s broader context, even when you bucket 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
std::string. - It must be unique for the entity you intend to bucket (for example, if using a
user_id, each user’s ID should be unique). - The key must be available to the SDK at the exact moment it evaluates the feature flag decision 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 this SDK supports, see use visit history to target users. You can also use your own external data to target users.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 aligns visitor data across devices, it’s not always necessary. Below are two scenarios where custom mapping sync isn’t required: Same user ID across devices If you use the same user ID consistently across all devices, the SDK handles synchronization automatically without a custom mapping sync. It’s enough to call theget_remote_visitor_data() 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 get_remote_visitor_data()) is sufficient without additional custom mapping sync.
Customers who need additional data can refer to the get_remote_visitor_data() method description for further guidance. In the below code, it’s assumed that you use the same unique identifier (in this case, the visitor_code, also known as userId) 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.
Device A
Device B
Using custom data for session merging
Cross-device experimentation allows for combining a visitor’s history across each of their devices (history reconciliation). History reconciliation allows merging different visitor sessions into one. To reconcile visit history, useCustomData to provide a unique identifier for the visitor. For more information, see the dedicated documentation.
After you enable cross-device reconciliation, calling get_remote_visitor_data() with the parameter userId retrieves all known data for a given user.
Sessions with the same identifier always see the same variation in an experiment. In the Visitor view of your experiment’s results pages, these sessions will appear as a single visitor.
The SDK configuration ensures that associated sessions always see the same variation of the experiment. However, there are some limitations regarding cross-device variation allocation. The cross-device experimentation documentation outlines these limitations.
Follow the activating cross-device history reconciliation guide to set up your custom data on the Kameleoon platform.
Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:
get_remote_visitor_data()with addedUniqueIdentifier(true)- to retrieve data for all linked visitors.track_conversion()orflush()with addedUniqueIdentifier(true)data - to track some data for specific visitor that’s associated with another visitor.
get_visitor_code() method. After the user logs in, the app associates the anonymous visitor with the user ID and uses it as a unique identifier for the visitor.
Logging
The SDK generates logs to reflect various internal processes and issues.Log levels
The SDK supports configuring limiting logging by a log level.Custom handling of logs
The SDK writes its logs to the console output by default. This behaviour can be overridden.The SDK limits logging by log level separately from the log handling logic.
Reference
This is the full reference documentation for the C++ SDK.Initialization
create()
To use the SDK, create aKameleoonClient with KameleoonClientFactory::create(), either from a KameleoonClientConfig struct or from a JSON configuration file.
Clients are cached per site code and environment: repeated create() calls with the same site code and environment return clients over the same underlying SDK instance, and the configuration of the first call wins.
- create(config struct)
- create(config file)
Parameters
Return value
Exceptions
initialize()
Useinitialize() when your app should wait for the Kameleoon client to finish initialization before it evaluates feature flags.
The call returns the result of the configuration fetch: it completes successfully when the client finishes initializing, and fails if the initial configuration fetch fails before the client becomes ready. Background retries continue after that first failure. Once a retry succeeds, subsequent calls return a successful result. If no initialization result is available before the timeout expires, the call fails. If you don’t provide a timeout value, the SDK uses the default timeout from default_timeout_millis.
Parameters
Return value
Exceptions
is_ready()
is_ready() checks whether the SDK is ready for use, which means its configuration has been successfully loaded. Unlike initialize(), this method returns immediately without blocking or throwing.
Return value
forget()
Removes the cached SDK client associated with the specifiedsite_code, so the next create() call with the same site code and environment creates a new one.
forget() only drops the factory’s reference. Every KameleoonClient created for that site code keeps the underlying SDK instance (and its worker thread, polling, and tracking) alive until it’s destroyed, and outstanding asynchronous operations keep it alive until their completions finish. To release the background resources, call forget() and destroy all KameleoonClient instances of that site code.
Parameters
Feature flags and variations
is_feature_active()
- 📨 Sends tracking data to Kameleoon (depending on the
trackoption)
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as
is_feature_active(), get_variation() or get_variations().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 get_variations() 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 5 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.Parameters
Return value
Exceptions
get_variation()
- 📨 Sends Tracking Data to Kameleoon (depending on the
trackparameter)
Variation assigned to a given visitor for a specific feature flag.
This method takes a visitor_code and feature_key as mandatory arguments. The track argument is optional and defaults to true.
It returns the assigned Variation for the visitor. If the visitor isn’t associated with any feature flag rules, the method returns the default Variation for the given feature flag.
Ensure your code includes proper error handling to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they don’t match any predefined delivery rules for a feature flag. In other words, it’s the fallback variation applied to all users who aren’t targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Parameters
The optional
track parameter is passed as the track field of a GetVariationOptions struct.Return value
Exceptions
get_variations()
- 📨 Sends Tracking Data to Kameleoon (depending on the
trackparameter)
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 visitor_code as a mandatory argument, while only_active and track are optional.
- If you set
only_activetotrue, the methodget_variations()returns feature flag variations only if the visitor isn’t bucketed with theoffvariation. - The
trackparameter controls whether the method tracks the variation assignments. By default, it’strue. If it’sfalse, the method doesn’t track variation assignments.
Variation as values. If the SDK assigns no variation for a feature flag, the method returns the default Variation for that flag.
Implement proper error handling to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they don’t match any predefined delivery rules for a feature flag. In other words, it’s the fallback variation applied to all users who aren’t targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Parameters
The optional
only_active and track parameters are passed as the fields of a GetVariationsOptions struct.Return value
Exceptions
set_forced_variation()
The method allows you to programmatically assign a specificVariation to a user, bypassing the standard evaluation process. The method is especially valuable for controlled experiments where the usual evaluation logic isn’t required or you need to skip it. It can also be helpful in scenarios like debugging or custom testing.
When you set a forced variation, it overrides Kameleoon’s real-time evaluation logic. The SDK skips processes like segmentation, targeting conditions, and algorithmic calculations. To preserve segmentation and targeting conditions during an experiment, set force_targeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation starts, the SDK fully processes and completes it first.
Parameters
The optional
force_targeting parameter is passed as the force_targeting field of a SetForcedVariationOptions struct.Exceptions
evaluate_audiences()
- 📨 Sends Tracking Data to Kameleoon
evaluate_audiences() after you set or update all relevant visitor data, and just before getting a feature variation or checking a feature flag. This approach ensures that Kameleoon evaluates the visitor 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.
Parameters
Exceptions
In most cases, you only need to handle the basic error,
KameleoonException, as the example demonstrates. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, you can handle general language errors by including std::exception.get_datafile()
Returns the current SDK configuration as aDataFile object.
The returned DataFile is a copy of the current configuration: it doesn’t change when the SDK refreshes its configuration.
Return value
Exceptions
Visitor data
get_visitor_code()
Useget_visitor_code() to obtain the current visitor’s Kameleoon visitor_code. The method works with any cookie store that implements the CookieAccessor interface.
The implementation logic is as follows:
- The SDK checks whether a
kameleoonVisitorCodecookie is already available through the provided accessor. - If the cookie is absent, the SDK uses
default_visitor_codewhen you provide one. - Otherwise, the SDK generates a new visitor code and stores it through the accessor.
The
get_visitor_code() method allows you to set simulated variations for a visitor. When cookies (from a request or document) contain the key kameleoonSimulationFFData, the method reads the cookie and stores the simulated variations for that visitor; its return value doesn’t change. Subsequent feature evaluations for the visitor, such as get_variation() and is_feature_active(), then bypass the standard evaluation process and return the simulated 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, Kameleoon creates the cookie automatically when you simulate 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.CookieAccessor interface
Implement kameleoon::CookieAccessor to bridge SDK cookie reads and writes to your HTTP framework:
get()must return a cookie already written throughset()on the response in preference to the request cookie of the same name. The SDK keeps no cookie state between calls, so this is what makes a secondget_visitor_code()call within the same request return the code written by the first one instead of generating a new one.- The overrides are invoked from inside the SDK and must not throw. An exception escaping
get()is treated as an absent cookie. Cookie values must be valid UTF-8.
- Custom
- Drogon
Parameters
Return value
Exceptions
add_data()
Theadd_data() method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.
The add_data() method doesn’t return any value and doesn’t interact with Kameleoon backend servers on its own. Instead, the SDK saves all the declared data for future transmission using the flush() method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that’s triggered by the flush().
The track_conversion() method also sends out any previously associated data, just like the flush(). The same holds true for get_variation() and get_variations() methods if an experimentation rule is triggered.
The data parameter is a std::vector<Data>, where Data is a std::variant of all the data types. Each data type converts implicitly to Data, so you can pass a braced list of data objects.
Parameters
Exceptions
flush()
- 📨 Sends tracking data to Kameleoon
flush() method aggregates all Kameleoon data associated with a visitor and sends a tracking request to the server. This request includes any data previously added via the add_data method that hasn’t yet been transmitted through other tracking mechanisms (see the referenced methods for details). The flush() operation is non-blocking, as the server call is performed asynchronously.
This method provides control over when data linked to a specific visitor_code is transmitted. For example, if add_data() is called multiple times, sending a request after each invocation would be inefficient. Instead, you can batch these updates and call flush() once to send all accumulated data in a single request.
The flush() method uses the provided visitor_code as the unique visitor identifier.
Parameters
Exceptions
get_remote_data()
Theget_remote_data() method lets you retrieve remote data stored on Kameleoon servers for the specified key. In most setups, this data is written through the Kameleoon Data API and can later be fetched by your C++ service whenever you need additional app context.
This method is useful when you want to keep structured information on Kameleoon’s remote infrastructure and reuse it from your back-end without maintaining a separate retrieval mechanism.
Parameters
Return value
Exceptions
get_remote_visitor_data()
get_remote_visitor_data() retrieves Kameleoon visit data for the provided visitor_code. The method adds the data to local visitor storage so other SDK methods can use it for targeting decisions.
Data obtained using this method is especially useful when you want to:
- use data collected from other devices.
- access a visitor’s history, such as previously viewed pages from past visits.
- use data that’s only available on the client side, such as datalayer variables and front-end goal conversions.
Parameters
Exceptions
Using parameters in get_remote_visitor_data()
Theget_remote_visitor_data() method lets you control which data is retrieved for a visitor. The same filtering approach works across goals, experiments, variations, and other visitor data.
For example, if you want to target users who converted on a goal during their last five visits, you can set previous_visit_amount to 5 and conversions to true.
The flexibility shown in this example isn’t limited to goal data. You can use the filter to retrieve many different visitor behaviors and make them available to targeting and reporting logic in your C++ app.
RemoteVisitorDataFilter fields
get_visitor_warehouse_audience()
This method retrieves audience data associated with a visitor in your warehouse integration by using the specifiedvisitor_code and, optionally, a warehouse_key. The warehouse_key is typically your internal user ID. The custom_data_index parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors.
When the call succeeds, the SDK converts the returned audience list into CustomData, adds it to the visitor locally, and makes it available for targeting purposes. For more background, see the warehouse targeting documentation.
Parameters
Exceptions
set_legal_consent()
You must use this method to specify whether the visitor has given legal consent to use personal data. Settingconsent to false limits the types of data that can be included in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. For more information, see the consent management policy.
If you pass a CookieAccessor, the SDK also updates the visitor cookies according to the consent status.
Parameters
Exceptions
Consent revocation behavior
When you callset_legal_consent() with consent=false, the SDK doesn’t 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 won’t remove the file automatically.
Goals and third-party analytics
track_conversion()
- 📨 Sends Tracking Data to Kameleoon
visitor_code and goal_id. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitor_code is usually identical to the one you used when triggering the experiment.
Parameters
The optional
revenue, negative, and metadata parameters are passed as the fields of a TrackConversionOptions struct.metadata values are accessible through raw data exports and the results page.If you provide the
metadata parameter, Kameleoon uses these specified values for the current conversion instead of what you previously collected using the add_data() method. If you omit the parameter, Kameleoon uses 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 track_conversion() 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’).Exceptions
get_engine_tracking_code()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call theget_engine_tracking_code() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous 5 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.
- To use this feature, implement both the C++ SDK and Kameleoon Engine.js. Because this flow uses Engine.js only for tracking, you can install the asynchronous tag before the closing
</body>tag. - If you only want to track experiments in Kameleoon and don’t need to send exposure events to third-party analytics tools, use the JavaScript / TypeScript SDK. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call
getVisitorCode, as long as you add the corresponding experiment assignments towindow.kameleoonQueue. - 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.Parameters
Return value
Exceptions
Events
set_event_handler()
Use this method to register a handler for SDK events. The SDK calls the handler when the selected event occurs. The client keeps at most one handler per event type: registering a new handler for the same event type replaces the previous handler. TheEventHandler constructor you use (EventHandler::datafile_update() or EventHandler::http_request()) selects the event type, so a handler and the events it receives can’t get out of sync. Passing an empty std::function ({}) removes the current handler for the selected event type.
- datafile_update
- http_request
Handlers are called synchronously on the SDK’s single worker thread, so they must not block: time spent in a handler delays data file polling and tracking flushes. They must be thread-safe and must not throw: an exception escaping a handler is caught and discarded, and never affects SDK behavior. Don’t call blocking SDK operations from a handler; use the
*_async forms and finish the work on an application thread instead.An invocation already in progress may finish after you clear the handler or destroy the client, and the handler (with its captures) is destroyed on an SDK thread once it’s no longer in use. Keep captured objects alive and thread-safe accordingly. A handler may clear or replace itself.All KameleoonClient instances created for the same site code and environment share one handler per event type: the last handler set wins, and destroying any of those instances clears it. Keep a single client instance per site code and environment.Parameters
Data types
This section lists the C++ data types declared by the SDK in thekameleoon namespace (kameleoon/data/*.hpp). All of them are plain structs that you pass to add_data().
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
Browser
TheBrowser data set stored here can be used to filter experiment and personalization reports by any value associated with it.
Conversion
TheConversion data set stored here can be used to filter experiment and personalization reports by any goal associated with it.
Cookie
Cookie contains information about the cookies stored on the visitor’s device.
CustomData
CustomData enables the association of any type of data with each visitor, making it an effective tool for targeting conditions in segments. Additionally, it can be used as a filter or breakdown in experiment reports. For more information about custom data, refer to this article.
Define custom data types in the Kameleoon app or the Data API and use them from the SDK.
CustomData has two constructors: one identifies the custom data by its id (index), the other by its name.
-
Each visitor is allowed only one
CustomDatafor each uniqueid(name). Adding anotherCustomDatawith the sameid(name) will 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 isn’t initialized or the name isn’t registered, will result in the data being ignored.
Device
You can use device data to filter experiment and personalization reports by any associated value.Geolocation
Geolocation contains the visitor’s geolocation details.
OperatingSystem
OperatingSystem contains information about the operating system on the visitor’s device.
PageView
Store page view events.The referrer index is available in the Kameleoon app on the acquisition channel configuration page. Be careful: the index starts at
0, so the first acquisition channel you create has the ID 0, not 1.UniqueIdentifier
If you don’t addUniqueIdentifier for a visitor, visitor_code is used as the unique visitor identifier, which is useful for cross-device experimentation. When you add UniqueIdentifier{true}, the SDK links flushed data with the visitor associated with the specified identifier.
This can be useful in situations where you can’t access the anonymous visitor_code originally assigned to a visitor, but you do have access to an internal identifier connected to that visitor through session merging.
UserAgent
Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to recognize known bots and spiders, and it also uses theUserAgent field to filter out other unwanted traffic that might distort your conversion metrics. For more information, see the help article on bot filtering.
If you use internal bots, send the user-agent value curl/8.0 to exclude them from analytics.
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, contact your Customer Success Manager.
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, contact your Customer Success Manager.
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, contact your Customer Success Manager.
Variation
Variation contains information about the visitor’s assigned variation, or the default variation when no specific assignment exists.
Variationdescribes the assigned or default variation, whileVariablecontains the details of each individual variable.idandexperiment_idcan bestd::nullopt, which indicates a default variation that’s not tied to a specific experiment assignment.
Variable
Variable contains information about a variable associated with the assigned variation.
JsonValue
JsonValue represents the value of a variation variable in C++. The kind field tells the string-carrying kinds apart; value is a std::variant<bool, double, std::string>.
Typed accessors return
std::nullopt when the value is of another kind: