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:npx:
deno.json:
deno.json
Initialisierung des Kameleoon-Clients
Entwickler müssen einen Einstiegspunkt für das NodeJS SDK erstellen, indem sie eine neue Instanz vonKameleoonClient.
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.
To add NodeJS SDK zu einem Edge-Umgebung, please siehe diesen Abschnitt.
- TypeScript
- JavaScript
Arguments
Ausgelöste Ausnahmen
Konfigurationsparameter
- SDK Version 4
- SDK Version 5
Kompatibilitätsmodus
Verwenden Sie the SDK parametercompatibility 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 therequestTimeoutparameter inSDKConfigurationTypeunavailable und prevent the SDK from usingAbortControllerfor request cancellation, even within default10_000ms timeout. Supports Node version 14 und higher.Compatibility.Node12- compatibility mit this version implies the same limitations as theNode14Kompatibilitä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 thegetVisitorCode() 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 thegetVariation() 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 theaddData() 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 thetrackConversion() 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 thegetEngineTrackingCode() 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 everyKameleoonClient 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.
- TypeScript
- JavaScript
Integration mit Edge-Anbieter
- SDK Version 4
- SDK Version 5
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 thegetRemoteVisitorData() 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.
- TypeScript
- JavaScript
Device One
Device Two
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.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.- TypeScript
- JavaScript
Login Page
Application Page
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.
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:- 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 aCustomDataobject. Here,newVisitorCoderefers zum identifier you wish to use for Ihr bucketing (zum Beispiel, the newuserIdoderaccountId).
- Bucketing logic: Sobald ein custom bucketing key is provided durch den
addData()Methode, all hash calculations for assigning Benutzer to variations will use thisnewVisitorCode(Ihr custom key) instead des defaultvisitorCode. Unter Verwendung dernewVisitorCodemeans 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 originalvisitorCode. 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.- TypeScript
- JavaScript
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.
- TypeScript
- JavaScript
Domain-Informationen
You provide a domain as thedomain 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 iswww.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 ..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
domainfield in dem SDK client while testing. Dies verhindertlocalhostissues (das Cookie wird gesetzt on any domain). - Create a local domain for
localhost. Zum Beispiel:- Navigate to
/etc/hostson Linux oder toc:\Windows\System32\Drivers\etc\hostson Windows - Öffnen Sie
hostsmit file super user oder administrator rights - Fügen Sie hinzu a domain zum
localhostport, zum Beispiel:127.0.0.1 app.com - Now, Sie können run Ihr app locally on
app.com:{my_port}und specify.app.comas Ihr domain
- Navigate to
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.
Sie können also implement
visitorCodeManager unter Verwendung der IExternalNextJSVisitorCodeManager, IExternalDenoVisitorCodeManager, oder IExternalCustomVisitorCodeManager interfaces for NextJS, Deno, oder custom Besuchercode manager implementations, respectively.@kameleoon/nodejs-event-source- basierend aufeventsourcelibrary (kann verwendet werden for NodeJS/Deno/NextJS SSR)@kameleoon/nodejs-requester- basierend aufnode-fetchlibrary (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 SSRheaderscookie oder NextJS SSR request/response
Storage
- TypeScript
- JavaScript
EventSource
- TypeScript
- JavaScript
VisitorCodeManager
visitorCodeManager implementation for NodeJS/NextJS SSR:
- TypeScript
- JavaScript
visitorCodeManager implementation for Deno:
- TypeScript
- JavaScript
visitorCodeManager implementation for NextJS Server Actions:
- TypeScript
- JavaScript
visitorCodeManager implementation mit arbitrary parameters:
- TypeScript
- JavaScript
Requester
- TypeScript
- JavaScript
Utilities
The SDK has a set of utility Methoden that Sie können use to simplify development. All Methoden are represented as static members desKameleoonUtils class.
- SDK Version 4
- SDK Version 5
simulateSuccessRequest
Verwenden Sie thesimulateSuccessRequest 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.
- TypeScript
- JavaScript
Arguments
The
SimulateRequestDataType data type is defined wie folgt:
RequestType.Tracking-nullRequestType.ClientConfiguration-ClientConfigurationDataTypeRequestType.RemoteData-JSONType
Rückgabewert
getCookieValue
Verwenden Sie thegetCookieValue 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.
- TypeScript
- JavaScript
Arguments
Rückgabewert
Referenz
Dies ist the full reference documentation für den Kameleoon JavaScript SDK.Initialisierung
initialize()
An asynchronous Methode for initializingKameleoonClient 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.
- TypeScript
- JavaScript
Rückgabewert
Ausgelöste Ausnahmen
Feature flags und variations
getVariation()
- 📨 Sends Tracking Data to Kameleoon (abhängig von the
trackparameter)
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.
- TypeScript
- JavaScript
Arguments
An object of typeGetVariationParamsType mit Folgendes properties:
Rückgabewert
Ausgelöste Ausnahmen
getVariations()
- 📨 Sends Tracking Data to Kameleoon (abhängig von the
trackparameter) - 🎯 Events:
EventType.Evaluation
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
onlyActivegesetzt ist totrue, the MethodegetVariations()will return feature flags variations provided der Benutzer is not bucketed mit demoffvariation. - The
trackparameter controls whether oder not the Methode will track die variation assignments. Standardmäßig it gesetzt ist totrue. If set tofalse, the tracking will be disabled.
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.
- TypeScript
- JavaScript
Arguments
An object of typeGetVariationsParamsType mit Folgendes properties:
Rückgabewert
Ausgelöste Ausnahmen
isFeatureFlagActive()
- 📨 Sends Tracking Data to Kameleoon (abhängig von the
trackparameter) - 🎯 Events:
EventType.Evaluation
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.- TypeScript
- JavaScript
Arguments
There are two overloads available for this method:- Two parameters overload:
- Object parameter overload of type
IsFeatureFlagActiveParamsType:
Rückgabewert
Ausgelöste Ausnahmen
setForcedVariation()
The Methode ermöglicht you to programmatically assign a specificVariation 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.
- TypeScript
- JavaScript
Arguments
An object of typeSetForcedVariationParametersType mit Folgendes properties:
Ausgelöste Ausnahmen
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
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.
- TypeScript
- JavaScript
Arguments
Ausgelöste Ausnahmen
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()
Gibt den current SDK configuration as aDataFile object.
- TypeScript
- JavaScript
Rückgabewert
Besucherdaten
getVisitorCode()
ThegetVisitorCode 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
kameleoonSimulationFFDatacookie manually.
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific zu einem individual experiment.
kameleoonSimulationFFData cookie follows this format:kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates die variation mitvarIdof experimentexpIdfür den givenfeatureKey.kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined in dem Then, for everyone else in Production, serve Abschnitt) für den givenfeatureKey.
encodeURIComponent.- TypeScript
- JavaScript
Arguments
The parameters object is overloaded mit two types:- Type
GetVisitorCodeParametersType(forNodeJS/Express/NextJS SSR methods), containing Folgendes fields:
- Type
GetNextJSVisitorCodeParametersType(forNextJS SSR server actions), containing Folgendes fields:
- Type
GetDenoVisitorCodeParametersType(forDeno), containing Folgendes fields:
- Type
GetCustomVisitorCodeParametersType(for customVisitorCodeManagerimplementation), containing Folgendes fields:
Wenn Sie don’t provide a
defaultVisitorCode und there is no Besuchercode stored in einem cookie, den Besuchercode will be randomly generated.Rückgabewert
Ausgelöste Ausnahmen
addData()
Verwenden Sie theaddData() 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.
Check the list of supported conditions to see the data types Sie können use for targeting.
- TypeScript
- JavaScript
Arguments
-
kameleoonDatais 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 assigned0as its ID, rather than1.
Ausgelöste Ausnahmen
Check the data types reference for more details on how to manage different data types.
flush()
- SDK Version 4
- SDK Version 5
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.- TypeScript
- JavaScript
Arguments
Or ein Objekt mit der Typ FlushParamsType, containing:
Ausgelöste Ausnahmen
getRemoteData()
ThegetRemoteData() 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.
- TypeScript
- JavaScript
Arguments
Rückgabewert
Ausgelöste Ausnahmen
getRemoteVisitorData()
- SDK Version 4
- SDK Version 5
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.
- TypeScript
- JavaScript
Arguments
An object mit der TypRemoteVisitorDataParamsType, containing:Rückgabewert
Ausgelöste Ausnahmen
Using parameters in getRemoteVisitorData()
ThegetRemoteVisitorData() 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:getVisitorWarehouseAudience()
ThegetVisitorWarehouseAudience 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.
- TypeScript
- JavaScript
Arguments
Parameters object consisting of:Rückgabewert
Ausgelöste Ausnahmen
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.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.
- TypeScript
- JavaScript
Arguments
The parameters object is overloaded mit Folgendes types:- Type
SetLegalConsentParametersType(forNodeJS/Express/NextJS SSR methods), containing Folgendes fields:
- Type
SetNextJSLegalConsentParametersType(forNextJS SSR server actions), containing Folgendes fields:
- Type
SetDenoLegalConsentParametersType(forDeno), containing Folgendes fields:
- Type
SetCustomLegalConsentParametersType(for customVisitorCodeManagerimplementation), containing Folgendes fields:
Ausgelöste Ausnahmen
Verhalten bei Widerruf der Einwilligung
Wenn Sie callsetLegalConsent() 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
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.- TypeScript
- JavaScript
Arguments
Parameters object consisting of: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’).- TypeScript
- JavaScript
Ausgelöste Ausnahmen
getEngineTrackingCode()
Kameleoon integrates mit several analytics solutions, including Mixpanel, Google Analytics 4, und Segment. To track server-side Experiments correctly, call thegetEngineTrackingCode() 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.
- TypeScript
- JavaScript
-
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.
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
Rückgabewert
Ausgelöste Ausnahmen
Events
- SDK Version 5
onEvent()
TheonEvent() 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.- TypeScript
- JavaScript
Events
Events are defined in demEventType enum. The eventData parameter will have a different type basierend auf dem event type.Arguments
Ausgelöste Ausnahmen
Datentypen
Kameleoon Datentypen are helper classes used for storing data in predefined forms. During theflush() 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.- TypeScript
- JavaScript
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.- TypeScript
- JavaScript
Conversion
TheConversion data set stored here kann verwendet werden, um filter experiment und personalization reports by any goal associated mit it.
ConversionParametersType conversionParameters - ein Objekt mit Conversion parameters described below
- TypeScript
- JavaScript
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.- TypeScript
- JavaScript
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.
- TypeScript
- JavaScript
GeolocationData
GeolocationData enthält der Besucher’s geolocation details.
Each visitor can only have one
GeolocationData. Adding a second GeolocationData overwrites the first one.GeolocationInfoType enthält Folgendes fields:
- TypeScript
- JavaScript
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.
-
Each visitor is allowed only one
CustomDatafor each uniqueindex. Adding anotherCustomDatamit dem sameindexwill 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
CustomDatainstance created mit ein Name wenn der SDK instance is not initialized oder der Name is not registered, will result in dem data being ignored.
- TypeScript
- JavaScript
Device
Device enthält information about Ihr device.Each visitor can only have one
Device. Adding a second Device overwrites the first one.- TypeScript
- JavaScript
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.- TypeScript
- JavaScript
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
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.
- TypeScript
- JavaScript
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.- TypeScript
- JavaScript
ApplicationVersion
ApplicationVersion stellt dar the semantic version number of Ihr application.
- TypeScript
- JavaScript
Rückgabetypen
DataFile
TheDataFile 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.
- TypeScript
- JavaScript
FeatureFlag
TheFeatureFlag 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.
- TypeScript
- JavaScript
Rule
TheRule 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.
- TypeScript
- JavaScript
Variation
Variation enthält information about the assigned variation to der Besucher (or the default variation, if no specific assignment existiert).
- Stellen Sie sicher, dass Ihr code handles the case where
idoderexperimentIdmay benull, indicating a default variation. - The
variablesmap might be empty if no variables are associated mit die variation.
- TypeScript
- JavaScript
Variable
Variable enthält information about a variable associated mit dem assigned variation.
- TypeScript
- JavaScript
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()
TherefreshDataFileIfStale() 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.
- TypeScript
- JavaScript
Rückgabewert
Veraltete Methoden
getFeatureFlagVariationKey()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation
Verwenden Sie the
getVariation Methode instead.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.
- TypeScript
- JavaScript
Arguments
Rückgabewert
Ausgelöste Ausnahmen
getVisitorFeatureFlags()
Verwenden Sie the
getVariations Methode instead.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.
- 🚫 Doesn’t send Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation(for each feature flag)
- TypeScript
- JavaScript
Arguments
Rückgabewert
Ausgelöste Ausnahmen
getActiveFeatureFlags()
- 🚫 Doesn’t send Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation(for each feature flag)
Verwenden Sie the
getVariations Methode instead.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.
- TypeScript
- JavaScript
Arguments
Rückgabewert
Ausgelöste Ausnahmen
getFeatureFlagVariable()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation
Verwenden Sie the
getVariation Methode instead.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.
- TypeScript
- JavaScript
Arguments
Parameters object of typeGetFeatureFlagVariableParamsType containing Folgendes fields:
Rückgabewert
Ausgelöste Ausnahmen
getFeatureFlagVariables()
- 📨 Sends Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation(for each feature flag)
Verwenden Sie the
getVariation Methode instead.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.
- TypeScript
- JavaScript
Arguments
Rückgabewert
Ausgelöste Ausnahmen
onConfigurationUpdate()
Verwenden Sie the
onEvent Methode mit EventType.ConfigurationUpdate instead.onConfigurationUpdate() Methode fires a callback upon client configuration update.
Diese Methode is only applicable to server-sent Ereignisse for real-time updates.
- TypeScript
- JavaScript
Arguments
Ausgelöste Ausnahmen
getFeatureFlags()
Verwenden Sie the
getDataFile() Methode instead.getFeatureFlags() Methode ruft ein list of feature flags that werden gespeichert in der Client configuration.
- TypeScript
- JavaScript