Skip to main content

JavaScript / TypeScript SDK

With the Kameleoon JavaScript SDK, you can run experiments and activate feature flags. Integrating our SDK into your web application is easy, and its footprint (memory and network usage) is low.

Getting started: For help getting started, see the developer guide.

Changelog: Details on the latest version of JavaScript / TypeScript SDK can be found in the changelog.

SDK methods: For the full reference documentation of the JavaScript SDK, see the reference section.

Developer guide

This section will help you get started as well as introduce you to some of the more advanced concepts.

Getting started

Installation

The Kameleoon SDK Installation tool is the preferred way to install the SDK quickly. The SDK Installer helps you install the SDK of your choice, generate a basic code sample, and configure external dependencies if needed.

To use the SDK Installation tool, install and run it globally:

npm install --global @kameleoon/sdk-installer
kameleoon-sdk

Or run it directly with npx:

npx @kameleoon/sdk-installer
note

You can also inject the JavaScript SDK into your app as a single file using the <script> tag. You can then access all of the SDK methods using the global object KameleoonSDK.

Example:

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My App</title>
<script src="https://static.kameleoon.com/kameleoonSDK-4.1.0.js"></script>
<script type="module" src="app.js"></script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
app.js
const { KameleoonClient, CustomData } = KameleoonSDK;

To always use the latest version of a major release, you can use the following script, where 3 is the current major version:

https://static.kameleoon.com/kameleoonSDK-4-latest.js

To always stay on a specific version, specify the full version number instead. For example, for version 4.1.1, which is the earliest version available as a static script, use the following:

https://static.kameleoon.com/kameleoonSDK-4.1.1.js

Versions can be referenced on the release page.

Initialize the Kameleoon Client

Here is a step-by-step guide for configuring the JavaScript SDK for your application.

import {
Environment,
KameleoonClient,
SDKConfigurationType,
} from '@kameleoon/javascript-sdk';

// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
updateInterval: 20,
environment: Environment.Production,
domain: '.example.com',
};

const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });

// -- Waiting for the client initialization using `async/await`
async function init(): Promise<void> {
await client.initialize();
}

init();

// -- Waiting for the client initialization using `Promise.then()`
client
.initialize()
.then(() => {})
.catch((error) => {});

To start, developers need to create an entry point for JavaScript SDK by creating a new instance of Kameleoon Client.

Use KameleoonClient to run feature experiments and retrieve the status of feature flags and their variations.

KameleoonClient initialization is done asynchronously in order to make sure that Kameleoon API call was successful for that method initialize() is used. You can use async/await, Promise.then() or any other method to handle asynchronous client initialization.

Arguments
NameTypeDescription
siteCode (required)stringThis 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)ExternalsTypeExternal implementation of SDK dependencies (External dependencies)
Configuration Parameters
NameTypeDescriptionDefault Value
updateInterval (optional)numberupdate interval in minutes for sdk configuration, minimum value is 1 minute60
environment (optional)Environmentfeature flag environmentEnvironment.Production
targetingDataCleanupInterval (optional)numberinterval in minutes for cleaning up targeting data, minimum value is 1 minuteundefined (no cleanup will be performed)
cookieDomain (optional)stringdomain that the cookie belongs to.undefined
networkDomain (optional)stringcustom 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 valueundefined
requestTimeout (optional)numbertimeout in milliseconds for all SDK network requests, if timeout is exceeded request will fail immediately10_000 (10 seconds)
trackingInterval (optional)numberSpecifies 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 100 ms and the maximum value is 1_000 ms1_000 (1 second)
note

Make sure not to use several client instances in one application as it is not fully supported yet, which may lead to local storage configuration being overwritten and cause bugs.

Activating a feature flag

Assigning a unique ID to a user

To assign a unique ID to a user, you can use the getVisitorCode() 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 (visitorCode) is shared between the application file (kameleoon.js) and the SDK.

Retrieving a flag configuration

To implement a feature flag in your code, you must first create a feature flag in your Kameleoon account.

To determine if a feature flag is active for a specific user, you need to retrieve its configuration. Use the getFeatureFlagVariationKey() or isFeatureFlagActive() method to retrieve the configuration based on the featureKey.

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.

The getFeatureFlagVariationKey() method retrieves the configuration of a feature experiment with several feature variations. You can use the method to get a variation key for a given user by providing the visitorCode and featureKey as mandatory arguments.

Feature flags can have associated variables that are used to customize their behavior. To retrieve these variables, use the getFeatureFlagVariables() method. This method checks whether the user is targeted, finds the visitor’s assigned variation, saves it to storage, and sends a tracking request.

note

To check if a feature flag is active, you only need to use one method. Choose isFeatureFlagActive if you simply want to know if a feature flag is on or off. For more complex scenarios, like dynamically changing the feature's behavior, use getFeatureFlagVariables.

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 the addData() method to add these data points to the user’s profile.

