Skip to main content
Puede ejecutar experimentos y activar feature flags con el SDK de NodeJS. Integrar nuestro SDK en su servidor es sencillo y su huella (memoria y uso de red) es baja. Nuestro SDK de Node admite la versión 16+ de Node, con la opción de degradarlo a la versión 14 y 12 mediante el modo de compatibilidad. Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador. Métodos del SDK: Para la documentación de referencia completa del SDK de NodeJS, consulte la sección referencia. Changelog: Última versión del SDK de NodeJS: Changelog. Ejemplo de Next.js: Para ver ejemplos de la integración del SDK de NodeJS con Next.js, incluyendo App Router, Pages Router, middleware y server actions, consulte el repositorio de starter kits de Next.js.
Antes de comenzar la instalación de nuestro SDK de NodeJS, le recomendamos leer nuestro artículo de consideraciones técnicas para comprender los conceptos tecnológicos que hay detrás de nuestros SDKs. Este artículo le ayudará a garantizar una integración exitosa.

Guía del desarrollador

Siga esta sección para instalar y configurar el SDK y conocer las funcionalidades avanzadas.

Primeros pasos

Instalación

Utilice la herramienta de instalación de SDK de Kameleoon para instalar el SDK. El instalador de SDK le ayuda a instalar el SDK de su elección, generar una muestra de código básica y configurar las dependencias externas si es necesario. Para usar la herramienta de instalación del SDK, instálela y ejecútela globalmente:
O ejecútela directamente con npx:
When using Deno, provide dependencies manually in deno.json:
deno.json

Inicializar el cliente Kameleoon

Developers must create an entry point for the NodeJS SDK by instantiating a new KameleoonClient. It is recommended to treat KameleoonClient as a singleton, creating a single shared instance and reusing it throughout the server instance to ensure consistency and avoid unnecessary reinitialization. Use KameleoonClient para ejecutar experimentos de funcionalidades y obtener el estado de los feature flags y sus variaciones. KameleoonClient initializes asynchronously to ensure that communication with the Kameleoon API is successful, using the initialize() method. You can use async/await, Promise.then(), or any other asynchronous pattern to handle client initialization.
To add NodeJS SDK to an Edge environment, please refer to this section.
Argumentos
Exceptions thrown
Parámetros de configuración
Option 1 (Recommended): Use JSON.stringify()
Option 2: Raw JSON string (escape special characters)
Compatibility Mode
Use the SDK parameter compatibility to disable some of the SDK’s features to improve compatibility with older NodeJS versions. Compatibility is an enum representing all possible compatibility modes:
  • Compatibility.Node16 - default mode, all features are enabled. This mode will be used if no compatibility mode is provided. Supports Node version 16 and higher.
  • Compatibility.Node14 - compatibility with this version will make the requestTimeout parameter in SDKConfigurationType unavailable and prevent the SDK from using AbortController for request cancellation, even within default 10_000 ms timeout. Supports Node version 14 and higher.
  • Compatibility.Node12 - compatibility with this version implies the same limitations as the Node14 compatibility mode. Adicionalmente, you cannot provide “@kameleoon/nodejs-requester” as a requester implementation in this compatibility mode, 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, como por ejemplo an older “node-fetch” version or other HTTP based implementation.

Activar un feature flag

Asignar un identificador único a un usuario
To assign a unique ID to a user, you can use the getVisitorCode() method. If a código de visitante doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode that you would have generated. The ID is then set in a response headers cookie. If you are using Kameleoon in Hybrid mode, calling the getVisitorCode() method ensures that the unique ID (código de visitante) is shared between the application file engine.js (previously named, kameleoon.js) and the SDK.
Retrieving a flag configuration
To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account. To determine the status or variation of a feature flag for a specific user, you should use the getVariation() or isFeatureFlagActive() method to retrieve the configuration based on the featureKey. The getVariation() method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the featureKey and visitorCode. The isFeatureFlagActive() method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options. If your feature flag has associated variables (como por ejemplo specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK will send the exposure event to the specified experiment on the next solicitud de seguimiento, which is automatically triggered based on the SDK’s tracking_interval_millisecond. By default, this interval is set to 1000 milliseconds (1 second). The getVariation() method allows you to control whether tracking is done. If track=false, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Adicionalmente, setting track=false is helpful when using the getVariations() method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article
Adding data points to target a user or filter / breakdown visits in reports
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the addData() method to add these data points to the user’s profile. Para recuperar los puntos de datos recogidos en otros dispositivos o para acceder a los datos pasados del usuario (recogidos en el lado del cliente cuando se utiliza Kameleoon en modo híbrido), utilice el método getRemoteVisitorData(). This method asynchronously fetches data from the servers. It is important to call getRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation. To learn more about available targeting conditions, see the detailed article on the subject. Adicionalmente, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here. Si necesita rastrear puntos de datos adicionales más allá de lo que se recoge automáticamente, puede utilizar la funcionalidad Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recogidos a los servidores de Kameleoon para su análisis.
To ensure your results are accurate, it’s recommended to filter out bots by using the UserAgent data type.
Tracking goal conversions
When a user completes a desired action (como por ejemplo making a purchase), it is recorded as a conversion. To track conversions, use the trackConversion() method and provide the required visitorCode and goalId parameters. La solicitud de seguimiento de la conversión se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval_millisecond). If you prefer to send the request immediately, use the flush() method with the parameter instant=true.
Sending events to analytics solutions
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the getEngineTrackingCode() method. The getEngineTrackingCode() method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.

