JavaScript / TypeScript SDK
Introduction
Welcome to the developer documentation for the Kameleoon JavaScript SDK! Our SDK gives you the possibility of running experiments and activating feature flags on your front-end web application. Integrating our SDK into your web-application is easy, and its footprint (in terms of memory and network usage) is low.
Before you begin installing our JavaScript SDK, we recommend that you read our technical considerations article to gain an understanding of the fundamental technological concepts behind our SDKs. This will help you to better understand the SDK and ensure a successful integration.
The JavaScript SDK can be used on apps built with Ionic. By using Kameleoon's SDK on your Ionic app, you can take advantage of our powerful A/B testing and feature flags capabilities to improve the user experience and drive better engagement and conversion rates.
Changelog
Latest version description of JavaScript / Typescript SDK can be found here.
Installation
Use preferred package manager to install JavaScript SDK from npm repository.
Npm:
npm install @kameleoon/javascript-sdk
Yarn:
yarn add @kameleoon/javascript-sdk
Pnpm:
pnpm add @kameleoon/javascript-sdk
Contents
Check out migration guide if you are migrating from the outdated JavaScript SDK kameleoon-client-javascript
To configure your JavaScript application and start running feature experiments and deploying new features to your users, please follow the instructions provided in the Main usage section. This section contains all the main steps for proper Kameleoon JavaScript SDK configuration as well as main tools for development.
- Initializing the Kameleoon Client
- Getting access to feature flags and variations
- Using Kameleoon Client methods
In addition to using Kameleoon’s JavaScript SDK to roll out new features and define advanced delivery rules with our Feature Management & Experimentation solution, you can also leverage this SDK for running server-side and hybrid experiments (without utilizing feature flags). For more information on configuring these experiments, please refer to the triggerExperiment method.
We highly recommend that you take a look at the Methods section, which includes useful information on every method that is introduced in JavaScript SDK.
- KameleoonUtils getVisitorCode - Obtain Visitor Code / Use own User ID
- initialize - Initialize Kameleoon Client
- addData - Add associated client data
- triggerExperiment - Trigger an Experiment (without feature flags)
- trackConversion - Track Conversion
- flushData - Flush tracking data
- getRemoteData - Obtain data from Kameleoon remote source
- getRemoteVisitorData - Obtain custom data from Kameleoon Data API
- isFeatureFlagActive - Check if the feature is active for visitor
- getExperiments - Get list of all experiments
- getVisitorExperiments - Get list of experiments for a certain visitor
- getExperimentVariationData - Get a certain experiment variation data
- getFeatureFlags - Get list of all feature flags
- getVisitorFeatureFlags - Get list of feature flags for a certain visitor
- getFeatureFlagVariationKey - Get variation key for a certain feature flag
- getFeatureFlagVariable - Get a variable of a certain feature flag
- onConfigurationUpdate - Define an action for real time configuration update
- getEngineTrackingCode - Sending exposure events to external tools
Explore additional sections with some useful information on Kameleoon Data types and Error handling.
Migration
We have introduced updated JavaScript SDK under the scoped name @kameleoon/javascript-sdk
.
Older kameleoon-client-javascript
will not receive updates anymore and soon will be deprecated, we recommend to use the new version due to it's long support prospect and improved stability.
Migration considerations
Overall most of the methods preserved their functionality and changing the name from the considerations below will be enough, however this document along with js-docs
on the methods themselves contains a lot of useful information on how to use them.
Removed methods:
runWhenReady
(no longer needed, useinitialize
instead)getFeatureFlagAllVariables
(getFeatureFlagVariable
can be used instead to get one variable with strong typing)
Renamed methods:
flush
--->flushData
getFeatureVariable
--->getFeatureFlagVariable
getVariationAssociatedData
--->getExperimentVariationData
getVisitorCode
--->KameleoonUtils.getVisitorCode
(is now used on a dedicated helper classKameleoonUtils
)activateFeature
--->isFeatureFlagActive
retrieveDataFromRemoteSource
--->getRemoteData
getExperimentList
--->getExperiments
getExperimentListForVisitorCode
--->getVisitorExperiments
getFeatureList
--->getFeatureFlags
getFeatureListForVisitorCode
--->getVisitorFeatureFlags
onUpdateConfiguration
--->onConfigurationUpdate
Added methods:
Main Usage
Here is a step-by-step guide for configuring JavaScript SDK for your application.
1. Initializing the Kameleoon Client
import {
Environment,
KameleoonClient,
SDKConfigurationType,
} from '@kameleoon/javascript-sdk';
// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
updateInterval: 20,
environment: Environment.Production,
};
const client = new KameleoonClient('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) => {});
For the start developers will need to create an entry point for JavaScript SDK by creating a new instance of Kameleoon Client.
KameleoonClient
is used to run experiments and retrieve the status of feature flag and its variables using concerned methods.
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
Name | Type | Description |
---|---|---|
siteCode (required) | string | client's site code defined on Kameleoon platform |
configuration (optional) | Partial<SDKConfigurationType> | client's configuration |
configuration
consists of following parameters:
Name | Type | Description | Default Value |
---|---|---|---|
updateInterval (optional) | number | update interval in minutes for sdk configuration, minimum value is 1 minute | 60 |
environment (optional) | Environment | feature flag environment | Environment.Production |
targetingDataCleanupInterval (optional) | number or undefined | interval in minutes for cleaning up targeting data, minimum value is 1 minute | undefined (no cleanup will be performed) |
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.
2. Getting access to feature flags and variations
To implement a feature flag in your code, you must first create a feature flag in your Kameleoon account.
After the SDK has been initialized, you can obtain a feature flag configuration. Subsequently, all methods will require you to specify the User ID or visitor code associated with the request.
If you are using Kameleoon in Hybrid mode with mixed front-end and back-end environments, you can call the KameleoonUtils.getVisitorCode helper method to obtain the Kameleoon visitorCode for the current visitor. Alternatively, if you provide your own User ID, you must ensure its uniqueness on your end.
3. Using Kameleoon Client methods
Now your setup is done! You can use KameleoonClient
methods to handle experiments and feature flags.
To associate various data points with the current user, you can use the addData method. This method requires the visitorCode as the first parameter and accepts several additional parameters. These additional parameters represent the various Data Types allowed in Kameleoon.
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
// -- Trigger an experiment
const experimentId = 100;
const variationId = client.triggerExperiment(visitorCode, experimentId);
// -- Add user data
const customDataIndex = 0;
client.addData(visitorCode, new CustomData(customDataIndex, 'my_data'));
// -- Check if the feature is active for visitor
const isMyFeatureActive = client.isFeatureFlagActive(
visitorCode,
'my_feature_key',
);
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
}
init();
Feature flags can be very useful for implementing ON/OFF switches with optional but advanced user targeting rules. However, you can also use feature flags to run feature experiments with several variations of your feature flag. Check out our documentation on creating feature experiments for more information.
See Methods section for detailed guide for each KameleoonClient
method available.
Methods
Get Visitor Code / Use Own Visitor ID
KameleoonUtils getVisitorCode
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
// -- Get visitor code
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
// -- Get visitor code with default value
const visitorCode = KameleoonUtils.getVisitorCode(
'www.example.com',
'my_default_visitor_code',
);
Static method getVisitorCode
called on KameleoonUtils
obtains visitor code from the browser cookie, if the visitor code doesn't yet exist generates a random visitor code (or uses a provided default) and sets a new visitor code to cookie
Parameters
Name | Type | Description |
---|---|---|
domain (required) | string | domain which cookie belongs to |
defaultVisitorCode (optional) | string | visitor code to be used in case there is no visitor code in cookies |
If defaultVisitorCode
wasn't provided and there is no visitor code stored in cookie it will be randomly generated
Returns
string
- result visitor code
Initialize Kameleoon Client
initialize
import {
KameleoonClient,
KameleoonError,
KameleoonException,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('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();
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.
Client initialization has an optional offline mode.
It is activated by setting optional useCache
parameter to true
. Offline mode allows for silent polling fails.
If the SDK was already initialized successfully but at some point Internet connection was lost, SDK will still try to fetch next configuration when time of updateInterval
comes, which can cause initialize
errors, activating offline mode will prevent such errors from happening, while the latest cached experiments and feature flags data will be used as a fallback.
Activating offline mode doesn't prevent initialization from failing if there is no cached data available.
Parameters
Name | Type | Description | Default Value |
---|---|---|---|
useCache (optional) | boolean or undefined | parameter for activating SDK offline mode, if true is passed failed polls will not return error and will use cached data if such data is available | false |
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
Type | Description |
---|---|
KameleoonException.StorageWrite | Couldn't update storage data |
KameleoonException.ClientConfiguration | Couldn't retrieve client configuration from Kameleoon API |
KameleoonException.MaximumRetriesReached | Maximum retries reached, request failed |
Add associated client data
addData
import {
KameleoonClient,
BrowserType,
CustomData,
Browser,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('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();
Method for adding targeting data to the storage so that other methods could decide whether the current visitor is targeted or not.
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 via the flushData method .This approach helps reduce the number of server calls made, as the data is typically grouped into a single server call triggered by the execution of flushData.
triggerExperiment and trackConversion methods also send out any previously associated data, just like the flushData. The same holds true for getFeatureFlagVariationKey and getFeatureFlagVariable methods if an experimentation rule is triggered.
userAgent
data will not be stored in storage like other data, and it will be sent with every tracking request for bot filtration.
Parameters
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique 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 |
kameleoonData
is variadic argument it can be passed as one or several arguments (see the example)
The index or ID of the custom data can be found in your Kameleoon account. It is important to note that this index starts at 0
, which means that the first custom data you create for a given site will be assigned 0
as its ID, not 1
.
Throws
Type | Description |
---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageWrite | Couldn't update storage data |
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Check Data Types reference for more details of how to manage different data types
Trigger an Experiment (without feature flags)
triggerExperiment
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
const experimentId = 123;
// -- Get visitor code using `KameleoonUtils` helper method
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
await client.initialize();
// -- Trigger Experiment and obtain variation id
const variationId = client.triggerExperiment(visitorCode, experimentId);
}
init();
triggerExperiment()
method triggers experiment by assigning the variation to the user with visitorCode
, if the variation is already assigned just returns its id. At the same time executes flushData without sending extra tracking request.
The triggerExperiment()
method allows you to run server-side or hybrid experiments without the need to configure feature flags.
Returned id 0
indicates default variation.
Parameters
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
experimentId (required) | number | id of experiment running for the current visitor |
Returns
number
- associated variationId which is successfully found in storage or newly assigned
Throws
Type | Description |
---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.ExperimentConfigurationNotFound | No configuration found for provided experimentId |
KameleoonException.StorageRead | Couldn't find associated experiment by provided experimentId and visitorCode inside the storage |
KameleoonException.NotTargeted | Current visitor is not targeted |
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Track Conversion
trackConversion
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
const experimentId = 123;
// -- Get visitor code using `KameleoonUtils` helper method
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
await client.initialize();
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
}
init();
Method trackConversion()
creates and adds Conversion
data to the visitor with specified parameters and executes flushData
.
It's a helper method for the quick and convenient conversion tracking, however creating and adding Conversion manually allows more flexible Conversion
with negative
parameter
Parameters
Parameters object consisting of:
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
goalId (required) | number | goal to be sent in tracking request |
revenue (required) | number | revenue to be sent in tracking request |
Throws
Type | Description |
---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageWrite | Couldn't update storage data |
Flush tracking data
flushData
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
// -- Get visitor code using `KameleoonUtils` helper method
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
await client.initialize();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data
client.flushData(visitorCode);
}
init();
Method flushData()
takes visitor associated Kameleoon data and sends the data tracking request with all data added using addData by this point
Parameters
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Get list of all experiments
getExperiments
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Get experiment list
const experiments = client.getExperiments();
}
init();
Method getExperiments()
returns a list of experiments stored in the client configuration
Returns
ExperimentType[]
- list of experiments, each experiment item contains id
and name
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Get list of experiments for a certain visitor
getVisitorExperiments
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
// -- Get visitor code using `KameleoonUtils` helper method
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
await client.initialize();
// -- Get all visitor experiments
const experiments = client.getVisitorExperiments(visitorCode, false);
// -- Get only allocated visitor experiments
const experiments = client.getVisitorExperiments(visitorCode);
}
init();
Method getVisitorExperiments()
returns a list of experiments that the visitor with visitorCode
is targeted by and that are active for the visitor
Visitor will have one of the variations allocated if the experiment was triggered
Parameters
Name | Type | Description | Default Value |
---|---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length | - |
isAllocated (optional) | boolean | boolean value indicating that only experiments allocated for visitor will be returned | true |
Returns
ExperimentType[]
- list of experiments, each experiment item contains id
and name
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
Get experiment variation data
getExperimentVariationData
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Get experiment variation data
const variationId = 100;
const variationDataJson = client.getExperimentVariationData(variationId);
}
init();
Method getExperimentVariationData
returns variation data in JSON format for the variation with variationId
Parameters
Name | Type | Description |
---|---|---|
variationId (required) | number | id of a variation |
Returns
JSONType
- variation data in JSON format
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.JSONParse | Couldn't parse retrieved data to JSON format |
KameleoonException.VariationNotFound | No variation found for provided variationId |
Get list of all feature flags
getFeatureFlags
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Get all feature flags
const experiments = client.getFeatureFlags();
}
init();
Method getFeatureFlags()
returns a list of feature flags stored in the client configuration
Returns
FeatureFlagType[]
- list of feature flags, each experiment item contains id
and key
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Get list of feature flags for a certain visitor
getVisitorFeatureFlags
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
// -- Get visitor code using `KameleoonUtils` helper method
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
await client.initialize();
// -- Get active feature flags for visitor
const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}
init();
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).
Parameters
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
Returns
FeatureFlagType[]
- list of feature flags, each experiment item contains id
and key
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.NotTargeted | Current visitor is not targeted |
Check if the feature is active for visitor
isFeatureFlagActive
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
// -- Get visitor code using `KameleoonUtils` helper method
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
await client.initialize();
// -- 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');
}
init();
Method isFeatureFlagActive()
returns a boolean indicating whether the visitor with visitorCode
has featureKey
active for him, this method includes targeting check, finding the according variation exposed to the visitor and saving it to storage along with sending tracking request.
Visitor must be targeted to has feature flag active
Parameters
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
featureKey (required) | string | a unique key for feature flag |
Returns
boolean
- a boolean indicator of whether the feature flag with featureKey
is active for visitor with visitorCode
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.NotTargeted | Current visitor is not targeted |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided visitorCode and featureKey |
KameleoonException.DataInconsistency | Allocated variation was found, but there is no feature flag with according featureKey . |
Get variation key for a certain feature flag
getFeatureFlagVariationKey
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
// -- Get visitor code using `KameleoonUtils` helper method
const visitorCode = KameleoonUtils.getVisitorCode('www.example.com');
await client.initialize();
// -- 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();
Method getFeatureFlagVariationKey()
returns variation key 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.
If the user has never been associated with the feature flag, the SDK returns a variation key randomly, following the feature flag rules. If the user is already registered with the feature flag, the SDK detects the previous variation key value. If the user doesn't match any of the rules, the default value defined in Kameleoon's feature flag delivery rules will be returned. It's important to note that the default value may not be a variation key, but a boolean value or another data type, depending on the feature flag configuration.
Parameters
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
featureKey (required) | string | a unique key for feature flag |
Returns
string
a string containing variable key for the allocated feature flag variation for the provided visitor
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.NotTargeted | Current visitor is not targeted |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided visitorCode and featureKey |
Get a variable of a certain feature flag
getFeatureFlagVariable
import {
KameleoonClient,
VariableType,
JSONType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Get feature variable
const variableResult = client.getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key'
variableKey: 'my_variable_key'
});
// -- Infer the type of variable by it's `type`
switch (variableResult.type) {
case VariableType.BOOLEAN:
const myBool: boolean = res.value;
break;
case VariableType.NUMBER:
const myNum: number = res.value;
break;
case VariableType.JSON:
const myJson: JSONType = res.value;
break;
case VariableType.STRING:
const myStr: string = res.value;
break;
default:
break;
}
}
init();
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.
Parameters
Parameters object of a type GetFeatureFlagVariableParamsType
containing the following fields:
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
featureKey (required) | string | a unique key for feature flag |
variableKey (required) | string | key of the variable to be found for a feature flag with provided featureKey , can be found on Kameleoon Platform |
Returns
FeatureVariableResultType
a variable object containing type
and value
fields, type
can be checked against FeatureVariableType
enum, if the type
is FeatureVariableType.BOOLEAN
then the value
type will be boolean
and so on
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.NotTargeted | Current visitor is not targeted |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided visitorCode and featureKey |
KameleoonException.FeatureFlagVariableNotFound | No feature variable was found for provided visitorCode and variableKey |
KameleoonException.JSONParse | Couldn't pass JSON value |
KameleoonException.NumberParse | Couldn't pass Number value |
Obtain data from Kameleoon remote source
getRemoteData
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Get remote data
const jsonData = await getRemoteData('my_data_key');
const data: MyDataType = JSON.parse(jsonData);
}
init();
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.
Parameters
Name | Type | Description |
---|---|---|
key (required) | string | unique key that the data you try to get is associated with |
Returns
JSONType
- promise with data retrieved for specific key
Throws
Type | Description |
---|---|
KameleoonException.RemoteData | Couldn't retrieve data from Kameleoon server |
Obtain custom data from Kameleoon Data API
getRemoteVisitorData
import { KameleoonClient, KameleoonDataType } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Get remote visitor data and add it to storage
const customDataList: KameleoonDataType[] = await getRemoteVisitorData(
'my_visitor_code',
);
// -- Get remote visitor data without adding it to storage
const customDataList: KameleoonDataType[] = await getRemoteVisitorData(
'my_visitor_code',
false,
);
}
init();
getRemoteVisitorData()
is an asynchronous method for retrieving custom data for the latest visit of visitorCode
from Kameleoon Data API and adding it to the storage so that other methods could decide whether the current visitor is targeted or not.
Parameters
Name | Type | Description | Default Value |
---|---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length | - |
shouldAddData (optional) | boolean | boolean flag identifying whether the retrieved custom data should be set to the storage like addData method does | true |
Returns
KameleoonDataType[]
- promise with list of custom data retrieved
Throws
Type | Description |
---|---|
KameleoonException.RemoteData | Couldn't retrieve data from Kameleoon server |
Define an action for real time configuration update
onConfigurationUpdate
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Define logic to be executed on client configuration update
client.onConfigurationUpdate(() => {
// -- My Logic
});
}
init();
Method onConfigurationUpdate()
fires a callback on client configuration update.
This method only works for server sent events of real time update
Parameters
Name | Type | Description |
---|---|---|
callback (required) | () => void | callback function with no parameters that will be called upon configuration update |
Throws
Type | Description |
---|---|
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Sending exposure events to external tools
Kameleoon offers built-in integrations with various analytics and CDP solutions, such as Mixpanel, GA4, Segment.... To ensure that you can track and analyze your server-side experiments, Kameleoon provides a method getEngineTrackingCode()
that returns the JavasScript code to be inserted in your page to automatically send the exposure events to the analytics solution you are using. For more information about hybrid experimentation, please refer to this documentation.
To benefit from this feature, you will need to implement both the JavaScript SDK and our Kameleoon JavaScript tag. We recommend you implement the Kameleoon Asynchronous tag, which you can install before your closing <body>
tag in your HTML page, as it will be only used for tracking purposes.
getEngineTrackingCode
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Trigger an experiment
const experimentId = 100;
// -- E.g. result `variationId` is `200`
const variationId = client.triggerExperiment('visitor_code', experimentId);
// -- Get tracking code
const engineCode = client.getEngineTrackingCode('visitor_code');
// -- Result engine code will look like this
// `
// window.kameleoonQueue = window.kameleoonQueue || [];
// window.kameleoonQueue.push(['Experiments.assignVariation', 100, 200]);
// window.kameleoonQueue.push(['Experiments.trigger', 100, true]);
// `
}
init();
Method getEngineTrackingCode()
returns Kameleoon tracking code for the current visitor. Tracking code is built based the experiments that were triggered during the last 5 seconds
Result tracking code can be inserted directly into html <script>
tag
For example:
<!DOCTYPE html>
<html lang="en">
<body>
<script>
const engineTrackingCode = `
window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', 100, 200]);
window.kameleoonQueue.push(['Experiments.trigger', 100, true]);
`;
const script = document.createElement('script');
script.textContent = engineTrackingCode;
document.body.appendChild(script);
</script>
</body>
</html>
Parameters
Name | Type | Description |
---|---|---|
visitorCode (required) | string | unique visitor identification string, can't exceed 255 characters length |
Returns
string
containing engine tracking code
Data Types
Kameleoon Data types are helper classes used for storing data in storage in predefined forms.
During the flushData
execution all the data is collected and send along with tracking request.
Browser
import {
KameleoonClient,
BrowserType,
Browser,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Add new browser data to client
const browser = new Browser(BrowserType.Chrome);
client.addData('my_visitor_code', browser);
}
init();
Browser contains browser information.
Parameters
Name | Type | Description |
---|---|---|
browser (required) | BrowserType | predefined browser type (Chrome , InternetExplorer , Firefox , Safari , Opera , Other ) |
Conversion
import {
KameleoonClient,
ConversionParametersType,
Conversion,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Defined conversion parameters
const conversionParameters: ConversionParametersType = {
goalId: 123,
revenue: 10000,
negative: true,
};
// -- Add new conversion data to client
const conversion = new Conversion(conversionParameters);
client.addData('my_visitor_code', conversion);
}
init();
Conversion contains information about your conversion.
goalId
can be found on Kameleoon Platform
Parameters
ConversionParametersType
conversionParameters - an object with conversion parameters described below
Name | Type | Description | Default Value |
---|---|---|---|
goalId (required) | number | an id of a goal to track | - |
browser (optional) | number | an optional parameter for revenue | 0 |
negative (optional) | boolean | an optional parameter identifying whether the conversion should be removed | false |
CustomData
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
const dataItemOne = 'abc';
const dataItemTwo = JSON.stringify(100);
const dataItemThree = JSON.stringify({ a: 200, b: 300 });
const customDataIndex = 0;
// -- Create custom data using single parameter
const customData = new CustomData(customDataIndex, dataItemOne);
// -- Create custom data using variadic number of parameters
const customData = new CustomData(customDataIndex, dataItemOne, dataItemTwo);
// -- Create custom data using an array of values
const dataList = [dataItemOne, dataItemTwo, dataItemThree];
const customData = new CustomData(customDataIndex, ...dataList);
// -- Add custom data
client.addData('my_visitor_code', customData);
}
init();
CustomData is usually used together with custom data targeting condition on Kameleoon Platform to determine whether the visitor is targeted or not
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.
Parameters
Name | Type | Description |
---|---|---|
index (required) | number | an index of custom data to be stored under in a state, an index of custom data can be specified in Advanced Tools section of Kameleoon Application |
value (optional) | string[] | custom value to store under the specified id, value can be anything but has to be stringified to match the string type. Note value is variadic parameter and can be used as follows |
Device
import { KameleoonClient, DeviceType, Device } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Add device data
const device = new Device(DeviceType.Desktop);
client.addData('my_visitor_code', device);
}
init();
Device contains information about your device.
Parameters
Name | Type | Description |
---|---|---|
deviceType (required) | DeviceType | possible variants for device type (PHONE , TABLET , DESKTOP ) |
PageView
import {
KameleoonClient,
PageViewParametersType,
PageView,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Define page view parameters
const pageViewParameters: PageViewParametersType = {
urlAddress: 'www.example.com',
title: 'my example',
referrers: [123, 456],
};
// -- Add page view data
const pageView = new PageView(pageViewParameters);
client.addData('my_visitor_code', pageView);
}
init();
PageView contains information about your web page.
Parameters
PageViewParametersType
pageViewParameters - an object with page view parameters described below
Name | Type | Description |
---|---|---|
urlAddress (required) | string | url address of the page to track |
title (required) | string | title of the web page |
referrer (optional) | number[] | an optional parameter containing a list of referrers Indices, has no default value |
The index or ID of the referrer can be found in your Kameleoon account. It is important to note that this index starts at 0, which means that the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.
UserAgent
import { KameleoonClient, UserAgent } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init(): Promise<void> {
await client.initialize();
// -- Add user agent data
const userAgent = new UserAgent('my_unique_value');
client.addData('my_visitor_code', userAgent);
}
init();
UserAgent has a special meaning, if added to client it will be used provided value for filtering out bots during tracking requests
Parameters
Name | Type | Description |
---|---|---|
value (required) | string | value used for comparison |
Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. We recommend that you pass the user agent to be filtered by Kameleoon when running server-side experiments for each visitor browsing your website, to avoid counting bots in your analytics.
If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.
If you run a Kameleoon hybrid experiment, your server-side experiments will be automatically protected against bot traffic. This is because Kameleoon collects the user-agent automatically on the front-end side. Therefore, you don't need to pass the user-agent or any other parameter to filter bots and spiders.
Error Handling
import {
KameleoonError,
KameleoonClient,
KameleoonException,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('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();
Almost every KameleoonClient
method may throw an error at some point, these errors are not just caveats but rather deliberately predefined KameleoonError
s
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.