To retrieve data points that have been collected on other devices or to access past data points about a user (which would have been collected client-side if you are using Kameleoon in Hybrid mode), use the getRemoteVisitorData() method. This method asynchronously fetches data from our servers. However, it is important you 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 of a feature flag.

To learn more about available targeting conditions, read our 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. To ensure your results are accurate, it's recommended to filter out bots by using the userAgent data type. You can learn more about this here. Don't forget to call the flush() method to send the collected data to Kameleoon servers for analysis.

Tracking flag exposition and goal conversions

Kameleoon will automatically track visitors’ exposition to flags as soon as you call one of these methods:

  • getFeatureFlagVariationKey()
  • getFeatureFlagVariable()
  • getFeatureFlagVariables()
  • isFeatureFlagActive()

When a user completes a desired action (for example, making a purchase), it counts as a conversion. To track conversions, you must use the trackConversion() method, and provide the visitorCode and goalId parameters.

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 the getEngineTrackingCode() 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.

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.

import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });

// The `NONE` log level allows no logging.
client.setLogLevel(LogLevel.NONE);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.NONE);


// The `ERROR` log level allows to log only issues that may affect the SDK's main behaviour.
client.setLogLevel(LogLevel.ERROR);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.ERROR);

// The `WARNING` log level allows to log issues which may require an attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
client.setLogLevel(LogLevel.WARNING);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.WARNING);

// The `INFO` log level allows to log general information on the SDK's internal processes.
// It extends the `WARNING` log level.
client.setLogLevel(LogLevel.INFO);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.INFO);

// The `DEBUG` log level allows to log extra information on the SDK's internal processes.
// It extends the `INFO` log level.
client.setLogLevel(LogLevel.DEBUG);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);

Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

note

Logging limiting by a log level is performed apart from the log handling logic.

import { KameleoonClient, KameleoonLogger, IExternalLogger, LogLevel } from '@kameleoon/javascript-sdk';

export class CustomLogger implements IExternalLogger {
// `log` method accepts logs from the SDK
public log(level: LogLevel, message: string): void {
// Custom log handling logic here. For example:
switch (level) {
case LogLevel.DEBUG:
console.debug(message);
break;
case LogLevel.INFO:
console.info(message);
break;
case LogLevel.WARNING:
console.warn(message);
break;
case LogLevel.ERROR:
console.error(message);
break;
}
}
}

const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
logger: new CustomLogger(),
},
});

// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
client.setLogLevel(LogLevel.DEBUG);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);

Domain information

You provide a domain as the domain 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 is www.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 specify domain starting with the ., for instance domain .example.com allows the cookie to function on both app.example.com and login.example.com.

note

You can't use regular expressions, special symbols, protocol, or port numbers in the domain. Additionally, a specific list of subdomains can't be used with the prefix ..

Here's a small domain cheat sheet:

DomainAllowed URLsDisallowed URLs
www.example.comwww.example.comapp.example.com
example.com.com
.example.com = example.comexample.comotherexample.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 domain field in the SDK client while testing. This prevents localhost issues (the cookie will be set on any domain).
  • Create a local domain for localhost. For example:
    • Navigate to /etc/hosts on Linux or to c:\Windows\System32\Drivers\etc\hosts on Windows
    • Open hosts with 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.com as your domain

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.

note

In the JavaScript 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.

Here's the list of available external dependencies:

DependencyInterfaceRequired/OptionalAPI UsedDescription
storageIExternalStorageOptionalBrowser localStorageUsed for storing all the existing and collected SDK data
requesterIExternalRequesterOptionalBrowser fetchUsed for performing all the network requests
eventSourceIExternalEventSourceOptionalBrowser EventSourceUsed for receiving Server Sent Events for Real Time Update capabilities
visitorCodeManagerIExternalVisitorCodeManagerOptionalBrowser cookieUsed for storing and synchronizing visitor code
loggerILoggerOptionalCustom implementationUsed for custom handling of logs from the SDK. Allows to define how logs are processed and where they are output.

The following example implements external dependencies. To import an interface from an SDK, create a class that implements it and pass the instantiated class to the SDK.

Storage

import { IExternalStorage, KameleoonClient } from '@kameleoon/javascript-sdk';

// --- External Storage implementation ---
// - JavaScript `Map` is used as an example storage
const storage = new Map();

class MyStorage<T> implements IExternalStorage<T> {
public read(key: string): T | null {
// - Read data using `key`
const data = storage.get(key);

// - Return `null` if there's no data
if (!data) {
return null;
}

// - Return obtained data
return data;
}

public write(key: string, data: T): void {
// - Write data using `key`
storage.set(key, data);
}
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
storage: new MyStorage(),
},
});