Gestión de errores

Almost every KameleoonClient method may throw an error at some point. These errors are deliberately predefined KameleoonErrors that extend the native JavaScript Error class, providing useful messages and a special type field with a type KameleoonException. KameleoonException is an enum containing all possible error types. To know exactly what type of KameleoonException the method may throw, check the method description’s Throws section, or hover over the method in your IDE to see the jsdocs description. Handling errors is considered a good practice to make your application more stable and avoid technical issues.

Integración con proveedores Edge

Kameleoon provides lo siguiente starter packs to automate your integration with specific edge providers:For other edge providers, use External Dependencies for greater control over the SDK.

Experimentación entre dispositivos

To support visitors who access an app from multiple devices, Kameleoon allows the synchronization of previously collected datos del visitante across each of the visitor’s devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the article on cross-device experimentation.

Sincronización de datos personalizados entre dispositivos

Aunque se utiliza la sincronización con mapeo personalizado para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización con mapeo personalizado: Same user ID across devices If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the getRemoteVisitorData() method when you want to sync the data collected between multiple devices. Multi-server instances with consistent IDs In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with getRemoteVisitorData()) is sufficient without additional custom mapping sync. Customers who need additional data can refer to the getRemoteVisitorData() method 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) is used consistently between the two devices for accurate data retrieval.
Si desea sincronizar los datos recogidos en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
Device One
Device Two

Uso de datos personalizados para la fusión de sesiones

Cross-device experimentation lets you combine a visitor’s history across each of their devices (history reconciliation). You can merge multiple visitor sessions into one with history reconciliation. Use CustomData and provide a unique identifier for the visitor to reconcile visit history.Follow the activating cross-device history reconciliation guide to set up your datos personalizados in Kameleoon.You can use datos personalizados in your code to merge a visitor’s session. Sessions with the same identifier will always see the same experiment variation, and will be displayed as a single visitor in the Visitor view of your experiment’s result page.La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento.Before using other methods, inform the SDK that the visitor is a unique identifier by adding UniqueIdentifier data to a visitor.
Since the datos personalizados you use as the identifier must be set to the Visitor scope, you must use cross-device datos personalizados synchronization to retrieve the identifier with the getRemoteVisitorData method on each device.
In lo siguiente example, we have an application with a login page. Since we don’t know the user ID at the time of login, we use an anonymous visitor identifier generated by the getVisitorCode method. After the user logs in, we can associate the anonymous visitor with the user ID and use it as a unique identifier for the visitor.
Login Page
Application Page

Uso de una clave de bucketing personalizada

By default, Kameleoon uses a unique, anonymous visitor ID (visitorCode) to assign users to feature flag variations. This ID is typically generated and stored on the user’s device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). Sin embargo, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag. The Custom Bucketing Key option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon’s assignment logic uses your specified key instead of the default visitorCode.

Casos de uso

Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:
  • Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como un accountId. Las claves de bucketing personalizadas son fundamentales para realizar pruebas A/B de funcionalidades que afectan a todo un equipo o empresa.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y una mejor experiencia de usuario.

Detalles técnicos

Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico procedente de los datos de su aplicación:
  • Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the addData() method. In this method, you will pass your chosen custom bucketing key as a CustomData object. Here, newVisitorCode refers to the identifier you wish to use for your bucketing (for example, the new userId or accountId).
