NodeJS SDK
Introduction
Welcome to the developer documentation for the Kameleoon NodeJS SDK! Our SDK gives you the possibility of running experiments and activating feature flags on your server application. Integrating our SDK into your server is easy, and its footprint (in terms of memory and network usage) is low.
Before you begin installing our NodeJS 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.
Changelog
Latest version description of NodeJS SDK can be found here.
Installation
Use preferred package manager to install NodeJS SDK from npm repository.
Npm:
npm install @kameleoon/nodejs-sdk
Yarn:
yarn add @kameleoon/nodejs-sdk
Pnpm:
pnpm add @kameleoon/nodejs-sdk
Deno:
{
"imports": {
"@kameleoon/nodejs-sdk": "npm:@kameleoon/nodejs-sdk@^2.4"
}
}
Contents
To configure your NodeJS server 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 NodeJS SDK configuration as well as main tools for development.
- Initializing the Kameleoon Client
- Getting access to feature flags and variations
- Using Kameleoon Client methods
We highly recommend that you take a look at the Methods section, which includes useful information on every method that is introduced in NodeJS SDK.
- KameleoonUtils getVisitorCode - Obtain Visitor Code / Use own User ID
- KameleoonUtils getClientConfigurationUrl - Obtain Kameleoon Client Configuration URL
- initialize - Initialize Kameleoon Client
- addData - Add associated client data
- trackConversion - Track Conversion
- flush - 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
- List of supported targeting conditions
- Integration with Edge providers
- Tracking Rate Limit
- Synchronizing custom data across devices
- Error handling.
Main Usage
Here is a step-by-step guide for configuring NodeJS SDK for your application.
1. Initializing the Kameleoon Client
- Typescript
- Javascript
import {
Environment,
KameleoonClient,
SDKConfigurationType,
} from '@kameleoon/nodejs-sdk';
// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
updateInterval: 20,
environment: Environment.Production,
};
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) => {});
import { Environment, KameleoonClient } from '@kameleoon/nodejs-sdk';
// -- Optional configuration
const configuration = {
updateInterval: 20,
environment: Environment.Production,
};
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
// -- Waiting for the client initialization using `async/await`
async function init() {
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 NodeJS 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.
In order to add NodeJS SDK to an Edge environment please refer to Integration with Edge providers.
Arguments
Name | Type | Description |
---|---|---|
siteCode (required) | string | client's site code defined on Kameleoon platform |
configuration (optional) | Partial<SDKConfigurationType> | client's configuration |
integrations (optional) | IntegrationType | compute edge integrations, see Integration with Edge providers |
credentials (optional) | CredentialsType | client API credentials, see Tracking Rate Limit |
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 | 30 |
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 run experiments and manage 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.
- Typescript
- Javascript
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
// -- 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();
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
// -- 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
- Typescript
- Javascript
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
import { IncomingMessage, ServerResponse } from 'http';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
// -- Get visitor code using native `NodeJS/NextJS/Deno` `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
// -- Get visitor code using `Express`s `request`, `response` and optionally providing
// default visitor code
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req as IncomingMessage,
response: res as ServerResponse,
defaultVisitorCode: 'my_default_visitor_code',
});
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
import { IncomingMessage, ServerResponse } from 'http';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
// -- Get visitor code using native `NodeJS` `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
// -- Get visitor code using `express`s `request`, `response` and optionally providing
// default visitor code
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
defaultVisitorCode: 'my_default_visitor_code',
});
Static method getVisitorCode
called on KameleoonUtils
obtains visitor code from the request headers 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 response headers cookie
getVisitorCode
utilizes native NodeJS types for request
and response
, which are IncomingMessage
and ServerResponse
imported from http
module. However if you are using express
framework, the types of request
and response
will not match. This could be easily overcome using type cast as in example, it will produce identical result.
Parameters
Name | Type | Description |
---|---|---|
domain (required) | string | domain which cookie belongs to |
request (required) | IncomingMessage | server request |
response (required) | ServerResponse | server response |
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
Get Kameleoon Client Configuration URL
KameleoonUtils getClientConfigurationUrl
- Typescript / JavaScript
import { KameleoonUtils } from '@kameleoon/nodejs-sdk';
// -- Get Kameleoon Client Configuration URL
const uri = KameleoonUtils.getClientConfigurationUrl('my_site_code');
The static method getClientConfigurationUrl
called on KameleoonUtils
obtains the Kameleoon Client Configuration URL. Use this URL to retrieve a JSON representation of your feature flags. The JSON data contains all the information you need to activate your feature flags.
Parameters
Name | Type | Description |
---|---|---|
siteCode (required) | string | client's siteCode defined on Kameleoon platform |
Returns
string
- Kameleoon Client Configuration URL
Initialize Kameleoon Client
initialize
- Typescript
- Javascript
import {
KameleoonClient,
KameleoonError,
KameleoonException,
} from '@kameleoon/nodejs-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();
import { KameleoonClient, KameleoonException } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
try {
await client.initialize();
} catch (err) {
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.
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
- Typescript
- Javascript
import {
KameleoonClient,
BrowserType,
CustomData,
Browser,
} from '@kameleoon/nodejs-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();
import {
KameleoonClient,
BrowserType,
CustomData,
Browser,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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 flush method .This approach helps reduce the number of server calls made, as the data is typically grouped into a single server call triggered by the execution of flush.
The trackConversion method also sends out any previously associated data, just like the flush. The same holds true for getFeatureFlagVariationKey and getFeatureFlagVariable methods if an experimentation rule is triggered.
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
.
Check the list of supported conditions to know what data types can be used for targeting
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
The triggerExperiment()
method will be deprecated as SDK and Hybrid type experiments are being merged with feature experimentation in September 2023. Use feature experimentation methods instead.
- Typescript
- Javascript
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
const experimentId = 123;
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
// -- Trigger Experiment and obtain variation id
const variationId = client.triggerExperiment(visitorCode, experimentId);
}
init();
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
const experimentId = 123;
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
// -- Trigger Experiment and obtain variation id
const variationId = client.triggerExperiment(visitorCode, experimentId);
}
init();
The triggerExperiment()
method triggers an experiment by assigning the specified variation to the user with the specified visitorCode
. If the variation is already assigned, the method returns the variation ID and sends the 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
- Typescript
- Javascript
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
const experimentId = 123;
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
}
init();
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
const experimentId = 123;
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
}
init();
The method trackConversion()
creates and adds Conversion data to the visitor with the specified parameters and executes flush
.
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 (optional) | 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
flush
- Typescript
- Javascript
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data
client.flush(visitorCode);
}
init();
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data
client.flush(visitorCode);
}
init();
The method flush()
takes the Kameleoon data associated with the visitor and sends the data tracking request along with all of the data that's been added previously using the addData method.
If a visitorCode
isn't provided, the SDK flushes all of its stored data to the remote Kameleoon servers.
Previously, this method was named flushData
, which has been deprecated since 2.5.0
.
Parameters
Name | Type | Description |
---|---|---|
visitorCode (optional) | string | unique visitor identification string, can't exceed 255 characters length, if not passed all the data will be flushed (sent to the remote Kameleoon servers) |
Throws
Type | Description |
---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Get list of all experiments
getExperiments
The getExperiments()
method will be deprecated as SDK and Hybrid type experiments are being merged with feature experimentation in September 2023. Use feature experimentation methods instead.
- Typescript
- Javascript
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get experiment list
const experiments = client.getExperiments();
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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
The getVisitorExperiments()
method will be deprecated as SDK and Hybrid type experiments are being merged with feature experimentation in September 2023. Use feature experimentation methods instead.
- Typescript
- Javascript
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
// -- Get all visitor experiments
const experiments = client.getVisitorExperiments(visitorCode, false);
// -- Get only allocated visitor experiments
const experiments = client.getVisitorExperiments(visitorCode);
}
init();
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
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
- Typescript
- Javascript
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();
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient('my_site_code');
async function init() {
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
- Typescript
- Javascript
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get all feature flags
const experiments = client.getFeatureFlags();
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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
- Typescript
- Javascript
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
await client.initialize();
// -- Get active feature flags for visitor
const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}
init();
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
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
- Typescript
- Javascript
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
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();
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
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.FeatureFlagVariableNotFound | No feature variable was found for provided visitorCode and variableKey |
KameleoonException.DataInconsistency | Allocated variation was found, but there is no feature flag with according featureKey . |
Get variation key for a certain feature flag
getFeatureFlagVariationKey
- Typescript
- Javascript
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
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();
import {
KameleoonClient,
KameleoonUtils,
CustomData,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
domain: 'www.example.com',
request: req,
response: res,
});
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
- Typescript
- Javascript
import {
KameleoonClient,
VariableType,
JSONType,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- 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:
const myStr: string = result.value;
break;
default:
break;
}
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get feature variable
const variableResult = client.getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key'
variableKey: 'my_variable_key'
});
const { type, value } = variableResult;
}
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.JSONParse | Couldn't pass JSON value |
KameleoonException.NumberParse | Couldn't pass Number value |
Obtain data from Kameleoon remote source
getRemoteData
- Typescript
- Javascript
import { KameleoonClient } from '@kameleoon/nodejs-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();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get remote data
const jsonData = await getRemoteData('my_data_key');
const data = 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 |
Define an action for realt time configuration update
onConfigurationUpdate
- Typescript
- Javascript
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: '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();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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 |
Obtain custom data from Kameleoon Data API
getRemoteVisitorData
- Typescript
- Javascript
import { KameleoonClient, KameleoonDataType } from '@kameleoon/nodejs-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();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient('my_site_code');
async function init() {
await client.initialize();
// -- Get remote visitor data and add it to storage
const customDataList = await getRemoteVisitorData('my_visitor_code');
// -- Get remote visitor data without adding it to storage
const customDataList = 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.
getRemoteVisitorData
automatically attaches the latest custom data entry with scope=Visitor
to the visitor without calling addData
. You can use this data for Synchronizing custom data across devices.
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.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.RemoteData | Couldn't retrieve data from Kameleoon server |
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 NodeJS 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
- Typescript
- Javascript
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: '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();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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
Throws
Type | Description |
---|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length was exceeded |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
Data Types
Kameleoon Data types are helper classes used for storing data in storage in predefined forms. During the flush execution, the SDK collects all the data and sends it along with the tracking request.
Browser
- Typescript
- Javascript
import { KameleoonClient, BrowserType, Browser } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add new browser data to client
const browser = new Browser(BrowserType.Chrome, 86.1);
client.addData('my_visitor_code', browser);
}
init();
import { KameleoonClient, BrowserType, Browser } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add new browser data to client
const browser = new Browser(BrowserType.Chrome, 86.1);
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 ) |
version (optional) | number | version of the browser, floating point number represents major and minor version of the browser |
Conversion
- Typescript
- Javascript
import {
KameleoonClient,
ConversionParametersType,
Conversion,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: '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();
import { KameleoonClient, Conversion } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Defined conversion parameters
const conversionParameters = {
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 | - |
revenue (optional) | number | an optional parameter for revenue | 0 |
negative (optional) | boolean | an optional parameter identifying whether the conversion should be removed | false |
CustomData
- Typescript
- Javascript
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: '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();
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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.
To prevent the SDK from flushing the data with the selected index to the Kameleoon servers, check the Only save this data in Local Storage on the user's device, not on a server option when creating a new custom data entry on the Custom Data dashboard.
It's a useful option if you only want to utilize your private custom data for targeting.
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
- Typescript
- Javascript
import { KameleoonClient, DeviceType, Device } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: '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();
import { KameleoonClient, DeviceType, Device } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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
- Typescript
- Javascript
import {
KameleoonClient,
PageViewParametersType,
PageView,
} from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: '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();
import { KameleoonClient, PageView } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Define page view parameters
const pageViewParameters = {
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
- Typescript
- Javascript
import { KameleoonClient, UserAgent } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: '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();
import { KameleoonClient, UserAgent } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
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
Since NodeJS doesn't automatically provide the user agent header, you must provide UserAgent
data when using the bot-filtering
option in your NodeJS SDK project. Otherwise, all tracking calls will be disabled.
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 Kameleoon in hybrid mode, 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.
List of supported targeting conditions
Targeting conditions can be defined in the Kameleoon App on the Segment Dashboard.
The following list of conditions are supported by the SDK along with the data checked on the SDK side:
Condition Type | Description | Associated SDK Data |
---|---|---|
Exclusive Experiment | Check if only one certain experiment was triggered for visitor | Internal data saved after some experiments were triggered |
Target Experiment | Check if certain experiment was triggered for visitor | Internal data saved after some experiments were triggered |
Browser | Check if browser type or/and version matches parameters | Browser added by addData() method |
Device | Check if device type matches parameters | Device added by addData() method |
Conversion | Check if conversion goalId matches parameters | Conversion added by addData() method |
Custom Data | Check if custom data values matches parameters | CustomData added by addData() method |
Page Title | Check if page title value matches parameters | PageView added by addData() method |
Page Url | Check if page url value matches parameters | PageView added by addData() method |
SDK Language | Check if the current SDK language matches parameters | A type of the current SDK (NodeJS ) |
Visitor Code | Check if visitor code matches parameters | visitorCode passed as an argument to a method |
Error Handling
- Typescript
- Javascript
import {
KameleoonError,
KameleoonClient,
KameleoonException,
} from '@kameleoon/nodejs-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();
import { KameleoonClient, KameleoonException } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
try {
await client.initialize();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
} catch (error) {
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.
Integration with Edge providers
Kameleoon provides the following starter packs to automate your integration with specific edge providers:
Provider | Starter pack |
---|---|
Fastly Compute@Edge | https://github.com/Kameleoon/fastly-compute-starter-kit |
Cloudfare Workers | https://github.com/Kameleoon/cloudflare-worker-starter-kit |
AWS Lambda@Edge Function | https://github.com/Kameleoon/aws-lambda-edge-starter-kit |
For the other edge providers, you can initialize the Kameleoon Client yourself using externalClientConfiguration
. Passing externalClientConfiguration
causes the SDK to rely solely on the provided configuration data, instead of making a call to the Kameleoon servers. This gives you greater control and flexibility over the configuration data used in your application. For example:
- Typescript / Javascript
import rp from 'request-promise';
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
async function init() {
// -- Get Kameleoon Client Configuration URL
const uri = KameleoonUtils.getClientConfigurationUrl('my_site_code');
const clientConfiguration = await rp({
uri,
json: true,
});
const client = new KameleoonClient({
siteCode: 'my_site_code',
integrations: {
externalClientConfiguration: clientConfiguration,
},
});
}
init();
To update the configuration, obtain a fresh copy of the configuration data and re-initialize the client with the updated file.
Tracking Rate Limit
For the server systems dealing with the heavy load Kameleoon Provides a way to increase tracking request limit for Kameleoon API.
This can be achieved by passing credentials
to NodeJS SDK upon client initialization. CredentialsType
exported from SDK can be used for convenience in TypeScript
For server systems that deal with a high volume of requests, you can increase the tracking request limit for the Kameleoon API by passing credentials
to the NodeJS SDK during client initialization. For convenience, you can import the CredentialsType
in TypeScript from the SDK. For example:
- Typescript
- JavaScript
import {
CredentialsType,
KameleoonClient,
SDKConfigurationType,
} from '@kameleoon/nodejs-sdk';
// -- Credentials for access to higher request rate limit
const clientCredentials: CredentialsType = {
clientId: 'my_client_id',
clientSecret: 'my_client_secret',
};
const configuration: Partial<SDKConfigurationType> = {
credentials: clientCredentials,
};
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
// -- Credentials for access to higher request rate limit
const clientCredentials = {
clientId: 'my_client_id',
clientSecret: 'my_client_secret',
};
const configuration = {
credentials: clientCredentials,
};
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
Credentials Types
Name | Type | Description |
---|---|---|
clientId (required) | string | client id |
clientSecret (required) | string | client secret |
Follow Credentials Flow for more information
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.
The current implementation will change in an upcoming release.
The getRemoteVisitorData method implicitly attaches the latest custom data entry with scope=VISITOR to the visitor, so make sure your app calls this method before any other actions with Kameleoon Data. See the following example:
- TypeScript
- JavaScript
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Before working with data, make `getRemoteVisitorData` call
// -- That way visitor will always has latest data with `scope=VISITOR`
// associated (even without manually calling `addData`)
await getRemoteVisitorData("my_visitor_code");
// -- Let's say that only "Device 1" adds visitor data
if global.device === "Device 1" {
// -- Create custom data
// -- Let's assume index `0` is set to `scope=VISITOR` on Kameleoon Platform
const customData = new CustomData(0, "my_data");
// -- Add custom data
client.addData('my_visitor_code', customData);
}
// -- As a result visitor on "Device 1" and the same visitor on other devices will
// always have `CustomData(0, "my_data")` associated with them in the storage
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Before working with data, make `getRemoteVisitorData` call
// -- That way visitor will always has latest data with `scope=VISITOR`
// associated (even without manually calling `addData`)
await getRemoteVisitorData("my_visitor_code");
// -- Let's say that only "Device 1" adds visitor data
if global.device === "Device 1" {
// -- Create custom data
// -- Let's assume index `0` is set to `scope=VISITOR` on Kameleoon Platform
const customData = new CustomData(0, "my_data");
// -- Add custom data
client.addData('my_visitor_code', customData);
}
// -- As a result visitor on "Device 1" and the same visitor on other devices will
// always have `CustomData(0, "my_data")` associated with them in the storage
}
init();