EventSource

import {
IExternalEventSource,
KameleoonClient,
EventSourceOpenParametersType,
} from '@kameleoon/javascript-sdk';

// --- External EventSource implementation ---
// - Example uses native browser `EventSource`
class MyEventSource implements IExternalEventSource {
private eventSource?: EventSource;

public open({
eventType,
onEvent,
url,
}: EventSourceOpenParametersType): void {
// - Initialize `EventSource`
const eventSource = new EventSource(url);

this.eventSource = eventSource;
// - Add event listener with provided event type and event callback
this.eventSource.addEventListener(eventType, onEvent);
}

public close(): void {
// - Cleanup open event source
if (this.eventSource) {
this.eventSource.close();
}
}

public onError(callback: (error: Event) => void): void {
// - Set error callback
if (this.eventSource) {
this.eventSource.onerror = callback;
}
}
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
eventSource: new MyEventSource(),
},
});

VisitorCodeManager

import {
IExternalVisitorCodeManager,
SetDataParametersType,
KameleoonClient,
KameleoonUtils,
} from '@kameleoon/javascript-sdk';

// --- External Visitor Code Manager implementation ---
// - Example uses browser `document.cookie` API
class MyVisitorCodeManager implements IExternalVisitorCodeManager {
public getData(key: string): string | null {
const cookieString = document.cookie;

// - Return `null` if no cookie was found
if (!cookieString) {
return null;
}

// - Parse cookie finding it by provided `key`
return KameleoonUtils.getCookieValue(cookieString, key);
}

public setData({
visitorCode,
domain,
maxAge,
key,
path,
}: SetDataParametersType): void {
// - Set cookie with provided parameters
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;

if (domain) {
resultCookie += `; Domain=${domain}`;
}

document.cookie = resultCookie;
}
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});

Requester

import {
RequestType,
IExternalRequester,
KameleoonResponseType,
SendRequestParametersType,
KameleoonClient,
} from '@kameleoon/javascript-sdk';

// --- External Requester Implementation
export class MyRequester implements IExternalRequester {
public async sendRequest({
url,
parameters,
}: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
// - Using native browser `fetch`
return await fetch(url, parameters);
}
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
requester: new MyRequester(),
},
});

Logger

import { KameleoonClient, KameleoonLogger, IExternalLogger, LogLevel } from '@kameleoon/javascript-sdk';

// --- Custom Logger Implementation
export class CustomLogger implements IExternalLogger {
public log(level: LogLevel, message: string): void {
// Custom log handling logic here.
}
}

// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
logger: new CustomLogger(),
},
});

Error Handling

Almost every KameleoonClient method may throw an error at some point, these errors are not just caveats but rather deliberately predefined KameleoonErrors 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 variants.

To know exactly what variant of KameleoonException the method may throw you can check Throws section of the method description on this page or just hover over the method 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.

import {
KameleoonError,
KameleoonClient,
KameleoonException,
} from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
try {
await client.initialize();

const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
} catch (error) {
// -- Type guard for inferring error type as native JavaScript `catch`
// only infers `unknown`
if (error instanceof KameleoonError) {
switch (error.type) {
case KameleoonException.VisitorCodeMaxLength:
// -- Handle an error
break;
case KameleoonException.StorageWrite:
// -- Handle an error
break;
case KameleoonException.Initialization:
// -- Handle an error
break;
default:
break;
}
}
}
}

init();

Cross-device experimentation

To support visitors who access your app from multiple devices cross-device experimentation, Kameleoon allows you to synchronize your custom data across each of the visitor's devices and reconcile their visit history across each device.

Synchronizing custom data across devices

If you want to synchronize your Custom Data across multiple devices, Kameleoon provides a custom data synchronization mechanism.

To use this feature, in the custom data dashboard, edit the custom data and set the Scope value to Visitor. The custom data will now be permanently associated with a specific visitor as long as getRemoteVisitorData is called before any other actions with the visitor-associated data.

After the custom data is set up, calling getRemoteVisitorData makes the latest data accessible on any device.

See the following example of data synchronization between two devices:

Device One
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
await client.initialize();

// -- Custom Data with index `0` was set to `Visitor` scope
// on Kameleoon Platform
const customDataIndex = 0;
const customData = new CustomData(customDataIndex, 'my_data');

client.addData('my_visitor', customData);
client.flush();
}

init();
Device Two
import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
await client.initialize();

// -- Before working with data, make `getRemoteVisitorData` call
await getRemoteVisitorData({ visitorCode: 'my_visitor_code' });

// -- The further SDK code will have an access to CustomData with `Visitor` scope
// defined on Device One.
// So "my_data" is now available for targeting and tracking for "my_visitor"
}

init();

Using custom data for session merging

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 platform