For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK’s bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this article.
  • Bucketing logic: Once a custom bucketing key is provided through the addData() method, all hash calculations for assigning users to variations will use this newVisitorCode (your custom key) instead of the default visitorCode. Using the newVisitorCode means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
  • Data tracking and analytics: It’s crucial to note that while the newVisitorCode (your custom key) is used for bucketing decisions, all subsequent data (tracking events and conversions, for example) is sent and associated with the original visitorCode. This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment’s broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original datos del visitante remains intact for comprehensive reporting.

Requisitos técnicos

To effectively use a custom bucketing key:
  • The key must be a string.
  • Debe ser única para la entidad que desea segmentar (por ejemplo, si utiliza un userId, el ID de cada usuario debe ser único).
  • La clave debe estar disponible para el SDK en el momento exacto en el que se evalúa la decisión del feature flag para ese usuario o solicitud.

Condiciones de segmentación

Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede utilizar para segmentar usuarios en sus campañas. Para ver la lista de condiciones admitidas por este SDK, consulte usar el historial de visitas para segmentar usuarios. También puede utilizar sus propios datos externos para segmentar usuarios.

Registro de logs

The SDK generates logs to reflect various internal processes and issues.

Niveles de log

The SDK supports configuring limiting logging by a log level.

Gestión personalizada de los logs

El SDK escribe sus logs en la salida de consola de forma predeterminada. Este comportamiento puede modificarse.
La limitación de los logs por nivel de log se realiza de forma independiente a la lógica de gestión de los logs.

Información del dominio

You provide a domain as the domain in KameleoonClient configuration, which is used for storing Kameleoon código de visitante in cookies. Providing a domain is important when working with the getVisitorCode and setLegalConsent methods. The domain you provide is stored in the cookie as the Domain= key.

Configurar el dominio

The domain you provide lets the URL address use the cookie. Por ejemplo, if your domain is www.example.com, the cookie is only available from a www.example.com URL. Pages with the app.example.com domain can’t use the cookie. For more flexibility with subdomains, you can specify a domain starting with a .. For instance, domain .example.com allows the cookie to function on both app.example.com and login.example.com.
No puede utilizar expresiones regulares, símbolos especiales, protocolo ni números de puerto en domain. Adicionalmente, a specific list of subdomains cannot be used with the prefix ..
A continuación se ofrece una pequeña hoja de referencia para dominios:

Desarrollo en localhost

localhost is always considered a bad domain, making it hard to test the domain when developing on localhost. There are two ways to avoid this issue:
  • Don’t specify the domain field in the SDK client while testing. This prevents localhost issues (the cookie will be set on any domain).
  • Create a local domain for localhost. Por ejemplo:
    • Navigate to /etc/hosts on Linux or to c:\Windows\System32\Drivers\etc\hosts on Windows
    • Open hosts with file super user or administrator rights
    • Añadir un dominio al puerto localhost, por ejemplo: 127.0.0.1 app.com
    • Now, you can run your app locally on app.com:{my_port} and specify .app.com as your domain

Dependencias externas

The SDK’s external dependencies use the dependency injection pattern, letting you provide your own implementations for certain parts of an SDK.
In the NodeJS SDK, some external dependencies have default implementations, while others must be provided by the user, whether using dedicated Kameleoon implementations or custom implementations.
Here’s the list of available external dependencies:
You can also implement visitorCodeManager using the IExternalNextJSVisitorCodeManager, IExternalDenoVisitorCodeManager, or IExternalCustomVisitorCodeManager interfaces for NextJS, Deno, or custom código de visitante manager implementations, respectively.
External dependencies provide developers flexibility to adapt and use the NodeJS SDK in any environment. There are a number of npm packages Kameleoon provides for frequently used environments. You can install the packages manually, or by using the SDK installation tool (recommended). These are the Kameleoon-provided external dependencies for NodeJS SDK:
  • @kameleoon/nodejs-event-source - based on eventsource library (can be used for NodeJS/Deno/NextJS SSR)
  • @kameleoon/nodejs-requester - based on node-fetch library (can be used for NodeJS/Deno/NextJS SSR)
  • @kameleoon/nodejs-visitor-code-manager - implemented with 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 or NextJS SSR request/response
You can optionally implement external dependencies on your own. Lo siguiente example implements external dependencies. To import an interface from an SDK, create a class that implements it and pass the instantiated class to the SDK.

Almacenamiento

EventSource

VisitorCodeManager

visitorCodeManager implementation for NodeJS/NextJS SSR:
visitorCodeManager implementation for Deno:
visitorCodeManager implementation for NextJS Server Actions:
Custom visitorCodeManager implementation with arbitrary parameters:

Requester

Utilidades

The SDK has a set of utility methods that you can use to simplify development. All methods are represented as static members of the KameleoonUtils class.

simulateSuccessRequest

Use the simulateSuccessRequest method to simulate a successful request to the Kameleoon server. This method can be useful for custom Requester implementations when a developer needs to simulate a successful request.
Argumentos
The SimulateRequestDataType data type is defined de la siguiente manera:
  • RequestType.Tracking - null
  • RequestType.ClientConfiguration - ClientConfigurationDataType
  • RequestType.RemoteData - JSONType
Return value

getCookieValue

Use the getCookieValue method to parse a common cookie string (key_1=value_1; key_2=value_2; ...), and get the value of a specific cookie key. This method is useful when working with a custom implementation of VisitorCodeManager.
Argumentos
Return value

Referencia

This is the full reference documentation for the Kameleoon JavaScript SDK.

Inicialización

initialize()

An asynchronous method for initializing KameleoonClient that retrieves Kameleoon SDK data either from the server or a local source if the data is still up-to-date or the update interval has not yet elapsed.
Return value
Exceptions thrown

Feature flags y variaciones

getVariation()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
Retrieves the Variation assigned to a given visitor for a specific feature flag. This method takes featureKey as a mandatory argument and track as an optional argument. The track argument is optional and defaults to true. It returns the assigned Variation for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation for the given feature flag. Ensure that proper error handling is implemented in your code to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Argumentos
An object of type GetVariationParamsType with lo siguiente properties:
Return value
Exceptions thrown

getVariations()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
  • 🎯 Events: EventType.Evaluation
Retrieves a map of Variation objects assigned to a given visitor across all feature flags. This method iterates over all available feature flags and returns the assigned Variation for each flag associated with the specified visitor. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.
  • If onlyActive is set to true, the method getVariations() will return feature flags variations provided the user is not bucketed with the off variation.
  • The track parameter controls whether or not the method will track the variation assignments. By default, it is set to true. If set to false, the tracking will be disabled.
The returned map consists of feature flag keys as keys and their corresponding Variation as values. If no variation is assigned for a feature flag, the method returns the default Variation for that flag. Proper error handling should be implemented to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Argumentos
An object of type GetVariationsParamsType with lo siguiente properties:
Return value
Exceptions thrown

isFeatureFlagActive()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
  • 🎯 Events: EventType.Evaluation
The isFeatureFlagActive() method returns a boolean indicating whether the visitor with visitorCode has an active featureKey. This method checks for targeting, finds the variation for the visitor, and saves it to storage. The method also sends a solicitud de seguimiento. This method 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 and visitors when you call certain methods, como por ejemplo isFeatureFlagActive(), getVariation() or getVariations().Use the default true value for the track parameter when you expose visitors to a variation and need to count them. Set the track parameter to false only if you call these methods before you expose visitors.Por ejemplo, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
The isFeatureFlagActive() method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the Then, for everyone else serve default state. If you select Off for this default state, the method always returns false even when the master feature flag is On.
Argumentos
There are two overloads available for this method:
  1. Two parameters overload:
This overload is deprecated and will be removed in the next major version. Please use the new overload with an object parameter.
  1. Object parameter overload of type IsFeatureFlagActiveParamsType:
Return value
Exceptions thrown

setForcedVariation()

