Mit dem NodeJS SDK können Sie Experiments ausführen und feature flags aktivieren. Die Integration unseres SDKs in Ihren Server ist einfach, und sein Footprint (Speicher- und Netzwerknutzung) ist gering. Unser Node SDK unterstützt Node Version 16+ mit der Möglichkeit, eine Herabstufung auf Version 14 und 12 vorzunehmen, indem Sie den Kompatibilitätsmodus.
Erste Schritte: Hilfe für den Einstieg finden Sie im Entwicklerhandbuch.
SDK-Methoden: Die vollständige Referenzdokumentation des NodeJS SDK finden Sie im reference Abschnitt.
Changelog: Aktuelle Version des NodeJS SDK: Changelog.
Bevor Sie mit der Installation unseres NodeJS SDK beginnen, empfehlen wir Ihnen, unseren Artikel zu technischen Überlegungen zu lesen, um die technologischen Konzepte hinter unseren SDKs zu verstehen. Dieser Artikel hilft Ihnen, eine erfolgreiche Integration sicherzustellen.
Entwicklerhandbuch
Folgen Sie diesem Abschnitt, um das SDK zu installieren und zu konfigurieren und mehr über erweiterte Funktionen zu erfahren.
Erste Schritte
Installation
Verwenden Sie das Kameleoon SDK-Installationstool, um das SDK zu installieren. Der SDK-Installer hilft Ihnen, das SDK Ihrer Wahl zu installieren, ein einfaches Codebeispiel zu generieren und externe Abhängigkeiten bei Bedarf zu konfigurieren.
Um das SDK-Installationstool zu verwenden, installieren und führen Sie es global aus:
npm install --global @kameleoon/sdk-installer
kameleoon-sdk
Oder führen Sie es direkt aus mit npx:
npx @kameleoon/sdk-installer
Bei Verwendung von Deno stellen Sie die Abhängigkeiten manuell bereit in deno.json:
{
"imports": {
"@kameleoon/nodejs-sdk": "npm:@kameleoon/nodejs-sdk@^4.0",
// -- Optional dependencies, can be implemented manually
"@kameleoon/nodejs-requester": "npm:@kameleoon/nodejs-requester@^1.0",
"@kameleoon/nodejs-event-source": "npm:@kameleoon/nodejs-event-source@^1.0",
"@kameleoon/deno-visitor-code-manager": "npm:@kameleoon/deno-visitor-code-manager@^1.0",
}
}
Initialisierung des Kameleoon-Clients
Entwickler müssen einen Einstiegspunkt für das NodeJS SDK erstellen, indem sie eine neue Instanz von KameleoonClient.
Es wird empfohlen, KameleoonClient als Singleton zu behandeln, also eine einzige gemeinsame Instanz zu erstellen und sie über die gesamte Serverinstanz hinweg wiederzuverwenden, um Konsistenz zu gewährleisten und unnötige Neuinitialisierungen zu vermeiden.
Verwenden Sie KameleoonClient um feature Experiments auszuführen und den Status von feature flags und deren variations abzurufen.
KameleoonClient initialisiert asynchron, um sicherzustellen, dass die Kommunikation mit der Kameleoon API erfolgreich ist, unter Verwendung der initialize() Methode. Sie können async/await, Promise.then(), oder ein anderes asynchrones Muster verwenden, um die Client-Initialisierung zu handhaben.
import {
Environment,
KameleoonClient,
SDKConfigurationType,
CredentialsType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
// -- Mandatory credentials
const credentials: CredentialsType = {
clientId: 'my_client_id',
clientSecret: 'my_client_secret',
};
// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
updateInterval: 20,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials,
configuration,
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
// -- 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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
// -- Mandatory credentials
const credentials = {
clientId: 'my_client_id',
clientSecret: 'my_client_secret',
};
// -- Optional configuration
const configuration = {
updateInterval: 20,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials,
configuration,
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
// -- 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) => {});
Arguments
| Name | Type | Description |
|---|
| siteCode (required) | string | Dies ist the unique key des Kameleoon project you are using mit dem SDK. This field is mandatory. |
| credentials (required) | CredentialsType | client API credentials, see credentials flow for more information |
| externals (required) | ExternalsType | external implementation of SDK dependencies (Externe Abhängigkeiten) |
| configuration (optional) | Partial<SDKConfigurationType> | client’s configuration |
| compatibility (optional) | Compatibility | SDK’s Kompatibilitätsmodus, see Kompatibilitätsmodus |
| integrations (optional) | IntegrationType | compute edge integrations, see Integration mit Edge-Anbieter |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Credentials | Client credentials were not provided oder are empty |
Konfigurationsparameter
SDK Version 4
SDK Version 5
| Name | Type | Description | Default Value |
|---|
| updateInterval (optional) | number | Specifies the refresh interval, in minutes, that the SDK fetches die Konfiguration für den active Experiments und feature flags. The value determines the maximum time it takes to propagate changes, wie zum Beispiel activating oder deactivating feature flags oder launching Experiments, to Ihr production servers. If left unspecified, the default interval gesetzt ist to 60 minutes. Zusätzlich we offer a streaming mode that uses server-sent Ereignisse (SSE) to push new configurations zum SDK automatically und apply new configurations in real-time, ohne any delays. | 60 |
| environment (optional) | Environment | feature flag environment | Environment.Production |
| targetingDataCleanupInterval (optional) | number | interval in minutes for cleaning up targeting data, minimum value is 1 minute | 30 |
| domain (optional) | string | domain to which das Cookie belongs. Deprecated, use cookieDomain instead | undefined |
| cookieDomain (optional) | string | domain to which das Cookie belongs. | undefined |
| networkDomain (optional) | string | custom domain the SDK uses in all outgoing network Anfragen, commonly used for proxying. The format is second_level_domain.top_level_domain (zum Beispiel, example.com). The SDK uses the default Kameleoon value wenn der format is invalid. | undefined |
| requestTimeout (optional) | number | timeout in milliseconds for all SDK network Anfragen, if timeout is exceeded request will fail | 10_000 (10 seconds) |
| trackingInterval (optional) | number | Specifies the interval for tracking Anfragen in milliseconds. All Besucher who were evaluated for any feature flag oder had associated data will be included in this tracking request. The tracking request is performed once per interval. The minimum value is 100 ms und der maximum value is 1_000 ms | 1_000 (1 second) |
The domain parameter is deprecated und will be removed in dem future. Verwenden Sie cookieDomain instead.
| Name | Type | Description | Default Value |
|---|
| updateInterval (optional) | number | Specifies the refresh interval, in minutes, that the SDK fetches die Konfiguration für den active Experiments und feature flags. The value determines the maximum time it takes to propagate changes, wie zum Beispiel activating oder deactivating feature flags oder launching Experiments, to Ihr production servers. If left unspecified, the default interval gesetzt ist to 60 minutes. Zusätzlich we offer a streaming mode that uses server-sent Ereignisse (SSE) to push new configurations zum SDK automatically und apply new configurations in real-time, ohne any delays. | 60 |
| environment (optional) | Environment | string | feature flag environment | Environment.Production |
| targetingDataCleanupInterval (optional) | number | interval in minutes for cleaning up targeting data, minimum value is 1 minute | 30 |
| cookieDomain (optional) | string | domain that das Cookie belongs to. | undefined |
| networkDomain (optional) | string | The custom domain the SDK uses in all outgoing network Anfragen, commonly used for proxying. The format is second_level_domain.top_level_domain (zum Beispiel, example.com). The SDK uses the default Kameleoon value wenn der format is invalid. | undefined |
| requestTimeout (optional) | number | timeout in milliseconds for all SDK network Anfragen, if timeout is exceeded request will fail immediately | 10_000 (10 seconds) |
| trackingInterval (optional) | number | Specifies the interval for tracking Anfragen in milliseconds. All Besucher who were evaluated for any feature flag oder had associated data will be included in this tracking request. The tracking request is performed once per interval. The minimum value is 1_000 ms und der maximum value is 5_000 ms | 1_000 (1 second) |
| defaultDataFile (optional) | string | The defaultDataFile feature ensures the Kameleoon SDK is always READY by providing a fallback configuration when no cached Datendatei existiert. Developers can preload a valid configuration by fetching it from https://sdk-config.kameleoon.eu/v3/<sitecode> und passing it as defaultDataFile during initialization. Wenn ein dateModified timestamp (in milliseconds) is provided und is newer than the cached version, the SDK will use the default datafile instead des cached version. If dateModified is omitted, the default datafile is only applied when no cached version existiert. Dies stellt sicher the SDK always has a valid configuration, whether default, cached, oder updated. | undefined |
Option 1 (Recommended): Verwenden Sie JSON.stringify()const dataFileJson = {"configuration":{"consentType":.....,
{"key":"show_car","type":"JSON","value":"{\"make\":\"Porsche\",\"model\":\"911\"}"}},
"dateModified":1752209266000};
const dataFileString = JSON.stringify(dataFileJson);
const configuration = {
updateInterval: 20,
defaultDataFile: dataFileString
};
Option 2: Raw JSON string (escape special characters)const configuration = {
updateInterval: 20,
defaultDataFile: `{"configuration":{"consentType":.....,
{"key":"show_car","type":"JSON","value":"{\\"make\\":\\"Porsche\\",\\"model\\":\\"911\\"}"},
"dateModified":1752209266000}`
};
Kompatibilitätsmodus
Verwenden Sie the SDK parameter compatibility to disable some des SDK’s features to improve compatibility mit older NodeJS versions.
Compatibility is an enum representing all possible Kompatibilitätsmoduss:
Compatibility.Node16 - default mode, all features are enabled. This mode wird verwendet if no Kompatibilitätsmodus is provided. Supports Node version 16 und higher.
Compatibility.Node14 - compatibility mit this version will make the requestTimeout parameter in SDKConfigurationType unavailable und prevent the SDK from using AbortController for request cancellation, even within default 10_000 ms timeout. Supports Node version 14 und higher.
Compatibility.Node12 - compatibility mit this version implies the same limitations as the Node14 Kompatibilitätsmodus. Zusätzlich Sie könnennot provide “@kameleoon/nodejs-requester” as a requester implementation in this Kompatibilitätsmodus, as it uses the “node-fetch” library, which doesn’t support the Node.js 12.x.x version. A developer must provide a custom requester implementation of their choice, wie zum Beispiel an older “node-fetch” version oder other HTTP based implementation.
Aktivieren eines feature flag
Zuweisen einer eindeutigen ID an einen Benutzer
To assign a unique ID to ein Benutzer, Sie können use the getVisitorCode() Methode. Wenn ein Besuchercode doesn’t exist (from die Anfrage headers cookie), the Methode generates a random unique ID oder uses a defaultVisitorCode that you would have generated. The ID is then set in einem response headers cookie.
Wenn Sie are using Kameleoon in Hybrid mode, calling the getVisitorCode() Methode ensures that the unique ID (Besuchercode) is shared zwischen dem application file engine.js (previously named, kameleoon.js) und der SDK.
Abrufen einer Flag-Konfiguration
To implement a feature flag in Ihr code, Sie müssen first create the feature flag in Ihr Kameleoon account.
To determine the status oder variation eines feature flag für ein specific user, Sie sollten use the getVariation() oder isFeatureFlagActive() Methode to retrieve die Konfiguration basierend auf dem featureKey.
The getVariation() Methode handles both simple feature flags mit ON/OFF states und more complex flags mit multiple variations. The Methode ruft den appropriate variation for der Benutzer by checking the feature Regeln, assigning die variation, und returning it basierend auf dem featureKey und visitorCode.
The isFeatureFlagActive() Methode kann verwendet werden wenn Sie want to retrieve die Konfiguration eines simple feature flag that has only an ON oder OFF state, as opposed to more complex feature flags mit multiple variations oder targeting options.
If Ihr feature flag has associated variables (wie zum Beispiel specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which bietet details about the assigned variation und its associated experiment. Diese Methode checks whether der Benutzer is targeted, finds der Besucher’s assigned variation, und saves it to storage. When track=true, the SDK will send the exposure event zum specified experiment auf dem next tracking request, which is automatically triggered basierend auf dem SDK’s tracking_interval_millisecond. Standardmäßig this interval gesetzt ist to 1000 milliseconds (1 second).
The getVariation() Methode ermöglicht you to control whether tracking is done. If track=false, no exposure Ereignisse wird gesendet durch den SDK. Dies ist useful wenn Sie prefer not to track data durch den SDK und instead rely on client-side tracking managed durch den Kameleoon engine, zum Beispiel. Zusätzlich setting track=false is helpful when unter Verwendung der getVariations() Methode, where you might only need the variations for all flags ohne triggering any tracking Ereignisse. Wenn Sie want to know more about how tracking works, view this article
Hinzufügen von Datenpunkten, um einen Benutzer zu targetieren oder Besuche in Berichten zu filtern / aufzuschlüsseln
To target ein Benutzer, ensure you’ve added relevant data points to their profile before retrieving the feature variation oder checking wenn der flag is active. Verwenden Sie the addData() Methode to add these data points to der Benutzer’s profile.
To retrieve data points collected on other devices oder to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the getRemoteVisitorData() Methode. Diese Methode asynchronously fetches data aus dem servers. It is important to call getRemoteVisitorData() before retrieving die variation oder checking wenn der feature flag is active, as this data might be required to assign ein Benutzer zu einem given variation.
To learn more about available Targeting-Bedingungs, see the detailed article auf dem subject.
Zusätzlich the data points you add to der Besucher profile will be available when analyzing Ihr Experiments, allowing you to filter und break down Ihr results by factors like device und browser. Kameleoon Hybrid mode automatically collects a variety of data points on der Client-side, making it easy to break down Ihr results basierend auf demse pre-collected data points. See the complete list here.
If Sie müssen track additional data points beyond what’s automatically collected, Sie können use Kameleoon’s Custom Data feature. Custom Data ermöglicht you to capture und analyze specific information relevant to Ihr Experiments. Don’t forget to call the flush() Methode to send the collected data to Kameleoon servers for analysis.
To ensure Ihr results are accurate, it’s recommended to filter out bots durch die Verwendung von the UserAgent data type.
Tracking von Ziel-Conversions
Wenn ein user completes a desired action (wie zum Beispiel making a purchase), it is recorded as a Conversion. To track Conversions, use the trackConversion() Methode und provide the required visitorCode und goalId parameters.
The Conversion tracking request wird gesendet zusammen mit the next scheduled tracking request, which the SDK sends at regular intervals (defined by tracking_interval_millisecond). Wenn Sie psiehe send die Anfrage immediately, use the flush() Methode mit der Parameter instant=true.
Senden von Ereignissen an Analyse-Lösungen
To track Conversions und send exposure Ereignisse to Ihr customer analytics solution, Sie müssen first implement Kameleoon in Hybrid mode. Then, use the getEngineTrackingCode() Methode.
The getEngineTrackingCode() Methode ruft den unique tracking code required to send exposure Ereignisse to Ihr analytics solution. Using this Methode ermöglicht you to record Ereignisse und send them to Ihr desired analytics platform.
Fehlerbehandlung
Almost every KameleoonClient Methode may throw ein Fehler at some point. These Fehler are deliberately predefined KameleoonErrors
that extend the native JavaScript Error class, providing useful messages und a special type field mit ein Typ KameleoonException.
KameleoonException is an enum containing all possible error types.
To know exactly what type of KameleoonException the Methode may throw, check the Methode description’s Throws Abschnitt, oder hover over the Methode in Ihr IDE to see the jsdocs description.
Handling Fehler is considered a good practice to make Ihr application more stable und avoid technical issues.
import {
KameleoonError,
KameleoonClient,
KameleoonException,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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();
Integration mit Edge-Anbieter
SDK Version 4
SDK Version 5
Kameleoon bietet Folgendes starter packs to automate Ihr integration mit specific edge providers:For the other edge providers, Sie können initialize den Kameleoon-Client yourself using externalClientConfiguration. Passing externalClientConfiguration causes the SDK to rely solely auf dem provided configuration data instead of making ein Aufruf zum Kameleoon servers. externalClientConfiguration gives you greater control und flexibility over die Konfiguration data used in Ihr application. Zum Beispiel:import rp from 'request-promise';
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
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',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
integrations: {
externalClientConfiguration: clientConfiguration,
},
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
}
init();
Kameleoon bietet Folgendes starter packs to automate Ihr integration mit specific edge providers:For other edge providers, use External Dependencies for greater control over the SDK.
Geräteübergreifende Experimentierung
To support Besucher who access an app from multiple devices, Kameleoon ermöglicht the synchronization of previously collected visitor data across each of der Besucher’s devices und reconciliation of their visit history across devices through cross-device experimentation. Case studies und detailed information on how Kameleoon handles data across devices sind verfügbar in dem article on cross-device experimentation.
Synchronisieren von custom data über Geräte hinweg
Although custom mapping synchronization verwendet wird to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required:
Same user ID across devices
Wenn der same user ID verwendet wird consistently across all devices, synchronization is handled automatically ohne einen custom mapping sync. It is enough to call the getRemoteVisitorData() Methode wenn Sie want to sync the data collected between multiple devices.
Multi-server instances mit consistent IDs
In complex setups involving multiple servers (zum Beispiel, distributed server instances), where the same user ID ist verfügbar across servers, synchronization between servers (with getRemoteVisitorData()) is sufficient ohne additional custom mapping sync.
Customers who need additional data can siehe the getRemoteVisitorData() Methode description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the visitorCode, which can also be referred to as userId) verwendet wird consistently zwischen dem two devices for accurate data retrieval.
Wenn Sie want to sync collected data in real time, Sie müssen choose the scope Visitor for Ihr custom data.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Custom Data with index `0` was set to `Visitor` scope
// in Kameleoon.
const customDataIndex = 0;
const customData = new CustomData(customDataIndex, 'my_data');
client.addData('my_visitor', customData);
client.flush();
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Before working with data, call `getRemoteVisitorData`.
await getRemoteVisitorData({ visitorCode: 'my_visitor_code' });
// -- New SDK code will have access to CustomData with `Visitor` scope
// defined on Device One.
// So, "my_data" is available to target and track "my_visitor".
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Custom Data with index `0` was set to `Visitor` scope
// in Kameleoon.
const customDataIndex = 0;
const customData = new CustomData(customDataIndex, 'my_data');
client.addData('my_visitor', customData);
client.flush();
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Before working with data, call `getRemoteVisitorData`.
await getRemoteVisitorData({ visitorCode: 'my_visitor_code' });
// -- New SDK code will have access to CustomData with `Visitor` scope
// defined on Device One.
// So, "my_data" is now available to target and track "my_visitor".
}
init();
Verwendung von custom data zur Session-Zusammenführung
SDK Version 4
SDK Version 5
Geräteübergreifende Experimentierung lets you combine ein Besucher’s history across each of their devices (history reconciliation). Sie können merge multiple visitor Sessions into one mit history reconciliation. Verwenden Sie CustomData und provide a unique identifier for der Besucher to reconcile visit history.Folgen Sie the activating cross-device history reconciliation guide to set up Ihr custom data in Kameleoon.Sie können custom data in Ihr code to merge ein Besucher’s session. Sessions mit dem same identifier will always see the same experiment variation, und will be displayed as a single visitor in dem Visitor view of Ihr experiment’s result page.The SDK configuration ensures that associated Sessions always see the same variation of das Experiment.The following Methoden might be helpful in dem context of session merging:
- Verwenden Sie
getRemoteVisitorData mit isUniqueIdentifier=true to retrieve data for all linked Besucher.
- Verwenden Sie
trackConversion oder flush mit isUniqueIdentifier=true to track data for specific visitor that is associated mit another visitor.
In das folgende Beispiel, we have an application mit einem login page. Since we don’t know der Benutzer ID at the time of login, we use an anonymous visitor identifier generated durch den getVisitorCode Methode. Nach dem user logs in, we can associate the anonymous visitor mit der Benutzer ID und use it as a unique identifier for der Besucher.import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `global` to re-use it later
global.anonymousVisitor = anonymousVisitor;
// -- Getting a variation, assume it's variation `A`
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData } from '@kameleoon/nodejs-sdk';
async function init(): Promise<void> {
// -- At this point anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `global` object
client.addData(global.anonymousVisitor, userIdentifierData);
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
// -- Informing the SDK that the visitor is a unique identifier.
isUniqueIdentifier: true,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
// -- Informing the SDK that the visitor is a unique identifier.
isUniqueIdentifier: true,
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `global` to re-use it later.
global.anonymousVisitor = anonymousVisitor;
// -- Getting a variation, assume it's variation `A`.
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData } from '@kameleoon/nodejs-sdk';
async function init() {
// -- At this point anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `global` object
client.addData(global.anonymousVisitor, userIdentifierData);
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
// -- Informing the SDK that the visitor is a unique identifier.
isUniqueIdentifier: true,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
// -- Informing the SDK that the visitor is a unique identifier.
isUniqueIdentifier: true,
});
}
init();
Geräteübergreifende Experimentierung lets you combine ein Besucher’s history across each of their devices (history reconciliation). Sie können merge multiple visitor Sessions into one mit history reconciliation. Verwenden Sie CustomData und provide a unique identifier for der Besucher to reconcile visit history.Folgen Sie the activating cross-device history reconciliation guide to set up Ihr custom data in Kameleoon.Sie können custom data in Ihr code to merge ein Besucher’s session. Sessions mit dem same identifier will always see the same experiment variation, und will be displayed as a single visitor in dem Visitor view of Ihr experiment’s result page.The SDK configuration ensures that associated Sessions always see the same variation of das Experiment.Before using other methods, inform the SDK that der Besucher is a unique identifier by adding UniqueIdentifier data to ein Besucher.In das folgende Beispiel, we have an application mit einem login page. Since we don’t know der Benutzer ID at the time of login, we use an anonymous visitor identifier generated durch den getVisitorCode Methode. Nach dem user logs in, we can associate the anonymous visitor mit der Benutzer ID und use it as a unique identifier for der Besucher.import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `global` to re-use it later.
global.anonymousVisitor = anonymousVisitor;
// -- Getting a variation, assume it's variation `A`.
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData, UniqueIdentifier } from '@kameleoon/nodejs-sdk';
async function init(): Promise<void> {
// -- At this point anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `global` object
client.addData(global.anonymousVisitor, userIdentifierData);
// -- Flushing data for the anonymous `visitorCode`
client.flush(global.anonymousVisitor);
// -- Informing the SDK that the visitor is a unique identifier.
client.addData('my_user_id', new UniqueIdentifier(true));
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `global` to re-use it later.
global.anonymousVisitor = anonymousVisitor;
// -- Getting a variation, assume it's variation `A`.
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData, UniqueIdentifier } from '@kameleoon/nodejs-sdk';
async function init() {
// -- At this point anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `global` object
client.addData(global.anonymousVisitor, userIdentifierData);
// -- Flushing data for the anonymous `visitorCode`
client.flush(global.anonymousVisitor);
// -- Informing the SDK that the visitor is a unique identifier.
client.addData('my_user_id', new UniqueIdentifier(true));
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
});
}
init();
Verwendung eines benutzerdefinierten Bucketing-Keys
Standardmäßig Kameleoon uses a unique, anonymous visitor ID (visitorCode) to assign Benutzer to feature flag variations. This ID is typically generated und stored on der Benutzer’s device (in a browser cookie for client-side und server-side SDKs—in persistent storage for mobile SDKs). Allerdings in certain scenarios Sie können need to ensure all Benutzer des same organization see the same variant eines feature flag.
The Custom Bucketing Key option ermöglicht you to override this default behavior by providing Ihr own custom identifier for bucketing. This override ensures that Kameleoon’s assignment logic uses Ihr specified key instead des default visitorCode.
Anwendungsfälle
Verwendung eines benutzerdefinierten Bucketing-Keys is essential for maintaining consistency und accuracy in Ihr feature flag assignments, particularly in these situations:
- Account-level oder organizational Experiments: For B2B products oder scenarios where you want to assign all Benutzer aus dem same organization zum same variation, Sie können use an identifier like an
accountId. Custom bucketing keys are crucial for A/B-Testing features that impact an entire team oder company.
By implementing a custom bucketing key, you ensure greater consistency und accuracy in Ihr Experiments, leading to more reliable results und a better user experience.
Technische Details
Wenn Sie configure a custom bucketing key für ein feature flag, you provide Kameleoon mit einem specific identifier from Ihr application’s data:
client.addData(visitorCode, new CustomData(index, 'newVisitorCode'));
- Providing the custom key: You provide Ihr custom identifier zum Kameleoon SDK unter Verwendung der
addData() Methode. In this Methode, Sie werden pass Ihr chosen custom bucketing key as a CustomData object. Here, newVisitorCode refers zum identifier you wish to use for Ihr bucketing (zum Beispiel, the new userId oder accountId).
For the custom bucketing key to function correctly, it must also be defined und configured für den feature flag während des flag creation oder editing process. Without this corresponding configuration, the SDK’s bucketing will not apply Ihr custom key. For detailed instructions on how to set this up in Kameleoon, siehe this article.
- Bucketing logic: Sobald ein custom bucketing key is provided durch den
addData() Methode, all hash calculations for assigning Benutzer to variations will use this newVisitorCode (Ihr custom key) instead des default visitorCode. Unter Verwendung der newVisitorCode means that the bucketing decision is tied to Ihr custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
- Data tracking und analytics: It’s crucial to beachten Sie, dass while the
newVisitorCode (Ihr custom key) verwendet wird for bucketing decisions, all subsequent data (tracking Ereignisse und Conversions, zum Beispiel) is sent und associated mit dem original visitorCode. This separation ensures that Ihr analytics accurately reflect individual user journeys und interactions within Ihr experiment’s broader context, even when bucketing is performed at a higher level (like an account) oder across multiple devices/Sessions. Ihr original visitor data remains intact for comprehensive reporting.
Technische Anforderungen
To effectively use a custom bucketing key:
- The key muss ein
string.
- It must be unique für den entity you intend to bucket (zum Beispiel, if using a
userId, each user’s ID should be unique).
- The key must be available zum SDK at the exact moment the feature flag decision is evaluated for that user oder request.
Targeting-Bedingungen
The Kameleoon SDKs support a variety of predefined Targeting-Bedingungs that Sie können use to target Benutzer in Ihr campaigns. For die Liste of conditions supported by this SDK, see use visit history to target Benutzer.
Sie können also use Ihr own external data to target Benutzer.
Logging
The SDK generates logs to reflect various internal processes und issues.
Log-Level
The SDK unterstützt configuring limiting logging durch ein log level.
import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
// The `NONE` log level does not allow logging.
client.setLogLevel(LogLevel.NONE);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.NONE);
// The `ERROR` log level only allows logging issues that may affect the SDK's main behaviour.
client.setLogLevel(LogLevel.ERROR);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.ERROR);
// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
client.setLogLevel(LogLevel.WARNING);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.WARNING);
// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
client.setLogLevel(LogLevel.INFO);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.INFO);
// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
// The `NONE` log level does not allow logging.
client.setLogLevel(LogLevel.NONE);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.NONE);
// The `ERROR` log level only allows logging issues that may affect the SDK's main behaviour.
client.setLogLevel(LogLevel.ERROR);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.ERROR);
// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
client.setLogLevel(LogLevel.WARNING);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.WARNING);
// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
client.setLogLevel(LogLevel.INFO);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.INFO);
// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
Benutzerdefinierte Log-Behandlung
The SDK writes its logs zum console output by default. This behaviour can be overridden.
Logging limiting durch ein log level is performed apart aus dem log handling logic.
import { KameleoonClient, KameleoonLogger, IExternalLogger, LogLevel } from '@kameleoon/nodejs-sdk';
export class CustomLogger implements IExternalLogger {
// `log` method accepts logs from the SDK
public log(level: LogLevel, message: string): void {
// Custom log handling logic here. For example:
switch (level) {
case LogLevel.DEBUG:
console.debug(message);
break;
case LogLevel.INFO:
console.info(message);
break;
case LogLevel.WARNING:
console.warn(message);
break;
case LogLevel.ERROR:
console.error(message);
break;
}
}
}
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
logger: new CustomLogger(),
},
});
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/nodejs-sdk';
export class CustomLogger {
// `log` method accepts logs from the SDK
log(level, message) {
// Custom log handling logic here. For example:
switch (level) {
case 'DEBUG':
console.debug(message);
break;
case 'INFO':
console.info(message);
break;
case 'WARNING':
console.warn(message);
break;
case 'ERROR':
console.error(message);
break;
}
}
}
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
logger: new CustomLogger(),
},
});
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
Domain-Informationen
You provide a domain as the domain in KameleoonClient configuration, which verwendet wird for storing Kameleoon Besuchercode in Cookies. Providing a domain is important when working mit dem getVisitorCode und setLegalConsent Methoden. The domain you provide is stored in das Cookie as the Domain= key.
Festlegen der Domain
The domain you provide lets the URL address use das Cookie. Zum Beispiel, if Ihr domain is www.example.com, das Cookie is only available aus einem www.example.com URL. Pages mit dem app.example.com domain can’t use das Cookie.
For more flexibility mit subdomains, Sie können specify a domain starting mit einem .. For instance, domain .example.com ermöglicht das Cookie to function on both app.example.com und login.example.com.
Sie können’t use regular expressions, special symbols, protocol, oder port numbers in dem domain. Zusätzlich a specific list of subdomains kann nicht be used mit dem prefix ..
Here’s a small domain cheat sheet:
| Domain | Allowed URLs | Disallowed URLs |
|---|
www.example.com | ✅www.example.com | ❌ app.example.com |
| ✅ example.com | ❌ .com |
| | |
.example.com = example.com | ✅ example.com | ❌ otherexample.com |
| ✅ www.example.com | |
| ✅ app.example.com | |
| ✅ login.example.com | |
https://www.example.com | ⛔ bad domain | ⛔ bad domain |
www.example.com:4408 | ⛔ bad domain | ⛔ bad domain |
.localhost.com = localhost | ⛔ bad domain | ⛔ bad domain |
Entwicklung auf localhost
localhost is always considered a bad domain, making it hard to test die Domain when developing on localhost.
There are two ways to avoid this issue:
- Don’t specify the
domain field in dem SDK client while testing. Dies verhindert localhost issues (das Cookie wird gesetzt on any domain).
- Create a local domain for
localhost. Zum Beispiel:
- Navigate to
/etc/hosts on Linux oder to c:\Windows\System32\Drivers\etc\hosts on Windows
- Öffnen Sie
hosts mit file super user oder administrator rights
- Fügen Sie hinzu a domain zum
localhost port, zum Beispiel: 127.0.0.1 app.com
- Now, Sie können run Ihr app locally on
app.com:{my_port} und specify .app.com as Ihr domain
Externe Abhängigkeiten
The SDK’s externe Abhängigkeiten use the dependency injection pattern, letting you provide Ihr own implementations for certain parts eines SDK.
In the NodeJS SDK, some externe Abhängigkeiten have default implementations, while others must be provided by der Benutzer, whether using dedicated Kameleoon implementations oder custom implementations.
Here’s die Liste of available externe Abhängigkeiten:
| Dependency | Interface | Required/Optional | API Used | Description |
|---|
storage | IExternalStorage | Optional | Server memory | Used for storing all des existing und collected SDK data |
eventSource | IExternalEventSource | Required | - | Used for receiving Server Sent Events for Real Time Updates capabilities |
requester | IExternalRequester | Required | - | Used for performing all network Anfragen |
visitorCodeManager | IExternalVisitorCodeManager | Required | - | Used for storing und synchronizing Besuchercode |
logger | ILogger | Optional | Custom implementation | Used for custom handling of logs aus dem SDK. Lets Benutzer define how logs are processed und where they output. |
Sie können also implement visitorCodeManager unter Verwendung der IExternalNextJSVisitorCodeManager, IExternalDenoVisitorCodeManager, oder IExternalCustomVisitorCodeManager interfaces for NextJS, Deno, oder custom Besuchercode manager implementations, respectively.
Externe Abhängigkeiten provide developers flexibility to adapt und use the NodeJS SDK in any environment. There are eine Zahl of npm packages Kameleoon bietet for frequently used environments. Sie können install the packages manually, oder durch die Verwendung von the SDK installation tool (recommended).
These are the Kameleoon-provided externe Abhängigkeiten for NodeJS SDK:
@kameleoon/nodejs-event-source - basierend auf eventsource library (kann verwendet werden for NodeJS/Deno/NextJS SSR)
@kameleoon/nodejs-requester - basierend auf node-fetch library (kann verwendet werden for NodeJS/Deno/NextJS SSR)
@kameleoon/nodejs-visitor-code-manager - implemented mit server memory storage
@kameleoon/deno-visitor-code-manager - implemented using Deno request/response Cookies
@kameleoon/nextjs-visitor-code-manager - implemented using NextJS SSR headers cookie oder NextJS SSR request/response
Sie können optionally implement externe Abhängigkeiten on Ihr own.
The following example implements externe Abhängigkeiten. To import an interface aus einem SDK, create a class that implements it und pass the instantiated class zum SDK.
Storage
import { IExternalStorage, KameleoonClient } from '@kameleoon/nodejs-sdk';
// --- External Storage implementation ---
// - JavaScript `Map` is used as an example storage
const storage = new Map();
class MyStorage<T> implements IExternalStorage<T> {
public read(key: string): T | null {
// - Read data using `key`
const data = storage.get(key);
// - Return `null` if there's no data
if (!data) {
return null;
}
// - Return obtained data
return data;
}
public write(key: string, data: T): void {
// - Write data using `key`
storage.set(key, data);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
storage: new MyStorage(),
},
});
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
// --- External Storage implementation ---
// - JavaScript `Map` is used as an example storage
const storage = new Map();
class MyStorage {
read(key) {
// - Read data using `key`
const data = storage.get(key);
// - Return `null` if there's no data
if (!data) {
return null;
}
// - Return obtained data
return data;
}
write(key, data) {
// - Write data using `key`
storage.set(key, data);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
storage: new MyStorage(),
},
});
EventSource
import {
IExternalEventSource,
KameleoonClient,
EventSourceOpenParametersType,
} from '@kameleoon/nodejs-sdk';
// --- External EventSource implementation ---
// - Example uses dummy `EventSource` class
class MyEventSource implements IExternalEventSource {
private eventSource?: EventSource;
public open({
eventType,
onEvent,
url,
}: EventSourceOpenParametersType): void {
// - Initialize `EventSource` (use any event source of your choice here)
const eventSource = new EventSource(url);
this.eventSource = eventSource;
// - Add event listener with provided event type and event callback
this.eventSource.addEventListener(eventType, onEvent);
}
public close(): void {
// - Clean up open event source
if (this.eventSource) {
this.eventSource.close();
}
}
public onError(callback: (error: Event) => void): void {
// - Set error callback
if (this.eventSource) {
this.eventSource.onerror = callback;
}
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
eventSource: new MyEventSource(),
},
});
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
// --- External EventSource implementation ---
// - Example uses dummy `EventSource` class
class MyEventSource {
eventSource;
open({ eventType, onEvent, url }) {
// - Initialize `EventSource` (use any event source of your choice here)
const eventSource = new EventSource(url);
this.eventSource = eventSource;
// - Add event listener with provided event type and event callback
this.eventSource.addEventListener(eventType, onEvent);
}
close() {
// - Cleanup open event source
if (this.eventSource) {
this.eventSource.close();
}
}
public onError(callback) {
// - Set error callback
if (this.eventSource) {
this.eventSource.onerror = callback;
}
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
eventSource: new MyEventSource(),
},
});
VisitorCodeManager
visitorCodeManager implementation for NodeJS/NextJS SSR:
import {
IExternalVisitorCodeManager,
SetDataParametersType,
GetDataParametersType,
KameleoonClient,
KameleoonUtils,
} from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses server `request` and `response`
class MyVisitorCodeManager implements IExternalVisitorCodeManager {
public getData({ request, key }: GetDataParametersType): string | null {
// - Get cookie from server request
const cookieString = request.headers.cookie;
// - Return `null` if no cookie was found
if (!cookieString) {
return null;
}
// - Parse cookie using the provided `key`
return KameleoonUtils.getCookieValue(cookieString, key);
}
public setData({
visitorCode,
response,
domain,
maxAge,
key,
path,
}: SetDataParametersType): void {
// - Set cookie to request using provided parameters
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
response.setHeader('Set-Cookie', resultCookie);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses server `request` and `response`
class MyVisitorCodeManager {
getData({ request, key }) {
// - Get cookie from server request
const cookieString = request.headers.cookie;
if (!cookieString) {
return null;
}
// - Return `null` if no cookie was found
if (!cookieString) {
return null;
}
// - Parse cookie using the provided `key`
return KameleoonUtils.getCookieValue(cookieString, key);
}
setData({ visitorCode, response, domain, maxAge, key, path }) {
// - Set cookie to request using provided parameters
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
response.setHeader('Set-Cookie', resultCookie);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
visitorCodeManager implementation for Deno:
import {
IExternalDenoVisitorCodeManager,
SetDenoDataParametersType,
GetDenoDataParametersType,
KameleoonClient,
KameleoonUtils,
} from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses server `request` and `response`
class MyVisitorCodeManager implements IExternalDenoVisitorCodeManager {
public getData({ request, key }: GetDenoDataParametersType): string | null {
// - Get cookie from server request
const cookieString = request.headers.get('cookie');
// - Return `null` if no cookie was found
if (!cookieString) {
return null;
}
// - Parse cookie using the provided `key`
return KameleoonUtils.getCookieValue(cookieString, key);
}
public setData({
visitorCode,
response,
domain,
maxAge,
key,
path,
}: SetDenoDataParametersType): void {
// - Set cookie to request using provided parameters
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
response.headers.set('Set-Cookie', resultCookie);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
import { KameleoonClient, KameleoonUtils } from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses server `request` and `response`
class MyVisitorCodeManager {
getData({ request, key }) {
// - Get cookie from server request
const cookieString = request.headers.get('cookie');
// - Return `null` if no cookie was found
if (!cookieString) {
return null;
}
// - Parse cookie finding it by provided `key`
return KameleoonUtils.getCookieValue(cookieString, key);
}
setData({ visitorCode, response, domain, maxAge, key, path }) {
// - Set cookie to request using provided parameters
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
response.headers.set('Set-Cookie', resultCookie);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
visitorCodeManager implementation for NextJS Server Actions:
import {
IExternalNextJSVisitorCodeManager,
SetNextJSDataParametersType,
GetNextJSDataParametersType,
KameleoonClient,
} from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses server `cookies` object imported from "next/headers"
class MyVisitorCodeManager implements IExternalNextJSVisitorCodeManager {
public getData({ cookies, key }: GetNextJSDataParametersType): string | null {
// - Get cookie from server request by provided `key`
const cookie = cookies().get(key);
if (cookie) {
return cookie.value;
}
// - Return `null` if no cookie was found
return null;
}
public setData({
visitorCode,
cookie,
domain,
maxAge,
key,
path,
}: SetNextJSDataParametersType): void {
// - Set cookie to request using provided parameters
cookies().set(key, visitorCode, {
path,
domain,
maxAge,
});
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses server `cookies` object imported from "next/headers"
class MyVisitorCodeManager {
public getData({ cookies, key }) {
// - Get cookie from server request by provided `key`
const cookie = cookies().get(key);
if (cookie) {
return cookie.value;
}
// - Return `null` if no cookie was found
return null;
}
public setData({
visitorCode,
cookie,
domain,
maxAge,
key,
path,
}){
// - Set cookie to request using provided parameters
cookies().set(key, visitorCode, {
path,
domain,
maxAge,
});
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
Custom visitorCodeManager implementation mit arbitrary parameters:
import {
IExternalCustomVisitorCodeManager,
SetDataCustomParametersType,
GetDataCustomParametersType,
KameleoonClient,
} from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses custom arbitrary `input` and `output` objects
class MyVisitorCodeManager implements IExternalCustomVisitorCodeManager {
public getData({ input, key }: GetDataCustomParametersType): string | null {
// - Get visitor code from `input` object
// `input` is of type `unknown`, so you can provide any structure.
// In Example, we assume `input` is a `Map` object.
const visitorCode = input.get(key);
if (visitorCode) {
return visitorCode;
}
// - Return `null` if no visitor code was found
return null;
}
public setData({
visitorCode,
output,
domain,
maxAge,
key,
path,
}: SetDataCustomParametersType): void {
// - Set visitor code as a cookie to `output` object using provided parameters.
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
// - `output` is of type `unknown`, so you can provide any structure.
// In Example, we assume `output` is a `Map` object.
output.set(key, resultCookie);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses custom arbitrary `input` and `output` objects.
class MyVisitorCodeManager {
public getData({ input, key }) {
// - Get visitor code from `input` object
// `input` is of type `unknown`, so you can provide any structure
// In Example, we assume `input` is a `Map` object.
const visitorCode = input.get(key);
if (visitorCode) {
return visitorCode;
}
// - Return `null` if no visitor code was found
return null;
}
public setData({
visitorCode,
output,
domain,
maxAge,
key,
path,
}) {
// - Set visitor code as a cookie to `output` object using provided parameters.
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
// - `output` is of type `unknown`, so you can provide any structure.
// In Example, we assume `output` is a `Map` object.
output.set(key, resultCookie);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
Requester
import {
RequestType,
IExternalRequester,
KameleoonResponseType,
SendRequestParametersType,
KameleoonClient,
} from '@kameleoon/nodejs-sdk';
// --- External Requester Implementation
export class MyRequester implements IExternalRequester {
public async sendRequest({
url,
parameters,
}: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
// - Using native NodeJS `fetch` (for v18+)
return await fetch(url, parameters);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
requester: new MyRequester(),
},
});
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
// --- External Requester Implementation
export class MyRequester {
async sendRequest({ url, parameters }) {
// - Using native NodeJS `fetch` (for v18+)
return await fetch(url, parameters);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
requester: new MyRequester(),
},
});
Utilities
The SDK has a set of utility Methoden that Sie können use to simplify development. All Methoden are represented as static members des KameleoonUtils class.
SDK Version 4
SDK Version 5
getClientConfigurationUrl
Verwenden Sie the getClientConfigurationUrl Methode to get the URL for fetching der Client configuration. Diese Methode is useful for handling edge cases when working mit Edge computing integrations.Diese Methode will soon be deprecated und replaced by custom Requester implementation. import { KameleoonUtils, Environment } from '@kameleoon/nodejs-sdk';
const url = KameleoonUtils.getClientConfigurationUrl(
'my_site_code',
Environment.Production,
'example.com',
);
import { KameleoonUtils, Environment } from '@kameleoon/nodejs-sdk';
const url = KameleoonUtils.getClientConfigurationUrl(
'my_site_code',
Environment.Production,
'example.com',
);
Arguments
| Name | Type | Description | Default |
|---|
| siteCode (required) | string | site code | - |
| environment (optional) | Environment | an optional parameter specifying the SDK environment | Environment.Production |
| networkDomain (optional) | string | an optional parameter specifying die Domain zum Beispiels using custom domains. Must be in form example.com | kameleoon.com |
Rückgabewert
| Type | Description |
|---|
string | gibt den URL for fetching der Client configuration |
simulateSuccessRequest
Verwenden Sie the simulateSuccessRequest Methode to simulate a successful request zum Kameleoon server. Diese Methode can be useful for custom Requester implementations wenn ein developer benötigt to simulate a successful request.
import {
KameleoonUtils,
IExternalRequester,
SendRequestParametersType,
RequestType,
KameleoonResponseType,
} from '@kameleoon/nodejs-sdk';
// - Example of `Requester` with disabled tracking
class Requester implements IExternalRequester {
public async sendRequest({
url,
parameters,
requestType,
}: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
if (requestType === RequestType.Tracking) {
return KameleoonUtils.simulateSuccessRequest<RequestType.Tracking>(
requestType,
null,
);
}
return await fetch(url, parameters);
}
}
import { KameleoonUtils } from '@kameleoon/nodejs-sdk';
// - Example of `Requester` with disabled tracking
class Requester {
async sendRequest({ url, parameters, requestType }) {
if (requestType === RequestType.Tracking) {
return KameleoonUtils.simulateSuccessRequest(requestType, null);
}
return await fetch(url, parameters);
}
}
Arguments
| Name | Type | Description |
|---|
| requestType (required) | RequestType | A type of request |
| data (required) | SimulateRequestDataType[RequestType] | A type of request data, which is different abhängig von RequestType |
The SimulateRequestDataType data type is defined wie folgt:
RequestType.Tracking - null
RequestType.ClientConfiguration - ClientConfigurationDataType
RequestType.RemoteData - JSONType
Rückgabewert
| Type | Description |
|---|
Promise<KameleoonResponseType> | gibt ein promise mit die Anfrage’s response |
getCookieValue
Verwenden Sie the getCookieValue Methode to parse a common cookie string (key_1=value_1; key_2=value_2; ...), und get der Wert eines specific cookie key. Diese Methode is useful when working mit einem custom implementation of VisitorCodeManager.
import { KameleoonUtils } from '@kameleoon/nodejs-sdk';
const cookies = 'key_1=value_1; key_2=value_2';
const key = 'key_1';
const value = KameleoonUtils.getCookieValue(cookies, key); // = `value_1`
import { KameleoonUtils } from '@kameleoon/nodejs-sdk';
const cookies = 'key_1=value_1; key_2=value_2';
const key = 'key_1';
const value = KameleoonUtils.getCookieValue(cookies, key); // = `value_1`
Arguments
| Name | Type | Description |
|---|
| cookie (required) | string | Cookie string in form key_1=value_1; key_2=value_2 |
| key (required) | string | String representation of ein Schlüssel to find ein Wert by |
Rückgabewert
| Type | Description | |
|---|
| `string | null` | gibt ein string mit einem cookie value, oder null wenn der key was not found |
Referenz
Dies ist the full reference documentation für den Kameleoon JavaScript SDK.
Initialisierung
initialize()
An asynchronous Methode for initializing KameleoonClient that retrieves Kameleoon SDK data either from der Server oder a local source wenn der data is still up-to-date oder der update interval has not yet elapsed.
import {
KameleoonError,
KameleoonClient,
KameleoonException,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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();
Rückgabewert
| Type | Description |
|---|
Promise<boolean> | A promise resolved zu einem boolean indicating the SDK’s successful initialization. Allgemein initialize() will throw ein Fehler wenn ein unhandled issue occurs, so the boolean value will almost always be true und may not provide much useful information. |
Ausgelöste Ausnahmen
| 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 |
Feature flags und variations
getVariation()
- 📨 Sends Tracking Data to Kameleoon (abhängig von the
track parameter)
Ruft den Variation assigned zu einem given visitor für ein specific feature flag.
Diese Methode nimmt featureKey as a mandatory argument und track as an optional argument. The track argument ist optional und defaults to true.
It gibt den assigned Variation for der Besucher. Wenn der visitor is not associated mit any feature flag Regeln, the Methode gibt den default Variation für den given feature flag.
Stellen Sie sicher, dass proper error handling is implemented in Ihr code to manage potential Ausnahmen.
The default variation refers to die variation assigned to ein Besucher when they nicht match any predefined delivery Regeln für ein feature flag. Mit anderen Worten, it is the fallback variation applied to all Benutzer who are not targeted by specific Regeln. It’s represented as die variation in dem “Then, for everyone else…” Abschnitt in einem management interface.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get variation with tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
});
// -- Get variation without tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
track: false,
});
// -- An Example variation:
// {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get variation with tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
});
// -- Get variation without tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
track: false,
});
// -- An Example variation:
// {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
}
init();
Arguments
An object of type GetVariationParamsType mit Folgendes properties:
| Name | Type | Description | Default |
|---|
| visitorCode (required) | string | Unique identifier of der Besucher. | |
| featureKey (required) | string | Key des feature you want to expose to ein Besucher. | |
| track (optional) | boolean | An optional parameter to enable oder disable tracking des feature evaluation. | true |
Rückgabewert
| Type | Description |
|---|
Variation | An assigned Variation zu einem given visitor für ein specific feature flag. |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty. |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters). |
KameleoonException.FeatureFlagConfigurationNotFound | Exception indicating that the requested feature key wasn’t found in dem internal configuration des SDK. This usually means that the feature flag is not activated in dem Kameleoon app (but code implementing the feature is already deployed in die Anwendung). |
KameleoonException.FeatureFlagEnvironmentDisabled | Exception indicating that feature flag ist deaktiviert for der Besucher’s current environment (zum Beispiel, production, staging, oder development). |
getVariations()
- 📨 Sends Tracking Data to Kameleoon (abhängig von the
track parameter)
- 🎯 Events:
EventType.Evaluation
Ruft ein map of Variation objects assigned zu einem given visitor across all feature flags.
Diese Methode iterates over all available feature flags und gibt den assigned Variation for each flag associated mit dem specified visitor. It takes visitorCode as a mandatory argument, while onlyActive und track are optional.
- If
onlyActive gesetzt ist to true, the Methode getVariations() will return feature flags variations provided der Benutzer is not bucketed mit dem off variation.
- The
track parameter controls whether oder not the Methode will track die variation assignments. Standardmäßig it gesetzt ist to true. If set to false, the tracking will be disabled.
The returned map consists of feature flag keys as keys und their corresponding Variation as Werte. If no variation is assigned für ein feature flag, the Methode gibt den default Variation for that flag.
Proper error handling should be implemented to manage potential Ausnahmen.
The default variation refers to die variation assigned to ein Besucher when they nicht match any predefined delivery Regeln für ein feature flag. Mit anderen Worten, it is the fallback variation applied to all Benutzer who are not targeted by specific Regeln. It’s represented as die variation in dem “Then, for everyone else…” Abschnitt in einem management interface.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get all feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
});
// -- Get active feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
});
// -- Get active feature flag variations without tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
track: false,
});
// -- An Example variations:
// Map {
// 'feature_key' => {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
// }
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get all feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
});
// -- Get active feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
});
// -- Get active feature flag variations without tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
track: false,
});
// -- An Example variations:
// Map {
// 'feature_key' => {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
// }
}
init();
Arguments
An object of type GetVariationsParamsType mit Folgendes properties:
| Name | Type | Description | Default |
|---|
| visitorCode (required) | string | Unique identifier of der Besucher. | |
| onlyActive (optional) | boolean | An optional parameter indicating whether to return variations for active (true) oder all (false) feature flags. | false |
| track (optional) | boolean | An optional parameter to enable oder disable tracking des feature evaluation. | true |
Rückgabewert
| Type | Description |
|---|
Map<string, Variation> | Map that enthält the assigned Variation objects des feature flags unter Verwendung der keys des corresponding features. |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty. |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters). |
isFeatureFlagActive()
- 📨 Sends Tracking Data to Kameleoon (abhängig von the
track parameter)
- 🎯 Events:
EventType.Evaluation
The isFeatureFlagActive() Methode gibt ein boolean indicating whether der Besucher mit visitorCode has an active featureKey. Diese Methode checks for targeting, finds die variation for der Besucher, und saves it to storage. The Methode also sends a tracking request.
Diese Methode has an additional overload that lets you pass a track parameter, which disables the tracking of feature evaluation.
A visitor must be targeted for feature flags to activate.
Kameleoon uses tracking to count Sessions und Besucher wenn Sie call certain methods, wie zum Beispiel isFeatureFlagActive(), getVariation() oder getVariations().Verwenden Sie the default true value für den track parameter wenn Sie expose Besucher to eine variation und need to count them. Setzen Sie the track parameter to false only wenn Sie call these Methoden bevor Sie expose Besucher.Zum Beispiel, wenn Sie call getVariations() to retrieve all variations bevor Sie expose Besucher, set the track parameter to false. Thgesetzt istting prevents Kameleoon from prematurely counting a session. Sie können then trigger tracking later wenn Sie explicitly expose der Besucher.Kameleoon sends tracking data every second by default. Sie können configure this interval up to five seconds unter Verwendung der tracking interval configuration option. Kameleoon groups tracking Ereignisse into a single session as long as the interval between Ereignisse is less than 30 minutes. If more than 30 minutes elapse between tracking Ereignisse, Kameleoon counts the Ereignisse as separate Sessions. A visit appears in Ihr reports 30 minutes nach dem last recorded event in die Session.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(visitorCode, new CustomData(0, 'visitor_id'));
// -- Check if the feature flag is active for visitor
const isActive = client.isFeatureFlagActive(visitorCode, 'my_feature_key');
// -- Check if the feature flag is active for visitor without tracking
const isActive = client.isFeatureFlagActive({ visitorCode, featureKey: 'my_feature_key', track: false});
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(visitorCode, new CustomData(0, 'visitor_id'));
// -- Check if the feature flag is active for visitor
const isActive = client.isFeatureFlagActive(visitorCode, 'my_feature_key');
// -- Check if the feature flag is active for visitor without tracking
const isActive = client.isFeatureFlagActive({ visitorCode, featureKey: 'my_feature_key', track: false});
}
init();
The isFeatureFlagActive() Methode evaluates the served variant, not the master flag state. Wenn Sie exclude Regeln, the Methode uses the Then, for everyone else serve default state. Wenn Sie select Off for this default state, the Methode always returns false even wenn der master feature flag is On.
Arguments
There are two overloads available for this method:
- Two parameters overload:
This overload is deprecated und will be removed in dem next major version. Please use the new overload mit ein Objekt parameter.
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters length |
| featureKey (required) | string | a unique key for feature flag |
- Object parameter overload of type
IsFeatureFlagActiveParamsType:
| Name | Type | Description | Default |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length | - |
| featureKey (required) | string | a unique key für ein feature flag | - |
| track (optional) | boolean | a boolean indicator of whether to track the feature evaluation | true |
Rückgabewert
| Type | Description |
|---|
boolean | a boolean indicator of whether the feature flag mit featureKey is active for der Besucher mit visitorCode |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey |
KameleoonException.FeatureFlagVariableNotFound | No feature variable were found for provided visitorCode und variableKey |
KameleoonException.DataInconsistency | Allocated variation was found, aber there is no feature flag mit dem according featureKey. |
setForcedVariation()
The Methode ermöglicht you to programmatically assign a specific Variation to ein Benutzer, bypassing the standard evaluation process. Dies ist especially valuable for controlled Experiments where the usual evaluation logic is not required oder must be skipped. It can also be helpful in scenarios like debugging oder custom testing.
Wenn ein forced variation gesetzt ist, it overrides Kameleoon’s real-time evaluation logic. Processes like segmentation, Targeting-Bedingungs, und algorithmic calculations are skipped. To preserve segmentation und Targeting-Bedingungs during ein Experiment, set forceTargeting=false instead.
Simulated variations always take precedence in dem execution order. Wenn ein simulated variation calculation is triggered, it will be fully processed und completed first.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics und stored in der Benutzer context like any standard evaluated variation, ensuring consistency in reporting.
The Methode may throw Ausnahmen under certain conditions (e.g., invalid parameters, user context, oder internal issues). Proper exception handling is essential to ensure that Ihr application remains stable und resilient.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are specific zu einem individual experiment.
- Simulated variations: Affect the overall feature flag result.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Forcing the variation "on" for the "featureKey1" feature flag for the visitor.
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: 'on',
forceTargeting: false,
});
// -- Resetting the forced variation for the "featureKey1" feature flag for the visitor.
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: null,
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Forcing the variation "on" for the "featureKey1" feature flag for the visitor.
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: 'on',
forceTargeting: false,
});
// -- Resetting the forced variation for the "featureKey1" feature flag for the visitor.
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: null,
});
}
init();
Arguments
An object of type SetForcedVariationParametersType mit Folgendes properties:
| Name | Type | Description | Default | |
|---|
| visitorCode (required) | string | Unique identifier of der Besucher. | | |
| experimentId (required) | number | Experiment Id that will be targeted und selected während des evaluation process. | | |
| variationKey (required) | `string | null` | Variation Key corresponding zu einem Variation that should be forced as the returned value for das Experiment. Wenn der value is null, the forced variation will be reset. | |
| forceTargeting (optional) | boolean | Indicates whether targeting for das Experiment should be forced und skipped (true) oder applied as in dem standard evaluation process (false). | true | |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty. |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters). |
KameleoonException.Initialization | Indicates that the SDK is not yet fully initialized. |
KameleoonException.FeatureFlagExperimentNotFound | Exception indicating that the requested experiment id has not been found in dem SDK’s internal configuration. Dies ist usually normal und means that die Regel’s corresponding experiment has not yet been activated on Kameleoon’s side. |
KameleoonException.FeatureFlagVariationNotFound | Exception indicating that the requested variation key(id) has not been found in dem internal configuration des SDK. Dies ist usually normal und means that die variation’s corresponding experiment has not yet been activated on Kameleoon’s side. |
KameleoonException.StorageRead | Couldn’t read storage data. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
In den meisten Fällen only the basic error, KameleoonException, benötigt to be handled, as demonstrated in dem example. Allerdings if different types of Fehler require a response, handle each one separately basierend auf specific requirements. Zusätzlich for enhanced reliability, general language Fehler can be handled by including Error.
evaluateAudiences()
- 📨 Sends Tracking Data to Kameleoon
Diese Methode evaluates Besucher against all available Audiences Explorer Segmente und tracks those who match.
evaluateAudiences() sollte aufgerufen werden after all relevant visitor data wurde gesetzt oder updated, und just before getting a feature variation oder checking a feature flag. This approach ensures that der Besucher is evaluated against the most current data available, allowing for accurate audience assignment basierend auf einemll criteria.
After calling this Methode, Sie können perform a detailed analysis of segment performance in Audiences Explorer.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
client.evaluateAudiences(visitorCode);
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
client.evaluateAudiences(visitorCode);
}
init();
Arguments
| Name | Type | Description |
|---|
| visitorCode (required) | string | Unique identifier of der Besucher. |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty. |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters). |
In den meisten Fällen only the basic error, KameleoonException, benötigt to be handled, as demonstrated in dem example. Allerdings if different types of Fehler require a response, handle each one separately basierend auf specific requirements. Zusätzlich for enhanced reliability, general language Fehler can be handled by including Error.
getDataFile()
To evaluate all feature flags, use getVariations(). Diese Methode is more efficient than calling DataFile und iterating through flags mit getVariation().
Gibt den current SDK configuration as a DataFile object.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
const dataFile = client.getDataFile();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
const dataFile = client.getDataFile();
Rückgabewert
| Type | Description |
|---|
DataFile | The DataFile containing the SDK configuration |
Besucherdaten
getVisitorCode()
The getVisitorCode Methode ruft ein Besuchercode from die Anfrage’s cookie in dem headers. If den Besuchercode nicht exist, the Methode generates a new random Besuchercode, oder uses a provided defaultVisitorCode value. It then sets the new Besuchercode in einem cookie in die Antwort headers.
Diese Methode utilizes Node.js’s native types for request und response, specifically IncomingMessage und ServerResponse, imported aus dem http module. Allerdings if you’re unter Verwendung der Express framework, Deno, oder Next.js super server-rendering methods, like getServerProps, the types for request und response will differ. Sie können resolve this issue using type casting, which will yield identical results.
When using getVisitorCode() mit Deno, Next.js SSR, Node, oder Express, ensure that you’ve implemented the correct externe Abhängigkeiten.
The getVisitorCode() Methode ermöglicht you to set simulated variations for ein Besucher. When Cookies (from a request oder document) contain der Schlüssel kameleoonSimulationFFData, the standard evaluation process is bypassed. Stattdessen the Methode directly gibt ein Variation basierend auf dem provided data.Sie können apply simulations in two ways:
- Automatically (recommended): If using Kameleoon Web Experimentation oder der SDK in Hybrid mode, das Cookie is created automatically when simulating a variant’s display unter Verwendung der Simulation Panel.
- Manually: Setzen Sie the
kameleoonSimulationFFData cookie manually.
It’s important to distinguish simulated variations from forced variations:
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific zu einem individual experiment.
⚙️ Manual setupPlease ensure the kameleoonSimulationFFData cookie follows this format:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates die variation mit varId of experiment expId für den given featureKey.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined in dem Then, for everyone else in Production, serve Abschnitt) für den given featureKey.
⚠️ To ensure proper functionality, das Cookie value must be encoded as a URI component using a Methode wie zum Beispiel encodeURIComponent.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using native `NodeJS/NextJS/Deno` `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get visitor code using `Express`/`Deno`/`NextJS` SSR methods' `request`, `response`, and optionally providing
// default visitor code
const visitorCode = client.getVisitorCode({
request: req,
response: res,
defaultVisitorCode: 'my_default_visitor_code',
});
// -- Get visitor code using `NextJS` server side actions
// (`cookies` imported from "next/headers")
const visitorCode = client.getVisitorCode({
cookies,
});
// -- Get visitor code using custom `VisitorCodeManager` implementation
// `myInput` and `myOutput` are custom input and output parameters with arbitrary types.
// According types should be defined in `VisitorCodeManager` implementation.
const visitorCode = client.getVisitorCode({
input: myInput,
output: myOutput,
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using native `NodeJS` `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get visitor code using `Express`/`Deno`/`NextJS SSR methods`, and optionally providing
// default visitor code
const visitorCode = client.getVisitorCode({
request: req,
response: res,
defaultVisitorCode: 'my_default_visitor_code',
});
// -- Get visitor code using `NextJS` server side actions
// (`cookies` imported from "next/headers")
const visitorCode = client.getVisitorCode({
cookies,
});
// -- Get visitor code using custom `VisitorCodeManager` implementation
// `myInput` and `myOutput` are custom input and output parameters with arbitrary types.
// According types should be defined in `VisitorCodeManager` implementation.
const visitorCode = client.getVisitorCode({
input: myInput,
output: myOutput,
});
}
init();
Arguments
The parameters object is overloaded mit two types:
- Type
GetVisitorCodeParametersType (for NodeJS/Express/NextJS SSR methods), containing Folgendes fields:
| Name | Type | Description |
|---|
| request (required) | IncomingMessage | server request |
| response (required) | ServerResponse | server response |
| defaultVisitorCode (optional) | string | Besuchercode to be used if is no Besuchercode in dem Cookies |
- Type
GetNextJSVisitorCodeParametersType (for NextJS SSR server actions), containing Folgendes fields:
| Name | Type | Description |
|---|
| Cookies (required) | typeof 'next/headers' cookies | NextJS server actions headers cookie |
| defaultVisitorCode (optional) | string | Besuchercode to be used if is no Besuchercode available in dem Cookies |
- Type
GetDenoVisitorCodeParametersType (for Deno), containing Folgendes fields:
| Name | Type | Description |
|---|
| request (required) | DenoMessage | server request |
| response (required) | DenoMessage | server response |
| defaultVisitorCode (optional) | string | default Besuchercode that the SDK uses when there is no Besuchercode in dem Cookies |
- Type
GetCustomVisitorCodeParametersType (for custom VisitorCodeManager implementation), containing Folgendes fields:
| Name | Type | Description |
|---|
| input (required) | unknown | arbitrary input object from which you want to read den Besuchercode |
| output (required) | unknown | arbitrary output object to which you want to write den Besuchercode |
| defaultVisitorCode (optional) | string | Besuchercode to be used in case there is no Besuchercode in dem Cookies |
Wenn Sie don’t provide a defaultVisitorCode und there is no Besuchercode stored in einem cookie, den Besuchercode will be randomly generated.
Rückgabewert
| Type | Description |
|---|
string | result Besuchercode |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
KameleoonException.VisitorCodeMaxLength | The maximum Besuchercode length was exceeded (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
addData()
Verwenden Sie the addData() Methode to add targeting data to storage so other Methoden can utilize this information to determine whether to target the current visitor.
The addData() Methode nicht return any value, und nicht directly interact mit dem Kameleoon back-end servers. Stattdessen all data the Methode collects is saved for future transmission unter Verwendung der flush() Methode. This approach minimizes die Zahl of server calls, as data is generally grouped into a single server call that is activated durch den flush() Methode.
Zusätzlich the trackConversion() Methode transmits any previously associated data. The getFeatureFlagVariationKey() und getFeatureFlagVariable() Methoden transmit data wenn ein experimentation rule is triggered.
Each visitor can only have one instance of associated data for most data types; however, CustomData is an exception, as Besucher can have one instance of associated CustomData for each customDataIndex.
import {
KameleoonClient,
BrowserType,
CustomData,
Browser,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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 a single data item (tracked by default)
client.addData('my_visitor_code', browserData);
// -- Add multiple data items (tracked by default)
client.addData('my_visitor_code', browserData, customData);
// -- Add multiple data items from array (tracked by default)
const dataArr = [browserData, customData];
client.addData('my_visitor_code', ...dataArr);
// -- Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
client.addData({visitorCode: 'my_visitor_code', track: false, data: dataArr});
}
init();
import {
KameleoonClient,
BrowserType,
CustomData,
Browser,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Create Kameleoon Data Types
const browserData = new Browser(BrowserType.Chrome);
const customData = new CustomData(0, 'my_data');
// -- Add a single data item (tracked by default)
client.addData('my_visitor_code', browserData);
// -- Add multiple data items (tracked by default)
client.addData('my_visitor_code', browserData, customData);
// -- Add multiple data items from array (tracked by default)
const dataArr = [browserData, customData];
client.addData('my_visitor_code', ...dataArr);
// -- Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
client.addData({visitorCode: 'my_visitor_code', track: false, data: dataArr});
}
init();
Arguments
| Name | Type | Description | Default value |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters. | |
| track (optional) | boolean | Specifies whether the added data is eligible for tracking. When set to false, the data is stored locally und used only for targeting evaluation; it is not sent zum Kameleoon Data API. | true |
| kameleoonData (optional) | KameleoonDataType[] | number of instances of any type of KameleoonData, can be added solely in array oder as sequential arguments | |
-
kameleoonData is a variadic argument: it kann übergeben werden as one oder several arguments (see the example).
-
The custom data’s index oder ID can be found in Ihr Kameleoon account. Beachten Sie, dass this index starts at
0, meaning the first custom data you create für ein given site will be assigned 0 as its ID, rather than 1.
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.StorageWrite | Couldn’t update storage data |
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
Check the data types reference for more details on how to manage different data types.
flush()
SDK Version 4
SDK Version 5
The flush() Methode takes the Kameleoon data associated mit ein Besucher und sends a data tracking request zusammen mit all previously added data unter Verwendung der addData() Methode.The SDK will send all of its stored data zum remote Kameleoon servers wenn Sie don’t specify a visitorCode. Zusätzlich if there were any tracking Anfragen that previously failed und were stored locally in offline mode, the SDK will attempt to send those stored Anfragen before processing the latest request.The isUniqueIdentifier parameter can be beneficial in certain edge cases. Zum Beispiel, if Sie können’t access the anonymous visitorCode initially assigned to ein Besucher aber have an internal ID linked through session merging, this parameter is useful.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Flush data for all the visitors
client.flush();
// -- Flush data with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.flush(internalUserId, true);
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Flush data for all the visitors
client.flush();
// -- Flush data with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.flush(internalUserId, true);
}
init();
Arguments
| Name | Type | Description | Default |
|---|
| visitorCode (optional) | string | unique visitor identification string, can’t exceed 255 characters in length, falls nicht passed, all data will be flushed (sent zum remote Kameleoon servers) | - |
| isUniqueIdentifier (optional) | boolean | an optional parameter for specifying wenn der visitorCode is a unique identifier | false |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
flush() takes the Kameleoon data associated mit der Besucher und schedules the data to be sent mit dem next tracking request. The time des next tracking request is defined in dem SDK Configuration’s trackingInterval parameter. Sie können add visitor data unter Verwendung der addData() und getRemoteVisitorData() Methoden.The SDK will send all of its stored data zum remote Kameleoon servers wenn Sie don’t specify a visitorCode. Zusätzlich if there were any tracking Anfragen that previously failed und were stored locally in offline mode, the SDK will attempt to send those stored Anfragen before processing the latest request.If Sie müssen send tracking Anfragen immediately, use flushInstant() — the asynchronous version of flush that returns Promise<void>. Sie können await it wenn Sie need delivery guarantees (zum Beispiel, before ending eine Anfrage/response cycle), oder call it ohne await as a fire-and-forget request:
await client.flushInstant(visitorCode) sends tracking Anfragen immediately für ein specific visitor und waits for completion
await client.flushInstant() sends tracking Anfragen immediately for all Besucher und waits for completion
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Instantly flush added custom data for visitor
client.flush({ visitorCode, instant: true });
// -- Flush data for all the visitors
client.flush();
// -- Instantly flush data for all the visitors
client.flush({ instant: true });
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Instantly flush added custom data for visitor (fire-and-forget)
client.flushInstant(visitorCode);
// -- Instantly flush added custom data for visitor and wait for completion
await client.flushInstant(visitorCode);
// -- Flush data for all the visitors
client.flush();
// -- Instantly flush data for all the visitors (fire-and-forget)
client.flushInstant();
// -- Instantly flush data for all the visitors and wait for complention
await client.flushInstant();
}
init();
Arguments
| Name | Type | Description | Default |
|---|
| visitorCode (optional) | string | unique visitor identification string, can’t exceed 255 characters, falls nicht passed, all data will be flushed (sent zum remote Kameleoon servers). | - |
Or ein Objekt mit der Typ FlushParamsType, containing:| Name | Type | Description | Default |
|---|
| visitorCode (optional) | string | unique visitor identification string, can’t exceed 255 characters, falls nicht passed, all data will be flushed (sent zum remote Kameleoon servers). | - |
| instant (optional) | boolean | Boolean flag indicating whether the data should be sent instantly (true) oder gemäß the scheduled tracking interval (false). | - |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
getRemoteData()
The getRemoteData() Methode retrieves data that is stored auf einem remote Kameleoon server für ein specified site code.
For instance, Sie können use this Methode to access user preferences, historical data, oder any other information pertinent to Ihr application’s logic. By storing this data on our highly scalable servers using our Data API, Sie können efficiently manage large volumes of data und retrieve it for each of Ihr Besucher oder Benutzer.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get remote data
const jsonData = await getRemoteData('my_data_key');
const data = JSON.parse(jsonData);
}
init();
Arguments
| Name | Type | Description |
|---|
| key (required) | string | the unique key mit which the retrieved data is associated |
Rückgabewert
| Type | Description |
|---|
JSONType | promise mit data retrieved for specific key |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
getRemoteVisitorData()
SDK Version 4
SDK Version 5
getRemoteVisitorData() is an asynchronous Methode that retrieves Kameleoon Visits Data für ein specific visitorCode aus dem Kameleoon Data API. Diese Methode stores the data for use by other Methoden when making targeting decisions.The data obtained using this Methode is essential for certain scenarios, including:
- Utilizing data collected from multiple devices.
- Accessing ein Benutzer’s history, including visited pages during prior visits.
- Using client-side data, wie zum Beispiel datalayer variables und Ziele that only convert auf dem front end.
For a clearer understanding des potential use cases, read this article.Standardmäßig getRemoteVisitorData() ruft den latest stored custom data mit scope=Visitor und attaches it to der Besucher, eliminating the need to call the Methode addData(). This feature is especially useful for synchronizing custom data between multiple devices. The isUniqueIdentifier parameter can be beneficial in certain edge cases. Zum Beispiel, if Sie können’t access the anonymous visitorCode initially assigned to ein Besucher aber have an internal ID linked through session merging, this parameter is useful.
import {
KameleoonClient,
KameleoonDataType,
VisitorDataFiltersType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get remote visitor data and add it to storage.
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage.
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data.
const filters: VisitorDataFiltersType = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get remote visitor data and add it to storage.
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage.
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data.
const filters = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
Arguments
An object mit der Typ RemoteVisitorDataParamsType containing:| Name | Type | Description | Default Value |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length | - |
| shouldAddData (optional) | boolean | boolean flag identifying whether the retrieved data should be added to storage automatically (without calling addData() afterwards). | true |
| filters (optional) | VisitorDataFiltersType | filters for specifying what data should be retrieved from visits, by default, only customData is retrieved aus dem current und latest previous visit | { previousVisitAmount: 1, currentVisit: true customData: true }, other filters parameters are set to false |
| isUniqueIdentifier (optional) | boolean | optional parameter that, when true, specifies the visitorCode as a unique identifier | false |
Rückgabewert
| Type | Description |
|---|
KameleoonDataType[] | promise mit list of Kameleoon Data retrieved |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
KameleoonException.VisitAmount | Besuchen Sie amount muss ein number between 1 und 25 |
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
Using parameters in getRemoteVisitorData()
The getRemoteVisitorData() Methode bietet flexibility by letting you define various parameters when retrieving visitor data. Diese Methode can target data basierend auf Ziele, Experiments, oder variations, und der same approach applies to all data types.Zum Beispiel, wenn Sie want to retrieve data on Besucher who completed das Ziel “Order transaction,” Sie können specify parameters in dem getRemoteVisitorData() Methode to refine Ihr targeting. If you’re interested in Benutzer who converted on das Ziel during their last five visits, Sie können set the previousVisitAmount parameter to 5 und conversions to true.The flexibility shown in this example is not limited to goal data. Sie können parameters innerhalb des getRemoteVisitorData() Methode to retrieve data auf einem variety of visitor behaviors.Here is die Liste of available VisitorDataFiltersType filters:| Name | Type | Description | Default |
|---|
| previousVisitAmount (optional) | number | Number of previous visits from which to retrieve data. Number between 1 und 25 | 1 |
| currentVisit (optional) | boolean | If true, current visit data will be retrieved | true |
| customData (optional) | boolean | If true, custom data will be retrieved. | true |
| pageViews (optional) | boolean | If true, page data will be retrieved. | false |
| geolocation (optional) | boolean | If true, geolocation data will be retrieved. | false |
| device (optional) | boolean | If true, device data will be retrieved. | false |
| browser (optional) | boolean | If true, browser data will be retrieved. | false |
| operatingSystem (optional) | boolean | If true, operating system data will be retrieved. | false |
| Conversions (optional) | boolean | If true, Conversion data will be retrieved. | false |
| Experiments (optional) | boolean | If true, experiment data will be retrieved. | false |
| kcs (optional) | boolean | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on. | false |
The getRemoteVisitorData() Methode is an asynchronous function that retrieves Kameleoon Visits Data für ein specific visitorCode aus dem Kameleoon Data API. Diese Methode stores the data so that it can be accessed when making targeting decisions.The data obtained through this Methode is crucial wenn Sie want to:
- Access data collected from multiple devices.
- Review ein Benutzer’s history, including pages visited during previous Sessions.
- Utilize client-side data, wie zum Beispiel data layer variables und Ziele that are only applicable auf dem front end.
For a better understanding of potential use cases, please read this article.Standardmäßig getRemoteVisitorData() ruft den latest stored custom data mit scope=Visitor und attaches it to der Besucher ohne den need to call the Methode addData(). This feature is particularly useful for synchronizing custom data across multiple devices. import {
KameleoonClient,
KameleoonDataType,
VisitorDataFiltersType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get remote visitor data and add it to storage.
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage.
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data.
const filters: VisitorDataFiltersType = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get remote visitor data and add it to storage.
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage.
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data.
const filters = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
Arguments
An object mit der Typ RemoteVisitorDataParamsType, containing:| Name | Type | Description | Default Value |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length | - |
| shouldAddData (optional) | boolean | boolean flag identifying whether the retrieved custom data should be added to storage automatically (without calling addData afterwards) | true |
| filters (optional) | VisitorDataFiltersType | filters for specifying what data should be retrieved from visits, by default, only customData is retrieved aus dem current und latest previous visit | { previousVisitAmount: 1, currentVisit: true customData: true }, other filters parameters are set to false |
Rückgabewert
| Type | Description |
|---|
KameleoonDataType[] | promise mit list of Kameleoon Data retrieved |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
KameleoonException.VisitAmount | Besuchen Sie amount muss ein number between 1 und 25 |
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
Using parameters in getRemoteVisitorData()
The getRemoteVisitorData() Methode bietet flexibility by letting you define various parameters when retrieving visitor data. Diese Methode can target data basierend auf Ziele, Experiments, oder variations, und der same approach applies to all data types.Zum Beispiel, wenn Sie want to retrieve data on Besucher who completed das Ziel “Order transaction,” Sie können specify parameters in dem getRemoteVisitorData() Methode to refine Ihr targeting. If you’re interested in Benutzer who converted on das Ziel during their last five visits, Sie können set the previousVisitAmount parameter to 5 und conversions to true.The flexibility shown in this example is not limited to goal data. Sie können parameters innerhalb des getRemoteVisitorData() Methode to retrieve data auf einem variety of visitor behaviors.Here is die Liste of available VisitorDataFiltersType filters:| Name | Type | Description | Default |
|---|
| previousVisitAmount (optional) | number | Number of previous visits from which to retrieve data. Number between 1 und 25 | 1 |
| currentVisit (optional) | boolean | If true, current visit data will be retrieved | true |
| customData (optional) | boolean | If true, custom data will be retrieved. | true |
| pageViews (optional) | boolean | If true, page data will be retrieved. | false |
| geolocation (optional) | boolean | If true, geolocation data will be retrieved. | false |
| device (optional) | boolean | If true, device data will be retrieved. | false |
| browser (optional) | boolean | If true, browser data will be retrieved. | false |
| operatingSystem (optional) | boolean | If true, operating system data will be retrieved. | false |
| Conversions (optional) | boolean | If true, Conversion data will be retrieved. | false |
| Experiments (optional) | boolean | If true, experiment data will be retrieved. | false |
| kcs (optional) | boolean | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on. | false |
| visitorCode (optional) | boolean | If true, Kameleoon will retrieve the visitorCode aus dem most recent visit und use it für den current visit. This retrieval is necessary wenn Sie want to ensure that der Besucher, identified by their visitorCode, always receives the same variation across visits for Geräteübergreifende Experimentierung. | true |
| personalization (optional) | boolean | If true, personalization data will be retrieved. Dies ist erforderlich für den personalization condition | false |
| cbs (optional) | boolean | If true, Contextual Bandit score data will be retrieved. | false |
getVisitorWarehouseAudience()
The getVisitorWarehouseAudience Methode is asynchronous und ruft einll audience data related to ein Besucher from Ihr data warehouse. To use this Methode, you’ll need to provide a visitorCode und a warehouseKey, which typically correspond to Ihr internal user ID. The customDataIndex parameter refers zum custom data Kameleoon uses to target Ihr Besucher. Weitere Details, siehe the warehouse targeting documentation.
import {
KameleoonClient,
KameleoonDataType,
CustomData,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor warehouse audience data using `warehouseKey`
// and add it to storage.
const customData: CustomData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
warehouseKey: 'my_key',
});
// -- Get visitor warehouse audience data using `visitorCode`
// and add it to storage.
const customData: CustomData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor warehouse audience data using `warehouseKey`
// and add it to storage.
const customData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
warehouseKey: 'my_key',
});
// -- Get visitor warehouse audience data using `visitorCode`
// and add it to storage.
const customData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
});
}
init();
Arguments
Parameters object consisting of:
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length |
| customDataIndex (required) | number | number representing the custom data’s index you want to use to target Ihr Warehouse Audiences |
| warehouseKey (optional) | string | unique key identifying the warehouse data (usually Ihr internal user ID) |
Rückgabewert
| Type | Description |
|---|
Promise<CustomData | null> | promise containing CustomData mit dem associated warehouse data, oder null if there was no data |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
setLegalConsent()
When handling legal consent, it’s important you use the getVisitorCode Methode aus dem KameleoonClient class, rather than the deprecated Methode from KameleoonUtils. Beachten Sie, dass this Methode nicht require the domain as an argument. Stattdessen Sie sollten pass the domain zum KameleoonClient constructor. Siehe the example above for clarification.
The Methode setLegalConsent determines whether ein Besucher has provided legal consent for their personal data’s use. Wenn Sie set the legalConsent parameter to false, it restricts the types of data Sie können include in tracking Anfragen. This measure ensures that you comply mit legal und regulatory requirements while responsibly managing visitor data. Weitere Informationen on personal data, siehe the consent management policy.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init(): Promise<void> {
await client.initialize();
const visitorCode = client.getVisitorCode();
client.setLegalConsent({
visitorCode,
consent: true,
response, // or cookies or output, depending on the environment
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init() {
await client.initialize();
const visitorCode = client.getVisitorCode();
client.setLegalConsent({
visitorCode,
consent: true,
response, // or cookies or output, depending on the environment
});
}
init();
Arguments
The parameters object is overloaded mit Folgendes types:
- Type
SetLegalConsentParametersType (for NodeJS/Express/NextJS SSR methods), containing Folgendes fields:
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string. Can’t exceed 255 characters in length |
| consent (required) | boolean | a boolean value representing the legal consent status. true indicates der Besucher has given legal consent, false indicates der Besucher has never provided oder withdrawn legal consent |
| response (required) | ServerResponse | server response |
- Type
SetNextJSLegalConsentParametersType (for NextJS SSR server actions), containing Folgendes fields:
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string. Can’t exceed 255 characters in length |
| consent (required) | boolean | a boolean value representing the legal consent status. true indicates der Besucher has given legal consent, false indicates der Besucher has never provided oder withdrawn legal consent |
| Cookies (required) | typeof 'next/headers' cookies | NextJS server actions headers cookie |
- Type
SetDenoLegalConsentParametersType (for Deno), containing Folgendes fields:
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string. Can’t exceed 255 characters in length |
| consent (required) | boolean | a boolean value representing the legal consent status. true indicates der Besucher has given legal consent, false indicates der Besucher has never provided oder withdrawn legal consent |
| response (required) | DenoMessage | server response |
- Type
SetCustomLegalConsentParametersType (for custom VisitorCodeManager implementation), containing Folgendes fields:
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string. Can’t exceed 255 characters in length |
| consent (required) | boolean | a boolean value representing the legal consent status. true indicates der Besucher has given legal consent, false indicates der Besucher has never provided oder withdrawn legal consent |
| output (required) | unknown | arbitrary output object to which you want to write den Besuchercode |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode length exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
Verhalten bei Widerruf der Einwilligung
Wenn Sie call setLegalConsent() mit consent=false, the SDK nicht delete the kameleoonVisitorCode cookie. Stattdessen it stops extending das Cookie’s expiration date, allowing das Cookie to persist until it naturally expires.
If Ihr compliance requirements demand the immediate removal of das Cookie file upon opt-out, Sie müssen delete it manually using Ihr framework’s native cookie management Methoden. The SDK will not remove die Datei automatically.
Goals und Drittanbieter-Analysen
trackConversion()
SDK Version 4
SDK Version 5
- _📨 Sends Tracking Data to Kameleoon
Verwenden Sie this Methode to track a Conversion für ein specific goal und user. Diese Methode erfordert visitorCode und goalId. Darüber hinaus this Methode also accepts an optional revenue argument. The visitorCode is usually identical zum one that was used when triggering das Experiment.The trackConversion() Methode doesn’t return any value. Diese Methode is non-blocking as der Server call is made asynchronously.Wenn Sie specify a visitorCode und set isUniqueIdentifier to true, the trackConversion() Methode uses it as the unique visitor identifier, which is useful for cross-device experimentation because the SDK links the flushed data mit der Besucher that is associated mit dem specified identifier.The isUniqueIdentifier can also be useful in other edge-case scenarios, wie zum Beispiel when Sie können’t access the anonymous visitorCode that was originally assigned to der Besucher, aber you do have access zu einem internal ID that is connected zum anonymous visitor using session merging capabilities.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
// -- Track conversion with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.trackConversion({
visitorCode: internalUserId,
revenue: 20000,
goalId: 123,
isUniqueIdentifier: true,
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
// -- Track conversion with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.trackConversion({
visitorCode: internalUserId,
revenue: 20000,
goalId: 123,
isUniqueIdentifier: true,
});
}
init();
Arguments
Parameters object consisting of:| Name | Type | Description | Default |
|---|
| visitorCode (required) | string | Unique identifier of der Besucher. | |
| goalId (required) | number | ID of das Ziel. | |
| revenue (optional) | number | Revenue des Conversion. | 0 |
| isUniqueIdentifier (optional) | boolean | An optional parameter for specifying wenn der visitorCode is a unique identifier. | false |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
- 📨 Sends Tracking Data to Kameleoon
Verwenden Sie this Methode to track a Conversion für ein specific goal und user. Diese Methode erfordert visitorCode und goalId. Darüber hinaus this Methode also accepts an optional revenue, negative und metadata arguments. The visitorCode is usually identical zum one that was used when triggering das Experiment.The trackConversion() Methode doesn’t return any value. Diese Methode is non-blocking as der Server call is made asynchronously.import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Track conversion
client.trackConversion({
visitorCode,
revenue: 20000,
goalId: 123,
metadata: [new CustomData(0, 'value')],
negative: true,
});
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Track conversion
client.trackConversion({
visitorCode,
revenue: 20000,
goalId: 123,
metadata: [new CustomData(0, 'value')],
negative: true,
});
}
init();
Arguments
Parameters object consisting of:| Name | Type | Description | Default |
|---|
| visitorCode (required) | string | Unique identifier of der Besucher. | |
| goalId (required) | number | ID of das Ziel. | |
| negative (optional) | boolean | Defines wenn der revenue is positive oder negative. | false |
| revenue (optional) | number | Revenue des Conversion. | 0 |
| metadata (optional) | CustomData[] | Metadata des Conversion. Must be defined beforehand in dem Kameleoon App. | undefined |
metadata Werte are accessible through raw data exports und the results page.Wenn der metadata parameter is provided, Kameleoon will use these specified Werte für den current Conversion instead of what was previously collected unter Verwendung der addData() Methode. Wenn der parameter is omitted, Kameleoon will use the last tracked Werte for those CustomData prior zum Conversion und innerhalb des same visit.Kameleoon will only consider the metadata Werte that are explicitly passed as parameters zum trackConversion() Methode.In the example below, Kameleoon will associate the Conversion only mit dem custom data value explicitly provided as ein Parameter (here: index 5 mit der Wert ‘Amex Credit Card’).kameleoonClient.addData(visitorCode, new CustomData(5, 'Credit Card'), new CustomData(9, 'Express Delivery'));
kameleoonClient.trackConversion({
visitorCode,
goalId: 1000,
metadata: [new CustomData(5, 'Amex Credit Card')]
});
kameleoonClient.addData(visitorCode, new CustomData(5, 'Credit Card'), new CustomData(9, 'Express Delivery'));
kameleoonClient.trackConversion({
visitorCode,
goalId: 1000,
metadata: [new CustomData(5, 'Amex Credit Card')]
});
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
getEngineTrackingCode()
Kameleoon integrates mit several analytics solutions, including Mixpanel, Google Analytics 4, und Segment. To track server-side Experiments correctly, call the getEngineTrackingCode() Methode nach dem visitor triggers ein Experiment. The SDK returns JavaScript queue commands für den Experiments that der Besucher triggered während des previous five seconds. Wenn Sie insert this code into die Seite, Engine.js processes the commands und sends the exposure Ereignisse durch den active analytics integration.
Siehe hybrid experimentation for more information on implementing this Methode.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Trigger feature experiment
// -- E.g., result `variationKey` id is `200`, and implicit experiment id is `100`
client.getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
// -- 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, true]);
// window.kameleoonQueue.push(['Experiments.trigger', 100, true]);
// `
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Trigger feature experiment
// -- E.g., result `variationKey` id is `200`, and implicit experiment id is `100`
client.getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
// -- 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, true]);
// window.kameleoonQueue.push(['Experiments.trigger', 100, true]);
// `
}
init();
-
To use this feature, implement both the NodeJS SDK und Kameleoon Engine.js. Because Engine.js verwendet wird only for tracking in this flow, Sie können install the asynchronous tag vor dem closing
</body> tag.
-
Sie können insert the returned tracking code directly into an HTML
<script> tag.
<html lang="en">
<body>
<script>
const engineTrackingCode = `
window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
`;
const script = document.createElement('script');
script.textContent = engineTrackingCode;
document.body.appendChild(script);
</script>
</body>
</html>
In diesem Beispiel 123456 und 234567 are experiment IDs, und 7890 und 8901 are variation IDs. In Ihr implementation, the SDK generates these Werte in dem returned tracking code.
Arguments
| Name | Type | Description |
|---|
| visitorCode (required) | string | Unique identifier of der Besucher. |
Rückgabewert
| Type | Description |
|---|
string | JavaScript code to insert into die Seite. |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
Events
onEvent()
The onEvent() Methode fires a callback wenn ein specific event is triggered. The callback function accesses the data associated mit das Ereignis.
The SDK Methoden in this documentation note which event types they trigger, falls vorhanden.Sie können only assign one callback to each EventType.
import {
KameleoonClient,
EventType,
EvaluationEventDataType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Define logic that will execute on SDK event
client.onEvent(EventType.Evaluation, (eventData: EventDataType) => {
// -- My Logic
});
}
init();
import { KameleoonClient, EventType } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Define logic that will execute on SDK event
client.onEvent(EventType.Evaluation, (eventData) => {
// -- My Logic
});
}
init();
Events
Events are defined in dem EventType enum. The eventData parameter will have a different type basierend auf dem event type.| Type | eventData type | Description |
|---|
EventType.Evaluation | EvaluationEventDataType | Triggered wenn der SDK evaluates any variation für ein feature flag. The event is triggered unabhängig von das Ergebnis variation |
EventType.ConfigurationUpdate | ConfigurationUpdateEventDataType | Triggered wenn der SDK receives a configuration update from der Server (when using real-time streaming) |
Arguments
| Name | Type | Description |
|---|
| event (required) | EventType | ein Typ of das Ereignis to associate the callback action mit |
| callback (required) | (eventData: EventDataType<EventType>) => void | a callback function mit dem eventData parameter that aufgerufen wird wenn ein configuration update occurs |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
Datentypen
Kameleoon Datentypen are helper classes used for storing data in predefined forms. During the flush() execution, the SDK collects all data und sends it zusammen mit the tracking request.
Data available in dem SDK ist nicht verfügbar for targeting und reporting in dem Kameleoon app until you add the data (zum Beispiel, durch die Verwendung von the addData() method).
See use visit history to target Benutzer for more information.
Wenn Sie are using Kameleoon in hybrid mode, Sie können call getRemoteVisitorData() to automatically fill all data that Kameleoon previously collected.
Browser
Browser enthält browser information.
Each visitor can only have one Browser. Adding a second Browser overwrites the first one.
| Name | Type | Description |
|---|
| browser (required) | BrowserType | predefined browser type (Chrome, InternetExplorer, Firefox, Safari, Opera, Other) |
| version (optional) | number | version of der Browser, floating point number stellt dar major und minor version of der Browser |
import { KameleoonClient, BrowserType, Browser } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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();
UniqueIdentifier
UniqueIdentifier data verwendet wird for unique visitor identification.
Wenn Sie add UniqueIdentifier for ein Besucher, visitorCode verwendet wird as the unique visitor identifier, which is useful for Geräteübergreifende Experimentierung. Linking a UniqueIdentifier to ein Besucher informs the SDK that this visitor is associated mit another visitor.
The UniqueIdentifier parameter can be beneficial in certain edge cases. Zum Beispiel, if Sie können’t access the anonymous visitorCode initially assigned to ein Besucher aber have an internal ID linked through session merging, this parameter is useful.
Each visitor can only have one UniqueIdentifier. Adding another UniqueIdentifier overwrites the first one.
| Name | Type | Description |
|---|
| value (required) | boolean | value that specifies wenn der visitor is associated mit another visitor, provided false will imply that der Besucher is not associated mit any other visitor |
import { KameleoonClient, UniqueIdentifier } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Add a unique identifier to a visitor
client.addData('my_visitor_code', new UniqueIdentifier(true));
}
init();
import { KameleoonClient, UniqueIdentifier } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Add a unique identifier to a visitor
client.addData('my_visitor_code', new UniqueIdentifier(true));
}
init();
Conversion
The Conversion data set stored here kann verwendet werden, um filter experiment und personalization reports by any goal associated mit it.
- Each visitor can have multiple
Conversion objects.
- Sie können find the
goalId in dem Kameleoon app.
ConversionParametersType conversionParameters - ein Objekt mit Conversion parameters described below
| Name | Type | Description | Default |
|---|
| goalId (required) | number | ID of das Ziel. | |
| revenue (optional) | float | Revenue des Conversion | 0 |
| negative (optional) | boolean | Defines wenn der revenue is positive oder negative. | false |
| metadata (optional) | CustomData[] | Metadata des Conversion. | undefined |
import {
KameleoonClient,
ConversionParametersType,
Conversion,
CustomData,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Defined conversion parameters
const conversionParameters: ConversionParametersType = {
goalId: 123,
revenue: 10000,
negative: true,
metadata: [new CustomData(0, 'value')],
};
// -- Add new conversion data to client
const conversion = new Conversion(conversionParameters);
client.addData('my_visitor_code', conversion);
}
init();
import { KameleoonClient, Conversion, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Defined conversion parameters
const conversionParameters = {
goalId: 123,
revenue: 10000,
negative: true,
metadata: [new CustomData(0, 'value')],
};
// -- Add new conversion data to client
const conversion = new Conversion(conversionParameters);
client.addData('my_visitor_code', conversion);
}
init();
Cookie
Cookie enthält information about das Cookie stored on der Besucher’s device.
The NodeJS SDK doesn’t require a request oder response to extract das Cookie. Stattdessen add das Cookie manually using Cookie data.
Each visitor can only have one Cookie. Adding a second Cookie overwrites the first one.
| Name | Type | Description |
|---|
| cookie (required) | CookieType[] | A list of CookieType objects consisting of cookie keys und Werte |
import { KameleoonClient, CookieType, Cookie } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Add new cookie data to client
const cookieData: CookieType[] = [
{ key: 'key_1', value: 'value_1' },
{ key: 'key_2', value: 'value_2' },
];
const cookie = new Cookie(cookieData);
client.addData('my_visitor_code', cookie);
}
init();
import { KameleoonClient, Cookie } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Add new cookie data to client
const cookieData = [
{ key: 'key_1', value: 'value_1' },
{ key: 'key_2', value: 'value_2' },
];
const cookie = new Cookie(cookieData);
client.addData('my_visitor_code', cookie);
}
init();
Methods
Cookie data has a static utility Methode, fromString, that can help you create a cookie by parsing ein String that enthält valid cookie data.
The Methode accepts string as ein Parameter, und gibt einn initialized Cookie instance.
import { Cookie } from '@kameleoon/nodejs-sdk';
const cookieString = 'key_1=value_1; key_2=value_2';
const cookie: Cookie = Cookie.fromString(cookieString);
// -- The result cookie will contain the following cookie array
// [
// { key: 'key_1', value: 'value_1' },
// { key: 'key_2', value: 'value_2' },
// ]
import { Cookie } from '@kameleoon/nodejs-sdk';
const cookieString = 'key_1=value_1; key_2=value_2';
const cookie = Cookie.fromString(cookieString);
// -- The result cookie will contain the following cookie array
// [
// { key: 'key_1', value: 'value_1' },
// { key: 'key_2', value: 'value_2' },
// ]
GeolocationData
GeolocationData enthält der Besucher’s geolocation details.
Each visitor can only have one GeolocationData. Adding a second GeolocationData overwrites the first one.
An object parameter mit der Typ GeolocationInfoType enthält Folgendes fields:
| Name | Type | Description |
|---|
| country (required) | string | The visitor’s country |
| region (optional) | string | The visitor’s region |
| city (optional) | string | The visitor’s city |
| postalCode (optional) | string | The visitor’s postal code |
| coordinates (optional) | [number, number] | Coordinates array tuple of two location Werte (longitude und latitude). Coordinate number stellt dar decimal degrees |
import {
KameleoonClient,
GeolocationData,
GeolocationInfoType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Add geolocation data
const geolocationInfo: GeolocationInfoType = {
country: 'France',
region: 'Île-de-France',
city: 'Paris',
postalCode: '75008',
coordinates: [48.8738, 2.295],
};
const geolocationData = new GeolocationData(geolocationInfo);
client.addData('my_visitor_code', geolocationData);
}
init();
import { KameleoonClient, GeolocationData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Add geolocation data
const geolocationInfo = {
country: 'France',
region: 'Île-de-France',
city: 'Paris',
postalCode: '75008',
coordinates: [48.8738, 2.295],
};
const geolocationData = new GeolocationData(geolocationInfo);
client.addData('my_visitor_code', geolocationData);
}
init();
CustomData
CustomData ermöglicht any type of data to be easily associated mit each visitor. It can then be used as a Targeting-Bedingung in Segmente oder as a filter/breakdown in experiment reports.
To learn more about custom data, please siehe this article.
To maintain the custom data in future visits, the SDK sends CustomData mit dem Visitor scope mit dem next tracking request. Sie können set the scope in dem custom data dashboard.
| Name | Type | Description | Default |
|---|
| index/name (required) | number/string | Index oder Name des custom data. Either index oder name must be provided to identify the data. | |
| overwrite (optional) | boolean | Flag to explicitly control how the Werte werden gespeichert und how they appear in reports. See more | true |
| value (required) | string[] | The custom data value. It must be stringified to match the string type. Note: value is variadic. | |
-
Each visitor is allowed only one
CustomData for each unique index. Adding another CustomData mit dem same index will replace the existing one.
-
The custom data ‘index’ can be found in dem Custom Data dashboard under the “INDEX” column.
-
To prevent the SDK from sending data mit dem selected index to Kameleoon servers for privacy reasons, enable the option: Verwenden Sie this data only locally for targeting purposes when creating custom data.
-
Adding a
CustomData instance created mit ein Name wenn der SDK instance is not initialized oder der Name is not registered, will result in dem data being ignored.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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 overwrite flag
const customData = new CustomData(customDataIndex, false, dataItemOne);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', 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);
// -- Create custom data using overwrite flag
const customData = new CustomData(customDataIndex, false, ...dataList);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', false, ...dataList);
// -- Add custom data
client.addData('my_visitor_code', customData);
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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 overwrite flag
const customData = new CustomData(customDataIndex, false, dataItemOne);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', 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);
// -- Create custom data using overwrite flag
const customData = new CustomData(customDataIndex, false, ...dataList);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', false, ...dataList);
// -- Add custom data
client.addData('my_visitor_code', customData);
}
init();
Device
Device enthält information about Ihr device.
Each visitor can only have one Device. Adding a second Device overwrites the first one.
| Name | Type | Description |
|---|
| deviceType (required) | DeviceType | possible types for device type (PHONE, TABLET, DESKTOP) |
import { KameleoonClient, DeviceType, Device } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Add device data
const device = new Device(DeviceType.Desktop);
client.addData('my_visitor_code', device);
}
init();
OperatingSystem
OperatingSystem enthält information about der Besucher’s operating system.
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.
| Name | Type | Description |
|---|
| operatingSystem (required) | OperatingSystemType | possible types for device type: WINDOWS_PHONE, WINDOWS, ANDROID, LINUX, MAC, IOS |
import {
KameleoonClient,
OperatingSystem,
OperatingSystemType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Add operating system data
const operatingSystem = new OperatingSystem(OperatingSystemType.Windows);
client.addData('my_visitor_code', operatingSystem);
}
init();
import {
KameleoonClient,
OperatingSystem,
OperatingSystemType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Add operating system data
const operatingSystem = new OperatingSystem(OperatingSystemType.Windows);
client.addData('my_visitor_code', operatingSystem);
}
init();
PageView
PageView enthält information about Ihr web page.
Each visitor can have one PageView per unique URL. Adding a PageView mit dem same URL notifies the SDK that der Besucher revisited die Seite.
PageViewParametersType pageViewParameters - ein Objekt mit page view parameters described below
| Name | Type | Description |
|---|
| urlAddress (required) | string | url address of die Seite to track |
| title (required) | string | title des web page |
| referrer (optional) | number[] | an optional parameter containing eine Liste von referrers indices, has no default value |
Sie können find the referrer’s index oder ID in Ihr Kameleoon account. Beachten Sie, dass this index starts at 0, meaning the first acquisition channel you create für ein given site will be assigned 0 as its ID, not 1.
import {
KameleoonClient,
PageViewParametersType,
PageView,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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();
UserAgent
UserAgent stores information on der Besucher’s user-agent. Server-side Experiments are more vulnerable to bot traffic than client-side Experiments. To address this, Kameleoon uses the IAB/ABC International Spiders und Bots List to identify known bots und spiders. Kameleoon also uses the UserAgent field to filter out bots und other unwanted traffic that could otherwise skew Ihr Conversion metrics. Weitere Details, see the help article on bot filtering.
Wenn Sie use internal bots, we suggest you pass der Wert curl/8.0 des userAgent to exclude them from our analytics.
A visitor can only have one UserAgent. Adding a second UserAgent overwrites the first one.
| Name | Type | Description |
|---|
| value (required) | string | value used for comparison |
Server-side Experiments are more vulnerable to bot traffic than client-side Experiments. To address this, Kameleoon uses the IAB/ABC International Spiders und Bots List to identify known bots und spiders. Wir empfehlen that you pass der Benutzer agent to be filtered by Kameleoon when running server-side Experiments for each visitor browsing Ihr website, to avoid counting bots in Ihr analytics.Wenn Sie use internal bots, we suggest that you pass der Wert curl/8.0 des userAgent to exclude them from our analytics.
import { KameleoonClient, UserAgent } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
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';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Add user agent data
const userAgent = new UserAgent('my_unique_value');
client.addData('my_visitor_code', userAgent);
}
init();
ApplicationVersion
ApplicationVersion stellt dar the semantic version number of Ihr application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.
| Name | Type | Description |
|---|
| version (optional) | string | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, oder major.minor.patch. |
import { KameleoonClient, ApplicationVersion } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Add application version
const applicationVersion = new ApplicationVersion('1.2');
client.addData('my_visitor_code', applicationVersion);
}
init();
import { KameleoonClient, ApplicationVersion } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Add application version
const applicationVersion = new ApplicationVersion('1.2');
client.addData('my_visitor_code', applicationVersion);
}
init();
Rückgabetypen
DataFile
The DataFile enthält the SDK configuration details.
It can be extended mit additional information if required by clients. Wenn Sie need more details, please contact Ihr Customer Success Manager.
| Name | Type | Description |
|---|
| featureFlags | Map<string, FeatureFlag> | A map of FeatureFlag objects, keyed by feature flag keys. |
| dateModified | number | The timestamp (in milliseconds) indicating wenn der DataFile was last modified. |
import { FeatureFlag } from '@kameleoon/nodejs-sdk';
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
const featureFlags: Map<string, FeatureFlag> = dataFile.featureFlags;
// Retrieves the last modification timestamp of the DataFile.
// The value is a number representing milliseconds since the Unix epoch.
const dateModified: number = dataFile.dateModified;
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
const featureFlags = dataFile.featureFlags;
// Retrieves the last modification timestamp of the DataFile.
// The value is a number representing milliseconds since the Unix epoch.
const dateModified = dataFile.dateModified;
FeatureFlag
The FeatureFlag stellt dar a set of properties that define a feature flag itself — zum Beispiel, its Variations, Rules, environment status, und other related details.
It can be extended mit additional information if required by clients. Wenn Sie need more details, please contact Ihr Customer Success Manager.
| Name | Type | Description |
|---|
| environmentEnabled | boolean | Indicating whether the feature flag ist aktiviert in dem current environment. |
| defaultVariationKey | string | The key des default variation associated mit dem feature flag. |
| variations | Map<string, Variation> | A map of Variation objects, keyed by variation keys. |
| Regeln | Rule[] | A list of Rule objects |
import { Variation, Rule } from '@kameleoon/nodejs-sdk';
// Check whether the feature flag is enabled in the current environment
const isEnvironmentEnabled: boolean = featureFlag.environmentEnabled;
// Retrieve the key of the default variation
const defaultVariationKey: string = featureFlag.defaultVariationKey;
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation> = featureFlag.variations;
// Retrieve all targeting rules associated with the feature flag
const rules: Rule[] = featureFlag.rules;
// Check whether the feature flag is enabled in the current environment
const isEnvironmentEnabled = featureFlag.environmentEnabled;
// Retrieve the key of the default variation
const defaultVariationKey = featureFlag.defaultVariationKey;
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
const variations = featureFlag.variations;
// Retrieve all targeting rules associated with the feature flag
const rules = featureFlag.rules;
Rule
The Rule stellt dar a set of properties that define eine Regel itself — zum Beispiel, its Variations.
It can be extended mit additional information if required by clients. Wenn Sie need more details, please contact Ihr Customer Success Manager.
| Name | Type | Description |
|---|
| variations | Map<string, Variation> | A map of Variation objects, keyed by variation keys. |
import { Variation } from '@kameleoon/nodejs-sdk';
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation> = rule.variations;
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
const variations = rule.variations;
Variation
Variation enthält information about the assigned variation to der Besucher (or the default variation, if no specific assignment existiert).
| Name | Type | Description |
|---|
| name | string | name of die variation. |
| key | string | key of die variation. |
| id | number oder null | id of die variation oder null wenn der visitor landed auf dem default variation. |
| experimentId | number oder null | id of das Experiment oder null wenn der visitor landed auf dem default variation. |
| variables | Map<string, Variable> | map of variables for die variation, where key is the variable key und value is the variable object. |
- Stellen Sie sicher, dass Ihr code handles the case where
id oder experimentId may be null, indicating a default variation.
- The
variables map might be empty if no variables are associated mit die variation.
// Retrieving the variation name
const variationName = variation.name;
// Retrieving the variation key
const variationKey = variation.key;
// Retrieving the variation id
const variationId = variation.id;
// Retrieving the experiment id
const experimentId = variation.experimentId;
// Retrieving the variables map
const variables = variation.variables;
// Retrieving the variation name
const variationName = variation.name;
// Retrieving the variation key
const variationKey = variation.key;
// Retrieving the variation id
const variationId = variation.id;
// Retrieving the experiment id
const experimentId = variation.experimentId;
// Retrieving the variables map
const variables = variation.variables;
Variable
Variable enthält information about a variable associated mit dem assigned variation.
| Name | Type | Description |
|---|
| key | string | The unique key identifying the variable. |
| type | string | The type des variable. Possible Werte: BOOLEAN, NUMBER, STRING, JSON, JS, CSS. |
| value | any | The value des variable, which can be of Folgendes types: boolean, number, String, Record<string, any>, any[]. |
// Retrieving the variables map
const variables = variation.variables;
// Variable type can be retrieved for further processing
const type = variables.get('isDiscount')?.type || '';
// Retrieving the variable value by key
const isDiscount = variables.get('isDiscount')?.value || false;
// Variable value can be of different types
const title = variables.get('title')?.value || '';
// Retrieving the variables map
const variables = variation.variables;
// Variable type can be retrieved for further processing
const type = variables.get('isDiscount')?.type || '';
// Retrieving the variable value by key
const isDiscount = variables.get('isDiscount')?.value || false;
// Variable value can be of different types
const title = variables.get('title')?.value || '';
Edge-Helfer
These helper Methoden are primarily intended for short-lived oder edge-style runtimes where the SDK may need explicit revalidation between Anfragen.
refreshDataFileIfStale()
The refreshDataFileIfStale() Methode triggers a Datendatei revalidation only wenn der current configuration is stale.
If die Datendatei is still valid und der last update happened less than the configured updateInterval ago, the Methode returns false und no update request is made.
If die Datendatei is stale, the Methode waits für den revalidation request to finish und returns true wenn der request was performed. Returning true means that the check was executed, aber die Konfiguration itself may still remain unchanged, zum Beispiel wenn der server reports that the current Datendatei is already up to date.
In a typical long-lived Node.js runtime, using this Methode is generally not recommended, because the SDK already keeps die Datendatei fresh automatically during initialization und normal runtime execution. It can still be helpful in edge-style environments wie zum Beispiel Cloudflare Workers, where runtime behavior is more short-lived und revalidation may need to be triggered explicitly.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Revalidate the data file only if the current configuration is stale
const dataFileRevalidated = await client.refreshDataFileIfStale();
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Revalidate the data file only if the current configuration is stale
const dataFileRevalidated = await client.refreshDataFileIfStale();
}
init();
Rückgabewert
| Type | Description |
|---|
Promise<boolean> | true wenn ein update request was performed, false wenn der current Datendatei is still valid und no request was made. |
Veraltete Methoden
These Methoden are deprecated und will be removed in dem next major update.
getFeatureFlagVariationKey()
The getFeatureFlagVariationKey() Methode ruft den variation key für den specified visitorCode in dem corresponding feature flag. Diese Methode umfasst a targeting check, finding the appropriate variation exposed to der Besucher, saving it to storage, und sending a tracking request.
Wenn ein user has not been previously assigned eine variation key für den feature flag, the SDK will randomly determine eine variation basierend auf dem feature flag’s Regeln. Wenn der user is already linked zum feature flag, the SDK will return their previously assigned variation key. Wenn der user nicht meet any des specified Regeln, the default value defined in Kameleoon’s feature flag delivery Regeln wird zurückgegeben. This default value is not always eine variation key—it can also be a boolean oder another data type, abhängig von the feature flag’s configuration.
import { KameleoonClient, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- 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, CustomData } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = KameleoonUtils.getVisitorCode({
request: req,
response: res,
});
// -- 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();
Arguments
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length |
| featureKey (required) | string | a unique key für ein feature flag |
Rückgabewert
| Type | Description |
|---|
string | ein String containing the variable key for der Besucher’s allocated feature flag. |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed before initialize was completed for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found für den specified featureKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag ist deaktiviert für den current environment |
getVisitorFeatureFlags()
The getVisitorFeatureFlags() Methode gibt ein list of feature flags that are active for der Besucher mit dem specified visitorCode, ensuring that der Besucher is allocated one des variations.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get active feature flags for visitor
const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get active feature flags for visitor
const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}
init();
Diese Methode only collects der Besucher’s active feature flags, meaning das Ergebnis excludes all feature flags for which der Besucher is assigned the off (default oder control) variation.Zum Beispiel:// -- `getVisitorFeatureFlags` doesn't trigger feature experiments;
// it only returns feature flags where visitors didn't get the `off` variation.
client.getVisitorFeatureFlags('my_visitor').forEach(({ key }) => {
// -- `getFeatureFlagVariationKey` triggers a feature experiment,
// as `off` is already filtered out - visitors will never take part
// in an experiment where the `off` variation was allocated.
client.getFeatureFlagVariationKey('my_visitor', key);
});
Verwenden Sie getFeatureFlags wenn Sie need all of der Besucher’s feature flags:// -- Both `off` and other variations are processed as expected.
client.getFeatureFlags('my_visitor').forEach(({ key }) => {
client.getFeatureFlagVariationKey('my_visitor', key);
});
Arguments
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length |
Rückgabewert
| Type | Description |
|---|
FeatureFlagType[] | list of feature flags, each feature flag item enthält id und key |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.StorageRead | Error while reading storage data |
getActiveFeatureFlags()
The getActiveFeatureFlags() Methode gibt ein Map, where der Schlüssel stellt dar the feature key, und der Wert enthält detailed information about der Besucher’s variation und its variables.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get active feature flags for visitor
// with detailed variation and variables data
const activeFeatures = client.getActiveFeatureFlags(visitorCode);
// -- Result example:
// Map {
// 'feature-key-one' => {
// id: 100,
// key: 'variation-key-one',
// experimentId: 200,
// variables: [
// { key: 'variable_bool', type: VariableType.Boolean, value: true },
// ]
// },
// 'feature-key-two' => {
// id: null, // -> `null` because it is default variation
// key: 'default-variation-key',
// experimentId: null, // -> `null` because it is default variation
// variables: []
// }
// }
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get active feature flags for visitor
// with detailed variation and variables data
const activeFeatures = client.getActiveFeatureFlags(visitorCode);
// -- Result example:
// Map {
// 'feature-key-one' => {
// id: 100,
// key: 'variation-key-one',
// experimentId: 200,
// variables: [
// { key: 'variable_bool', type: VariableType.Boolean, value: true },
// ]
// },
// 'feature-key-two' => {
// id: null, // -> `null` because it is default variation
// key: 'default-variation-key',
// experimentId: null, // -> `null` because it is default variation
// variables: []
// }
// }
}
init();
Diese Methode only collects der Besucher’s active feature flags, meaning das Ergebnis excludes all feature flags for which der Besucher is assigned the off (default oder control) variation.See the getVisitorFeatureFlags method’s CAUTION Abschnitt for more details.
Arguments
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length |
Rückgabewert
| Type | Description |
|---|
Map<string, KameleoonVariationType> | a map of feature flags, where key is feature key und value is detailed information about der Besucher’s variation und its variables |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.StorageRead | Error while reading storage data |
KameleoonException.NumberParse | Couldn’t parse Number value |
KameleoonException.JSONParse | Couldn’t parse JSON value |
getFeatureFlagVariable()
The getFeatureFlagVariable() Methode ruft ein variable for der Besucher basierend auf dem visitorCode innerhalb des identified feature flag. Diese Methode umfasst a targeting check, determines the appropriate variation for der Besucher, saves it to storage, und sends a tracking request.
import {
KameleoonClient,
VariableType,
JSONType,
} from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get feature variable
const result = client.getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key'
variableKey: 'my_variable_key'
});
// -- Infer the type of a variable by its `type`
switch (result.type) {
case VariableType.BOOLEAN:
const myBool: boolean = result.value;
break;
case VariableType.NUMBER:
const myNum: number = result.value;
break;
case VariableType.JSON:
const myJson: JSONType = result.value;
break;
case VariableType.STRING:
case VariableType.JS:
case VariableType.CSS:
const myStr: string = result.value;
break;
default:
break;
}
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get feature variable
const variableResult = client.getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key'
variableKey: 'my_variable_key'
});
const { type, value } = variableResult;
}
init();
Arguments
Parameters object of type GetFeatureFlagVariableParamsType containing Folgendes fields:
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length |
| featureKey (required) | string | a unique key für ein feature flag |
| variableKey (required) | string | variable’s key für ein feature flag mit provided featureKey, can be found in Kameleoon |
Rückgabewert
| Type | Description |
|---|
FeatureFlagVariableType | is a variable object containing type und value fields. Sie können check the type field against the VariableType enum. Zum Beispiel, wenn der type is VariableType.BOOLEAN, the value is a boolean type. |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed before initialize was completed for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found für den specified featureKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag ist deaktiviert für den current environment |
KameleoonException.JSONParse | Couldn’t parse JSON value |
KameleoonException.NumberParse | Couldn’t parse Number value |
getFeatureFlagVariables()
The getFeatureFlagVariables() Methode ruft ein list of variable Werte für ein specified visitor und feature flag. Diese Methode checks wenn der user is targeted, identifies der Besucher’s assigned variation, stores it, und sends a tracking request.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get a list of variables for the visitor under `visitorCode` in the feature flag
const variables = client.getFeatureFlagVariables(
visitorCode,
'my_feature_key',
);
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get visitor code using server `request` and `response`
const visitorCode = client.getVisitorCode({
request: req,
response: res,
});
// -- Get a list of variables for the visitor under `visitorCode` in the feature flag.
const variables = client.getFeatureFlagVariables(
visitorCode,
'my_feature_key',
);
}
init();
Arguments
| Name | Type | Description |
|---|
| visitorCode (required) | string | unique visitor identification string, can’t exceed 255 characters in length |
| featureKey (required) | string | a unique key für den feature flag |
Rückgabewert
| Type | Description |
|---|
FeatureVariableResultType[] | eine Liste von variable objects containing key, type und value fields. Sie können check the type field against the VariableType enum. Zum Beispiel, wenn der type is VariableType.BOOLEAN then value will be a boolean type. |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
KameleoonException.VisitorCodeMaxLength | The Besuchercode exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besuchercode is empty |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found für den specified featureKey |
KameleoonException.FeatureFlagVariationNotFound | No feature variation was found für den specified visitorCode und variationKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag ist deaktiviert für den current environment |
KameleoonException.JSONParse | Couldn’t parse JSON value |
KameleoonException.NumberParse | Couldn’t parse Number value |
onConfigurationUpdate()
Verwenden Sie the onEvent Methode mit EventType.ConfigurationUpdate instead.
The onConfigurationUpdate() Methode fires a callback upon client configuration update.
Diese Methode is only applicable to server-sent Ereignisse for real-time updates.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Define logic that will execute on client configuration update
client.onConfigurationUpdate(() => {
// -- My Logic
});
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Define logic that will execute on client configuration update
client.onConfigurationUpdate(() => {
// -- My Logic
});
}
init();
Arguments
| Name | Type | Description |
|---|
| callback (required) | () => void | callback function mit no parameters that wird aufgerufen upon configuration update |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |
getFeatureFlags()
🚫 Doesn’t send Tracking Data to Kameleoon
The getFeatureFlags() Methode ruft ein list of feature flags that werden gespeichert in der Client configuration.
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init(): Promise<void> {
await client.initialize();
// -- Get all feature flags
const featureFlags = client.getFeatureFlags();
}
init();
import { KameleoonClient } from '@kameleoon/nodejs-sdk';
import { KameleoonVisitorCodeManager } from '@kameleoon/nodejs-visitor-code-manager';
import { KameleoonEventSource } from '@kameleoon/nodejs-event-source';
import { KameleoonRequester } from '@kameleoon/nodejs-requester';
const client = new KameleoonClient({
siteCode: 'my_site_code',
credentials: { clientId: 'my_client_id', clientSecret: 'my_client_secret' },
externals: {
visitorCodeManager: new KameleoonVisitorCodeManager(),
eventSource: new KameleoonEventSource(),
requester: new KameleoonRequester(),
},
});
async function init() {
await client.initialize();
// -- Get all feature flags
const featureFlags = client.getFeatureFlags();
}
init();
Rückgabewert
| Type | Description |
|---|
FeatureFlagType[] | list of feature flags, each feature flag item enthält id und key |
Ausgelöste Ausnahmen
| Type | Description |
|---|
KameleoonException.Initialization | Method was executed vor dem kameleoonClient completed its initialize call |