When your custom data is set up, you can use it in your code to merge a visitor's sessions. 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 visitor

tip

As the custom data you use as the identifier must be set to Visitor scope, you need to use cross-device custom data synchronization to retrieve the identifier with the getRemoteVisitorData method on each device.

Here'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 thegetVisitorCode 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.

Login Page
import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
});

async function init(): Promise<void> {
await client.initialize();

const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `window` to later re-use it
window.anonymousVisitor = anonymousVisitor;

// -- Getting some variation, assume it's variation `A`
const variation = client.getFeatureFlagVariationKey(
anonymousVisitor,
'my_feature_key',
);
}

init();
Application Page
import { CustomData, UniqueIdentifier } from '@kameleoon/javascript-sdk';

async function init(): Promise<void> {
// -- At this point anonymous visitor has logged in
// and we have user ID to use as a visitor identifier
// -- Associating both visitors with identifier Custom Data,
// where index `1` is the index of the Custom Data configured
// as a unique identifier on Kameleoon Platform
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `window` object
client.addData(window.anonymousVisitor, userIdentifierData);

// -- Letting SDK know that the visitor is unique identifier
client.addData('my_user_id', new UniqueIdentifier(true));

// -- Getting the variation for user ID will
// result in the same variation as for anonymous visitor
// variation will be `A`
const variation = client.getFeatureFlagVariationKey(
'my_user_id',
'my_feature_key',
);

// -- `my_user_id` and `anonymousVisitor` are now linked
// They can be tracked as a single visitor
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
});

// -- Moreover linked visitors share previously
// collected remote data
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
});
}

init();

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 of KameleoonUtils class.

simulateSuccessRequest

Method simulateSuccessRequest 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).

import {
KameleoonUtils,
IExternalRequester,
SendRequestParametersType,
RequestType,
KameleoonResponseType,
} from '@kameleoon/javascript-sdk';

// - Example of `Requester` with disabled tracking
class Requester implements IExternalRequester {
public async sendRequest({
url,
parameters,
requestType,
}: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
if (requestType === RequestType.Tracking) {
return KameleoonUtils.simulateSuccessRequest<RequestType.Tracking>(
requestType,
null,
);
}

return await fetch(url, parameters);
}
}
Parameters
NameTypeDescription
requestType (required)RequestTypeA type of request
data (required)SimulateRequestDataType[RequestType]A type of request data, which is different depending on RequestType

Data type SimulateRequestDataType is defined as follows:

  • RequestType.Tracking - null
  • RequestType.ClientConfiguration - ClientConfigurationDataType
  • RequestType.RemoteData - JSONType
Returns

Promise<KameleoonResponseType> - returns a promise with the response of the request

getCookieValue

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

import { KameleoonUtils } from '@kameleoon/javascript-sdk';

const cookies = 'key_1=value_1; key_2=value_2';
const key = 'key_1';

const value = KameleoonUtils.getCookieValue(cookies, key); // = `value_1`
Parameters
NameTypeDescription
cookie (required)stringCookie string in a form key_1=value_1; key_2=value_2
key (required)stringString representation of a key to find a value by
Returns

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 Kameleoon JavaScript SDK.

Initialization

initialize()

An asynchronous method 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.

note

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 initialize does not throw an error.

note

SDK supports an offline mode.

In offline mode if tracking requests from any of the following methods fail due to internet connectivity issues, the SDK automatically resends the request as soon as it detects that the internet connection has been re-established:

import {
KameleoonClient,
KameleoonError,
KameleoonException,
} from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
try {
await client.initialize();
} catch (err) {
if (err instanceof KameleoonError) {
switch (err.type) {
case KameleoonException.StorageWrite:
// -- Handle error case
case KameleoonException.ClientConfiguration:
// -- Handle error case
default:
break;
}
}
}
}

init();
Returns

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.

Throws
TypeDescription
KameleoonException.StorageWriteCouldn't update storage data
KameleoonException.ClientConfigurationCouldn't retrieve client configuration from Kameleoon API
KameleoonException.MaximumRetriesReachedMaximum retries reached, request failed

Feature flags and variations

getVariation()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
  • 🎯 Events: EventType.Evaluation

Retrieves the VariationType assigned to a given visitor for a specific feature flag.

This method takes a visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true.

It returns the assigned VariationType for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default VariationType for the given feature flag.

Ensure that proper error handling is implemented in your code to manage potential exceptions.

note

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.

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Get variation with tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
});

// -- Get variation without tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
track: false,
});

// -- An Example variation:
// {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
}

init();
Parameters

An object of type GetVariationParamsType with the following properties:

NameTypeDescriptionDefault
visitorCode (required)stringUnique identifier of the user.
featureKey (required)stringKey of the feature you want to expose to a user.
track (optional)booleanAn optional parameter to enable or disable tracking of the feature evaluation.true
Return value
TypeDescription
VariationTypeAn assigned variation to a given visitor for a specific feature flag.
Exceptions thrown
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call.
KameleoonException.VisitorCodeEmptyThe visitor code is empty.
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters).
KameleoonException.FeatureFlagConfigurationNotFoundException 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 on your application).
KameleoonException.FeatureFlagEnvironmentDisabledException 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 track parameter)
  • 🎯 Events: EventType.Evaluation

Retrieves a map of VariationType objects assigned to a given visitor across all feature flags.

This method iterates over all available feature flags and returns the assigned VariationType for each flag associated with the specified visitor. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.

  • If onlyActive is set to true, the method getVariations() will return feature flags variations provided the user is not bucketed with the off variation.
  • The track parameter controls whether or not the method will track the variation assignments. By default, it is set to true. If set to false, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding VariationType as values. If no variation is assigned for a feature flag, the method returns the default VariationType for that flag.

Proper error handling should be implemented to manage potential exceptions.

note

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.

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Get all feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
});

// -- Get active feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
});

// -- Get active feature flag variations without tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
track: false,
});

// -- An Example variations:
// Map {
// 'feature_key' => {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
// }
}

init();
Parameters

An object of type GetVariationParamsType with the following properties:

NameTypeDescriptionDefault
visitorCode (required)stringUnique identifier of the user.
onlyActive (optional)booleanAn optional parameter indicating whether to return variations for active (true) or all (false) feature flags.false
track (optional)booleanAn optional parameter to enable or disable tracking of the feature evaluation.true
Return value
TypeDescription
Map<string, VariationType>Map that contains the assigned VariationType objects of the feature flags using the keys of the corresponding features.
Exceptions thrown
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call.
KameleoonException.VisitorCodeEmptyThe visitor code is empty.
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters).

isFeatureFlagActive()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
  • 🎯 Events: EventType.Evaluation

The method isFeatureFlagActive() returns a boolean value indicating whether the visitor identified by visitorCode has the specified featureKey active. This method checks for targeting, determines the variation for the visitor, and saves this information to storage. Additionally, it sends a tracking request.

There is also an overload of this method that allows you to pass a track parameter, which can be used to disable tracking of the feature evaluation.

note

Only visitors with feature flag active must be targetted.

import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(visitorCode, new CustomData(0, 'visitor_id'));

// -- Check if the feature flag is active for visitor
const isActive = client.isFeatureFlagActive(visitorCode, 'my_feature_key');

// -- Check if the feature flag is active for visitor without tracking
const isActive = client.isFeatureFlagActive({ visitorCode, featureKey: 'my_feature, track: false});
}

init();
Parameters

There are two overloads available for this method:

  1. Two parameters overload:
danger

This overload is deprecated and will be removed in the next major version. Please use the new overload with an object parameter.

NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
featureKey (required)stringa unique key for feature flag
  1. Object parameter overload of type IsFeatureFlagActiveParamsType:
NameTypeDescriptionDefault
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length-
featureKey (required)stringa unique key for feature flag-
track (optional)booleana boolean indicator of whether to track the feature evaluationtrue
Returns

boolean - a boolean indicator of whether the feature flag with featureKey is active for visitor with visitorCode

Throws
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.NotTargetedCurrent visitor is not targeted
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found for provided featureKey
KameleoonException.DataInconsistencyAllocated variation was found, but there is no feature flag with according featureKey.

getFeatureFlagVariationKey()

caution

This method is deprecated and will be removed in the next major version. Please use the new method getVariation

Method getFeatureFlagVariationKey() retrieves the variation key for a visitor identified by visitorCode. This method includes a targeting check, identifies the appropriate variation exposed to the visitor, saves it to storage, and also sends a tracking request.

note

When a user is not previously associated with a feature flag, the SDK randomly returns a variation key according to the feature flag rules. If the user has already been registered with the feature flag, the SDK will detect and return the user's previous variation key value. However, if the user does not meet any of the defined rules, the SDK will return the default value specified in Kameleoon's feature flag delivery rules. It's important to note that the default value can be a variation key, a boolean value, or another data type, depending on the configuration of the feature flag.

import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(new CustomData(0, 'visitor_id'));

// -- Get visitor feature flag variation key
const variationKey = client.getFeatureFlagVariationKey(
visitorCode,
'my_feature_key',
);
}

init();
Parameters
NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
featureKey (required)stringa unique key for feature flag
Returns

string a string containing variable key for the allocated feature flag variation for the provided visitor

Throws
TypeDescription
KameleoonException.InitializationMethod was executed before initialize was done for kameleoonClient
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.NotTargetedCurrent visitor is not targeted
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found for provided featureKey
KameleoonException.FeatureFlagEnvironmentDisabledFeature flag is disabled for the current environment