The method allows you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing. When a forced variation is set, it overrides Kameleoon’s real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting. The method may throw exceptions under certain conditions (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
  • Forced variations: Are specific to an individual experiment.
  • Simulated variations: Affect the overall feature flag result.
Argumentos
An object of type SetForcedVariationParametersType with lo siguiente properties:
Exceptions thrown
In most cases, only the basic error, KameleoonException, needs to be handled, as demonstrated in the example. Sin embargo, if different types of errors require a response, handle each one separately based on specific requirements. Adicionalmente, for enhanced reliability, general language errors can be handled by including Error.

evaluateAudiences()

  • 📨 Sends Tracking Data to Kameleoon
This method evaluates visitors against all available Audiences Explorer segments and tracks those who match. evaluateAudiences() should be called after all relevant datos del visitante has been set or updated, and just before getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria. After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
Argumentos
Exceptions thrown
In most cases, only the basic error, KameleoonException, needs to be handled, as demonstrated in the example. Sin embargo, if different types of errors require a response, handle each one separately based on specific requirements. Adicionalmente, for enhanced reliability, general language errors can be handled by including Error.

getDataFile()

To evaluate all feature flags, use getVariations(). This method is more efficient than calling DataFile and iterating through flags with getVariation().
Returns the current SDK configuration as a DataFile object.
Return value

Datos del visitante

getVisitorCode()

The getVisitorCode method retrieves a código de visitante from the request’s cookie in the headers. If the código de visitante does not exist, the method generates a new random código de visitante, or uses a provided defaultVisitorCode value. It then sets the new código de visitante in a cookie in the response headers. This method utilizes Node.js’s native types for request and response, specifically IncomingMessage and ServerResponse, imported from the http module. Sin embargo, if you’re using the Express framework, Deno, or Next.js super server-rendering methods, like getServerProps, the types for request and response will differ. You can resolve this issue using type casting, which will yield identical results.
When using getVisitorCode() with Deno, Next.js SSR, Node, or Express, ensure that you’ve implemented the correct external dependencies.
The getVisitorCode() method allows you to set simulated variations for a visitor. When cookies (from a request or document) contain the key kameleoonSimulationFFData, the standard evaluation process is bypassed. Instead, the method directly returns a Variation based on the provided data.You can apply simulations in two ways:
  • Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
  • Manually: Set 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 to an individual experiment.
⚙️ Manual setupPlease ensure the kameleoonSimulationFFData cookie follows this format:
  • kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates the variation with varId of experiment expId for the given featureKey.
  • kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined in the Then, for everyone else in Production, serve section) for the given featureKey.
⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method como por ejemplo encodeURIComponent.
Argumentos
The parameters object is overloaded with two types:
  • Type GetVisitorCodeParametersType (for NodeJS/Express/NextJS SSR methods), containing lo siguiente fields:
  • Type GetNextJSVisitorCodeParametersType (for NextJS SSR server actions), containing lo siguiente fields:
  • Type GetDenoVisitorCodeParametersType (for Deno), containing lo siguiente fields:
  • Type GetCustomVisitorCodeParametersType (for custom VisitorCodeManager implementation), containing lo siguiente fields:
If you don’t provide a defaultVisitorCode and there is no código de visitante stored in a cookie, the código de visitante will be randomly generated.
Return value
Exceptions thrown

addData()

Use the addData() method to add targeting data to storage so other methods can utilize this information to determine whether to target the current visitor. The addData() method does not return any value, and does not directly interact with the Kameleoon back-end servers. Instead, all data the method collects is saved for future transmission using the flush() method. This approach minimizes the number of server calls, as data is generally grouped into a single server call that is activated by the flush() method. Adicionalmente, the trackConversion() method transmits any previously associated data. The getFeatureFlagVariationKey() and getFeatureFlagVariable() methods transmit data when an experimentation rule is triggered.
Each visitor can only have one instance of associated data for most data types; however, CustomData is an exception, as visitors can have one instance of associated CustomData for each customDataIndex.
Check the list of supported conditions to see the data types you can use for targeting.
Argumentos
  • kameleoonData is a variadic argument: it can be passed as one or several arguments (see the example).
  • The datos personalizados’s index or ID can be found in your Kameleoon account. Tenga en cuenta que this index starts at 0, meaning the first datos personalizados you create for a given site will be assigned 0 as its ID, rather than 1.
Exceptions thrown
Check the data types reference for more details on how to manage different data types.

flush()

flush() takes the Kameleoon data associated with the visitor and schedules the data to be sent with the next solicitud de seguimiento. The time of the next solicitud de seguimiento is defined in the SDK Configuration’s trackingInterval parameter. You can add datos del visitante using the addData() and getRemoteVisitorData() methods.The SDK will send all of its stored data to the remote Kameleoon servers if you don’t specify a visitorCode. Adicionalmente, if there were any solicitudes de seguimiento that previously failed and were stored locally in offline mode, the SDK will attempt to send those stored requests before processing the latest request.
If you need to send solicitudes de seguimiento immediately, use flushInstant() — the asynchronous version of flush that returns Promise<void>. You can await it when you need delivery guarantees (for example, before ending a request/response cycle), or call it without await as a fire-and-forget request:
  • await client.flushInstant(visitorCode) sends solicitudes de seguimiento immediately for a specific visitor and waits for completion
  • await client.flushInstant() sends solicitudes de seguimiento immediately for all visitors and waits for completion
Argumentos
Or an object with the type FlushParamsType, containing:
Exceptions thrown

getRemoteData()