getFeatureFlags()

🚫 Doesn't send Tracking Data to Kameleoon

caution

This method is deprecated and will be removed in the next major version. Please use the new method getVariations

Method getFeatureFlags() returns a list of feature flags stored in the client configuration.

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
await client.initialize();

// -- Get all feature flags
const featureFlags = client.getFeatureFlags();
}

init();
Returns

FeatureFlagType[] - list of feature flags, each feature flag item contains id and key

Throws
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call

getVisitorFeatureFlags()

  • 🚫 Doesn't send Tracking Data to Kameleoon
  • 🎯 Events: EventType.Evaluation (for each feature flag)
caution

This method is deprecated and will be removed in the next major version. Please use the new method getVariations

Method getVisitorFeatureFlags() returns a list of feature flags that the visitor with visitorCode that is targeted by and that are active for the visitor (visitor will have one of the variations allocated).

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Get active feature flags for visitor
const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}

init();
caution

This method only collects the visitor's active feature flags. This means the result excludes all the feature flags for which the visitor is assigned to the off (default or control) variation. When you need all of the visitor's feature flags, use getFeatureFlags instead.

For example:

// -- `getVisitorFeatureFlags` doesn't trigger feature experiment
// it only returns feature flags, where visitor didn't get `off` variation
client.getVisitorFeatureFlags('my_visitor').forEach(({ key }) => {
// -- `getFeatureFlagVariationKey` triggers feature experiment,
// as `off` is already filtered out - I will never see
// visitor taking part in experiment, where `off` variation was allocated
client.getFeatureFlagVariationKey('my_visitor', key);
});

For cases where you need all of the visitor's feature flags, use getFeatureFlags instead:

// -- Both `off` and other variations are processed as expected
client.getFeatureFlags('my_visitor').forEach(({ key }) => {
client.getFeatureFlagVariationKey('my_visitor', key);
});
Parameters
NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
Returns

FeatureFlagType[] - list of feature flags, each feature flag item contains id and key

Throws
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.NotTargetedCurrent visitor is not targeted
KameleoonException.StorageReadError while reading storage data

getActiveFeatureFlags()

  • 🚫 Doesn't send Tracking Data to Kameleoon
  • 🎯 Events: EventType.Evaluation (for each feature flag)
caution

This method is deprecated and will be removed in the next major version. Please use the new method getVariations

Method getActiveFeatureFlags() returns a Map, where key is feature key and value is detailed information about the visitor's variation and it's variables

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Get active feature flags for visitor
// with detailed variation and variables data
const activeFeatures = client.getActiveFeatureFlags(visitorCode);

// -- Result example:
// Map {
// 'feature-key-one' => {
// id: 100,
// key: 'variation-key-one',
// experimentId: 200,
// variables: [
// { key: 'variable_bool', type: VariableType.Boolean, value: true },
// ]
// },
// 'feature-key-two' => {
// id: null, // -> `null` because it is default variation
// key: 'default-variation-key',
// experimentId: null, // -> `null` because it is default variation
// variables: []
// }
// }
}

init();
caution

This method only collects the visitor's active feature flags. This means the result excludes all the feature flags for which the visitor is assigned to the off (default or control) variation. When you need all of the visitor's feature flags to iterate, use getFeatureFlags instead.

See the getVisitorFeatureFlags CAUTION section method for more details.

Parameters
NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
Returns

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

Throws
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.StorageReadError while reading storage data
KameleoonException.NumberParseCouldn't parse Number value
KameleoonException.JSONParseCouldn't parse JSON value

Variables

getFeatureFlagVariable()

caution

This method is deprecated and will be removed in the next major version. Please use the new method getVariation

Method getFeatureFlagVariable() returns a variable for the visitor under visitorCode in the found feature flag, this method includes targeting check, finding the according variation exposed to the visitor and saving it to storage along with sending tracking request.

import {
KameleoonClient,
VariableType,
JSONType,
} from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Get feature variable
const result = client.getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key'
variableKey: 'my_variable_key'
});

// -- Infer the type of variable by it's `type`
switch (result.type) {
case VariableType.BOOLEAN:
const myBool: boolean = result.value;
break;
case VariableType.NUMBER:
const myNum: number = result.value;
break;
case VariableType.JSON:
const myJson: JSONType = result.value;
break;
case VariableType.STRING:
case VariableType.JS:
case VariableType.CSS:
const myStr: string = result.value;
break;
default:
break;
}
}

init();
Parameters

Parameters object of type GetFeatureFlagVariableParamsType containing the following fields:

NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
featureKey (required)stringa unique key for feature flag
variableKey (required)stringkey of the variable to be found for a feature flag with provided featureKey, can be found on Kameleoon Platform
Returns

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.