The getRemoteData() method retrieves data that is stored on a remote Kameleoon server for a specified site code. For instance, you can use this method to access user preferences, historical data, or any other information pertinent to your application’s logic. By storing this data on our highly scalable servers using our Data API, you can efficiently manage large volumes of data and retrieve it for each of your visitors or users.
Argumentos
Return value
Exceptions thrown

getRemoteVisitorData()

The getRemoteVisitorData() method is an asynchronous function that retrieves Kameleoon Visits Data for a specific visitorCode from the Kameleoon Data API. This method stores the data so that it can be accessed when making targeting decisions.The data obtained through this method is crucial when you want to:
  • Access data collected from multiple devices.
  • Review a user’s history, including pages visited during previous sessions.
  • Utilize client-side data, como por ejemplo data layer variables and goals that are only applicable on the front end.
For a better understanding of potential use cases, please read this article.
By default, getRemoteVisitorData() retrieves the latest stored datos personalizados with scope=Visitor and attaches it to the visitor without the need to call the method addData(). This feature is particularly useful for synchronizing datos personalizados across multiple devices.
Argumentos
An object with the type RemoteVisitorDataParamsType, containing:
Return value
Exceptions thrown
Using parameters in getRemoteVisitorData()
The getRemoteVisitorData() method provides flexibility by letting you define various parameters when retrieving datos del visitante. This method can target data based on goals, experiments, or variations, and the same approach applies to all data types.Por ejemplo, if you want to retrieve data on visitors who completed the goal “Order transaction,” you can specify parameters in the getRemoteVisitorData() method to refine your targeting. If you’re interested in users who converted on the goal during their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.The flexibility shown in this example is not limited to goal data. You can use parameters within the getRemoteVisitorData() method to retrieve data on a variety of visitor behaviors.
Here is the list of available VisitorDataFiltersType filters:

getVisitorWarehouseAudience()

The getVisitorWarehouseAudience method is asynchronous and retrieves all audience data related to a visitor from your data warehouse. To use this method, you’ll need to provide a visitorCode and a warehouseKey, which typically correspond to your internal user ID. The customDataIndex parameter refers to the datos personalizados Kameleoon uses to target your visitors. For more details, refer to the warehouse targeting documentation.
Argumentos
Parameters object consisting of:
Return value
Exceptions thrown

setLegalConsent()

When handling legal consent, it’s important you use the getVisitorCode method from the KameleoonClient class, rather than the deprecated method from KameleoonUtils. Tenga en cuenta que this method does not require the domain as an argument. Instead, you should pass the domain to the KameleoonClient constructor. Refer to the example above for clarification.
The method setLegalConsent determines whether a visitor has provided legal consent for their personal data’s use. If you set the legalConsent parameter to false, it restricts the types of data you can include in solicitudes de seguimiento. This measure ensures that you comply with legal and regulatory requirements while responsibly managing datos del visitante. For more information on personal data, refer to the consent management policy.
Argumentos
The parameters object is overloaded with lo siguiente types:
  • Type SetLegalConsentParametersType (for NodeJS/Express/NextJS SSR methods), containing lo siguiente fields:
  • Type SetNextJSLegalConsentParametersType (for NextJS SSR server actions), containing lo siguiente fields:
  • Type SetDenoLegalConsentParametersType (for Deno), containing lo siguiente fields:
  • Type SetCustomLegalConsentParametersType (for custom VisitorCodeManager implementation), containing lo siguiente fields:
Exceptions thrown
Consent revocation behavior
When you call setLegalConsent() with consent=false, the SDK does not delete the kameleoonVisitorCode cookie. Instead, it stops extending the cookie’s expiration date, allowing the cookie to persist until it naturally expires. If your compliance requirements demand the immediate removal of the cookie file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK will not remove the file automatically.

Objetivos y analítica de terceros

trackConversion()

  • 📨 Sends Tracking Data to Kameleoon
Use this method to track a conversion for a specific goal and user. This method requires visitorCode and goalId. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitorCode is usually identical to the one that was used when triggering the experiment.The trackConversion() method doesn’t return any value. This method is non-blocking as the server call is made asynchronously.
Argumentos
Parameters object consisting of:
metadata values are accessible through raw data exports and the results page.If the metadata parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the addData() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.In the example below, Kameleoon will associate the conversion only with the datos personalizados value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).
Exceptions thrown

getEngineTrackingCode()

Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the getEngineTrackingCode() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration. Refer to hybrid experimentation for more information on implementing this method.
  • To use this feature, implement both the NodeJS SDK and Kameleoon Engine.js. Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing </body> tag.
  • You can insert the returned tracking code directly into an HTML <script> tag.