Throws
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.NotTargetedCurrent visitor is not targeted
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found for provided featureKey
KameleoonException.FeatureFlagVariableNotFoundNo feature variable was found for provided visitorCode and variableKey
KameleoonException.FeatureFlagEnvironmentDisabledFeature flag is disabled for the current environment
KameleoonException.JSONParseCouldn't parse JSON value
KameleoonException.NumberParseCouldn't parse Number value

getFeatureFlagVariables()

caution

This method is deprecated and will be removed in the next major version. Please use the new method getVariation

Method getFeatureFlagVariables() returns a list of variables for the visitor under visitorCode in the found feature flag, this method includes targeting check, finding the according variation exposed to the visitor and saving it to storage along with sending tracking request.

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Get a list of variables for the visitor under `visitorCode` in the found feature flag
const variables = client.getFeatureFlagVariables(
visitorCode,
'my_feature_key',
);
}

init();
Parameters
NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
featureKey (required)stringa unique key for feature flag
Returns

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.

Throws
TypeDescription
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.NotTargetedCurrent visitor is not targeted
KameleoonException.FeatureFlagConfigurationNotFoundNo feature flag was found for provided featureKey
KameleoonException.FeatureFlagVariationNotFoundNo feature variation was found for provided visitorCode and variationKey
KameleoonException.FeatureFlagEnvironmentDisabledFeature flag is disabled for the current environment
KameleoonException.JSONParseCouldn't parse JSON value
KameleoonException.NumberParseCouldn't parse Number value

Visitor data

getVisitorCode()

Method getVisitorCode obtains a visitor code from the browser cookie. If the visitor code doesn't exist yet, the method generates a random visitor code (or uses the defaultVisitorCode value if you provided one) and sets the new visitor code in a cookie.

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

// -- Get visitor code with default value
const visitorCode = client.getVisitorCode('my_default_visitor_code');
}

init();

addData()

The addData() method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.

The addData() method 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 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 is triggered by flush. Note that the trackConversion method also sends out any previously associated data, just like the flush method. The same is true for getFeatureFlagVariationKey and getFeatureFlagVariable methods if an experimentation rule is triggered.

tip

Each visitor can only have one instance of associated data for most data types. However, CustomData is an exception. Visitors can have one instance of associated CustomData per customDataIndex.

note

userAgent data will not be stored in storage like other data, and it will be sent with every tracking request for bot filtration.

note

For the data types you can use for targeting, see the supported targeting conditions.

import {
KameleoonClient,
BrowserType,
CustomData,
Browser,
} from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
await client.initialize();

// -- Create Kameleoon Data Types
const browserData = new Browser(BrowserType.Chrome);
const customData = new CustomData(0, 'my_data');

// -- Add one Data item to Storage
client.addData('my_visitor_code', browserData);

// -- Add Data to Storage using variadic style
client.addData('my_visitor_code', browserData, customData);

// -- Add Data to Storage in array
const dataArr = [browserData, customData];
client.addData('my_visitor_code', ...dataArr);
}

init();
Parameters
NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
kameleoonData (optional)KameleoonDataType[]number of instances of any type of KameleoonData, can be added solely in array or as sequential arguments
note

kameleoonData is variadic argument it can be passed as one or several arguments (see the example)

note

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 assigned 0 as its ID, not 1.

Throws
TypeDescription
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length of 255 characters
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.StorageWriteCouldn't update storage data
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call.
note

Check Data Types reference for more details of how to manage different data types

Parameters
NameTypeDescription
defaultVisitorCode (optional)stringvisitor code to be used in case there is no visitor code in cookies
note

If you don't provide a defaultVisitorCode and there is no visitor code stored in a cookie, the visitor code will be randomly generated.

Returns

string - result visitor code

Throws
TypeDescription
KameleoonException.VisitorCodeMaxLengthThe visitor code length was exceeded
KameleoonException.VisitorCodeEmptyThe visitor code is empty

flush()

flush() takes the Kameleoon data associated with the visitor and schedules the data to be sent in the next tracking request. The time of the next tracking request is defined by the 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.

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor code
const visitorCode = client.getVisitorCode();

const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);

// -- Flush added custom data for visitor
client.flush(visitorCode);

// -- Flush data for all the visitors
client.flush();
}

init();
Parameters
NameTypeDescriptionDefault
visitorCode (optional)stringunique visitor identification string, can't exceed 255 characters in length, if not passed all the data will be flushed (sent to the remote Kameleoon servers)-
Throws
TypeDescription
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.InitializationMethod was executed before the kameleoonClient completed it's initialize call

getRemoteData()

Method getRemoteData() returns a data which is stored for specified site code on a remote Kameleoon server.

For example, you can use this method 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.

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
await client.initialize();

// -- Get remote data
const jsonData = await getRemoteData('my_data_key');

const data = JSON.parse(jsonData);
}

init();
Parameters
NameTypeDescription
key (required)stringunique key that the data you try to get is associated with
Returns

JSONType - promise with data retrieved for specific key

Throws
TypeDescription
KameleoonException.RemoteDataCouldn't retrieve data from Kameleoon server

getRemoteVisitorData()

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

Read this article for a better understanding of possible use cases.

caution

By default, getRemoteVisitorData() automatically retrieves the latest stored custom data with scope=Visitor and attaches them to the visitor without the need to call the method addData(). It is particularly useful for synchronizing custom data between multiple devices.

import {
KameleoonClient,
KameleoonDataType,
VisitorDataFiltersType,
} from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
await client.initialize();

// -- Get remote visitor data and add it to storage
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});

// -- Get remote visitor data without adding it to storage
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});

// -- Get remote visitor data without adding it to storage
// and customizing filters for retrieving visits data
const filters: VisitorDataFiltersType = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};

const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}

init();
Using parameters in getRemoteVisitorData()

The getRemoteVisitorData() method offers flexibility of 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, if 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.

Parameters

An object with the type RemoteVisitorDataParamsType containing:

NameTypeDescriptionDefault Value
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length-
shouldAddData (optional)booleanboolean flag identifying whether the retrieved custom data should be added to storage automatically (without calling the addData method afterwards)true
filters (optional)VisitorDataFiltersTypefilters 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

Here is the list of available VisitorDataFiltersType filters:

NameTypeDescriptionDefault
previousVisitAmount (optional)numberNumber of previous visits to retrieve data from. Number between 1 and 251
currentVisit (optional)booleanIf true, current visit data will be retrievedtrue
customData (optional)booleanIf true, custom data will be retrieved.true
pageViews (optional)booleanIf true, page data will be retrieved.false
geolocation (optional)booleanIf true, geolocation data will be retrieved.false
device (optional)booleanIf true, device data will be retrieved.false
browser (optional)booleanIf true, browser data will be retrieved.false
operatingSystem (optional)booleanIf true, operating system data will be retrieved.false
conversions (optional)booleanIf true, conversion data will be retrieved.false
experiments (optional)booleanIf true, experiment data will be retrieved.false
kcs (optional)booleanIf true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-onfalse
Returns

KameleoonDataType[] - promise with list of Kameleoon Data retrieved

Throws
TypeDescription
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.RemoteDataCouldn't retrieve data from Kameleoon server
KameleoonException.VisitAmountVisit amount must be a number between 1 and 25
KameleoonException.InitializationMethod was executed before initialize was done for kameleoonClient

getVisitorWarehouseAudience()

getVisitorWarehouseAudience is an asynchronous method that 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.

import {
KameleoonClient,
KameleoonDataType,
CustomData,
} from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({ siteCode: 'my_site_code' });

async function init(): Promise<void> {
await client.initialize();

// -- Get visitor warehouse audience data using `warehouseKey`
// and add it to storage
const customData: CustomData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
warehouseKey: 'my_key',
});

// -- Get visitor warehouse audience data using `visitorCode`
// and add it to storage
const customData: CustomData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
});
}

init();
Parameters

Parameters object consisting of:

NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
customDataIndex (required)numbernumber representing the index of the custom data you want to use to target your Warehouse Audiences
warehouseKey (optional)stringunique key to identify the warehouse data (usually, your internal user ID)
Returns

Promise<CustomData | null> - promise containing CustomData with the associated warehouse data or null if there was no data

Throws
TypeDescription
KameleoonException.VisitorCodeMaxLengthThe visitor code exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty
KameleoonException.RemoteDataCouldn't retrieve data from Kameleoon server

setLegalConsent()

note

Consent information is in sync between the Kameleoon Engine (application file kameleoon.js) and the JS 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.

If you use Kameleoon in Hybrid mode, we recommend reading the consent section in our Hybrid experimentation article

When handling legal consent, it's important to use the getVisitorCode method from KameleoonClient, not the deprecated method from KameleoonUtils. Additionally, this method does not accept domain as an argument. Instead, pass it to the KameleoonClient constructor. Refer to the above example.

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

import { KameleoonClient } from '@kameleoon/javascript-sdk';

const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { domain: '.example.com' },
});

async function init(): Promise<void> {
await client.initialize();

const visitorCode = client.getVisitorCode();
client.setLegalConsent(visitorCode, true);
}

init();
Parameters
NameTypeDescription
visitorCode (required)stringunique visitor identification string, can't exceed 255 characters length
consent (required)booleana 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
Throws
TypeDescription
KameleoonException.VisitorCodeMaxLengthThe visitor code length exceeded the maximum length (255 characters)
KameleoonException.VisitorCodeEmptyThe visitor code is empty

Goals and third-party analytics

trackConversion()