En este ejemplo, 123456 and 234567 are experiment IDs, and 7890 and 8901 are variation IDs. In your implementation, the SDK generates these values in the returned tracking code.
Argumentos
Return value
Exceptions thrown

Eventos

onEvent()

The onEvent() method fires a callback when a specific event is triggered. The callback function accesses the data associated with the event. The SDK methods in this documentation note which event types they trigger, if any.
You can only assign one callback to each EventType.
Events
Events are defined in the EventType enum. The eventData parameter will have a different type based on the event type.
Argumentos
Exceptions thrown

Tipos de datos

Kameleoon Data types are helper classes used for storing data in predefined forms. During the flush() execution, the SDK collects all data and sends it along with the solicitud de seguimiento. Data available in the SDK is not available for targeting and reporting in the Kameleoon app until you add the data (for example, by using the addData() method). See use visit history to target users for more information.
If you are using Kameleoon in hybrid mode, you can call getRemoteVisitorData() to automatically fill all data that Kameleoon previously collected.

Browser

Browser contains browser information.
Each visitor can only have one Browser. Adding a second Browser overwrites the first one.

UniqueIdentifier

UniqueIdentifier data is used for unique visitor identification. If you add UniqueIdentifier for a visitor, visitorCode is used as the unique visitor identifier, which is useful for Cross-device experimentation. Linking a UniqueIdentifier to a visitor informs the SDK that this visitor is associated with another visitor. The UniqueIdentifier parameter can be beneficial in certain edge cases. Por ejemplo, if you can’t access the anonymous visitorCode initially assigned to a visitor but 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.

Conversion

The Conversion data set stored here can be used to filter experiment and personalization reports by any goal associated with it.
  • Each visitor can have multiple Conversion objects.
  • You can find the goalId in the Kameleoon app.
ConversionParametersType conversionParameters - an object with conversion parameters described below
Cookie contains information about the cookie stored on the visitor’s device. The NodeJS SDK doesn’t require a request or response to extract the cookie. Instead, add the cookie manually using Cookie data.
Each visitor can only have one Cookie. Adding a second Cookie overwrites the first one.
Methods
Cookie data has a static utility method, fromString, that can help you create a cookie by parsing a string that contains valid cookie data. The method accepts string as a parameter, and returns an initialized Cookie instance.

GeolocationData

GeolocationData contains the visitor’s geolocation details.
Each visitor can only have one GeolocationData. Adding a second GeolocationData overwrites the first one.
An object parameter with the type GeolocationInfoType contains lo siguiente fields:

CustomData

CustomData allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports. To learn more about datos personalizados, please refer to this article. To maintain the datos personalizados in future visits, the SDK sends CustomData with the Visitor scope with the next solicitud de seguimiento. You can set the scope in the datos personalizados dashboard.
  • Each visitor is allowed only one CustomData for each unique index. Adding another CustomData with the same index will replace the existing one.
  • The datos personalizados ‘index’ can be found in the Custom Data dashboard under the “INDEX” column.
  • To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: Use this data only locally for targeting purposes when creating datos personalizados.
  • Adding a CustomData instance created with a name when the SDK instance is not initialized or the name is not registered, will result in the data being ignored.

Device

Device contains information about your device.
Each visitor can only have one Device. Adding a second Device overwrites the first one.

OperatingSystem

OperatingSystem contains information about the visitor’s operating system.
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.

PageView

PageView contains information about your web page.
Each visitor can have one PageView per unique URL. Adding a PageView with the same URL notifies the SDK that the visitor revisited the page.
PageViewParametersType pageViewParameters - an object with page view parameters described below
You can find the referrer’s index or ID in your Kameleoon account. Tenga en cuenta que this index starts at 0, meaning the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.

UserAgent

UserAgent stores information on the visitor’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 and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on bot filtering. If you use internal bots, we suggest you pass the value curl/8.0 of the userAgent to exclude them from our analytics.
A visitor can only have one UserAgent. Adding a second UserAgent overwrites the first one.
Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. We recommend that you pass the user agent to be filtered by Kameleoon when running server-side experiments for each visitor browsing your website, to avoid counting bots in your analytics.If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.

ApplicationVersion

ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.

Tipos devueltos

DataFile

The DataFile contains the SDK configuration details. It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

FeatureFlag

The FeatureFlag represents a set of properties that define a feature flag itself — for example, its Variations, Rules, environment status, and other related details. It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

Rule

The Rule represents a set of properties that define a rule itself — for example, its Variations. It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

Variation

Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
  • Ensure that your code handles the case where id or experimentId may be null, indicating a default variation.
  • The variables map might be empty if no variables are associated with the variation.

Variable

Variable contains information about a variable associated with the assigned variation.

Edge helpers

These helper methods are primarily intended for short-lived or edge-style runtimes where the SDK may need explicit revalidation between requests.

refreshDataFileIfStale()

The refreshDataFileIfStale() method triggers a data file revalidation only when the current configuration is stale. If the data file is still valid and the last update happened less than the configured updateInterval ago, the method returns false and no update request is made. If the data file is stale, the method waits for the revalidation request to finish and returns true when the request was performed. Returning true means that the check was executed, but the configuration itself may still remain unchanged, for example when the server reports that the current data file is already up to date.
In a typical long-lived Node.js runtime, using this method is generally not recommended, because the SDK already keeps the data file fresh automatically during initialization and normal runtime execution. It can still be helpful in edge-style environments como por ejemplo Cloudflare Workers, where runtime behavior is more short-lived and revalidation may need to be triggered explicitly.
Return value

Métodos obsoletos

These methods are deprecated and will be removed in the next major update.

getFeatureFlagVariationKey()

Use the getVariation method instead.
The getFeatureFlagVariationKey() method retrieves the variation key for the specified visitorCode in the corresponding feature flag. This method includes a targeting check, finding the appropriate variation exposed to the visitor, saving it to storage, and sending a solicitud de seguimiento.
If a user has not been previously assigned a variation key for the feature flag, the SDK will randomly determine a variation based on the feature flag’s rules. If the user is already linked to the feature flag, the SDK will return their previously assigned variation key. If the user does not meet any of the specified rules, the default value defined in Kameleoon’s feature flag delivery rules will be returned. This default value is not always a variation key—it can also be a boolean or another data type, depending on the feature flag’s configuration.
Argumentos
Return value
Exceptions thrown

getVisitorFeatureFlags()

Use the getVariations method instead.
The getVisitorFeatureFlags() method returns a list of feature flags that are active for the visitor with the specified visitorCode, ensuring that the visitor is allocated one of the variations.
  • 🚫 Doesn’t send Tracking Data to Kameleoon
  • 🎯 Events: EventType.Evaluation (for each feature flag)
This method only collects the visitor’s active feature flags, meaning the result excludes all feature flags for which the visitor is assigned the off (default or control) variation.Por ejemplo:
Use getFeatureFlags when you need all of the visitor’s feature flags:
Argumentos
Return value
Exceptions thrown

getActiveFeatureFlags()

  • 🚫 Doesn’t send Tracking Data to Kameleoon
  • 🎯 Events: EventType.Evaluation (for each feature flag)
Use the getVariations method instead.
The getActiveFeatureFlags() method returns a Map, where the key represents the feature key, and the value contains detailed information about the visitor’s variation and its variables.
This method only collects the visitor’s active feature flags, meaning the result excludes all feature flags for which the visitor is assigned the off (default or control) variation.See the getVisitorFeatureFlags method’s CAUTION section for more details.
Argumentos
Return value
Exceptions thrown

getFeatureFlagVariable()

Use the getVariation method instead.
The getFeatureFlagVariable() method retrieves a variable for the visitor based on the visitorCode within the identified feature flag. This method includes a targeting check, determines the appropriate variation for the visitor, saves it to storage, and sends a solicitud de seguimiento.
Argumentos
Parameters object of type GetFeatureFlagVariableParamsType containing lo siguiente fields:
Return value
Exceptions thrown

getFeatureFlagVariables()

Use the getVariation method instead.
The getFeatureFlagVariables() method retrieves a list of variable values for a specified visitor and feature flag. This method checks if the user is targeted, identifies the visitor’s assigned variation, stores it, and sends a solicitud de seguimiento.
Argumentos
Return value
Exceptions thrown

onConfigurationUpdate()

Use the onEvent method with EventType.ConfigurationUpdate instead.
The onConfigurationUpdate() method fires a callback upon client configuration update.
This method is only applicable to server-sent events for real-time updates.
Argumentos
Exceptions thrown

getFeatureFlags()

Use the getDataFile() method instead.
🚫 Doesn’t send Tracking Data to Kameleoon The getFeatureFlags() method retrieves a list of feature flags that are stored in the client configuration.
Return value
Exceptions thrown