JavaScript Personalize Edge SDK API Reference
The JavaScript Edge SDK allows real-time content personalization across websites powered by Contentstack, mobile applications using React Native, and server-side environments such as Node.js.
Additional Resources: To know more about the Personalize Edge SDK, refer to our About Personalize Edge SDK and Get Started with Personalize Edge SDK documentation.
Personalize
With Personalize, you can create and manage audiences, define audience attributes, and develop tailored experiences for your users. You can then create personalized content for these experiences in the CMS using Variants. This SDK wraps around our Edge API and enables you to retrieve a user’s active variants and deliver real-time personalized content based on user demographics, behavior, and preferences.
Note: To configure a different Contentstack region, call the setEdgeApiUrl method before init(). By default, the SDK will attempt to initialize using the AWS NA region.
init
The init() method initializes the SDK and must be called and awaited before use. It requests the Personalize Edge Manifest API and returns a promise that resolves to an SDK instance containing the current user's context, including active variants. This instance provides access to SDK features such as setting attributes, triggering events, and fetching variants.
In browsers, if a manifest cookie exists (e.g., set by the addStateToResponse() method), the SDK bypasses the network request and uses the cookie.
Name | Type | Description |
---|---|---|
projectUid | string | The personalize project UID. |
options | InitOptions | Options for initialization options. |
Example:
const personalizeSdk = await Personalize.init(projectUid, { request });
setEdgeApiUrl
The setEdgeApiUrl() method configures the Edge API URL, especially when directing the SDK to a different Contentstack region. By default, the SDK will attempt to initialize using the AWS NA region. Invoke this method before initializing the SDK to ensure the configuration is applied. Refer to our documentation to find your region-specific base URL
Name | Type | Description |
---|---|---|
edgeApiUrl | string | The region-specific endpoint used to optimize SDK performance. |
Example:
Personalize.setEdgeApiUrl('https://eu-personalize-edge.contentstack.com'); const personalizeSdk = await Personalize.init(projectUid);
getExperiences
The getExperiences() method retrieves a list of experiences, each linked to its active variant's short UID. For inactive experiences, activeVariantShortUid will return null. The list is sorted by experience priority in decreasing order.
For more details, refer to getExperiences() with an SDK Instance.
Example:
Personalize.getExperiences(); // [{shortUid: 'a', activeVariantShortUid: '0'}]
triggerImpression
The triggerImpression() method records an impression for a specified experience and sends it for the active variant as defined in the current user’s manifest. Use this method whenever an experience is displayed to the user.
For more details, refer to triggerImpression() with an SDK Instance.
Name | Type | Description |
---|---|---|
experienceShortUid | string | The unique identifier of the experience for which the impression is to be triggered. |
Example:
const experienceShortUid = 'a'; await Personalize.triggerImpression(experienceShortUid);
triggerImpressions
The triggerImpressions() method triggers multiple impressions for the given input. If provided with Experience Short UIDs, the impression is sent for the corresponding active variants in the manifest. If provided with Variant Aliases instead, it will use the Experience Short UID and Variant Short UID in the alias to trigger impressions, without referring to the manifest.
For more details, refer to triggerImpressions() with an SDK Instance.
Name | Type | Description |
---|---|---|
triggerImpressionOptions | TriggerImpressionOptions | A Javascript object containing either experienceShortUids or aliases. Trigger impressions with either Experience Short UIDs or Variant Aliases. |
Example:
const experienceShortUids = ['a', 'b']; await Personalize.triggerImpressions({ experienceShortUids }); await Personalize.triggerImpressions({ aliases: ['cs_personalize_a_0', 'cs_personalize_b_1'] });
triggerEvent
The triggerEvent() method records significant user actions, such as clicking a CTA or scrolling to the end of a page, by passing an eventKey—a unique identifier defined in the Personalize Events module. This allows tracking conversions, analyzing user behavior, and measuring A/B test outcomes.
For more details, refer to triggerEvent() with an SDK Instance.
Name | Type | Description |
---|---|---|
eventKey | string | Key for the event in Personalize |
Example:
await Personalize.triggerEvent('clickCTA');
set
The set() method allows you to define user attributes as key-value pairs representing user traits. To use these attributes, create them with matching keys in the Personalize Attributes module.
For more details, refer to set() with an SDK Instance.
Name | Type | Description |
---|---|---|
clientAttributes | ClientAttributes | An object representing key-value pairs to define user traits, set on the client. |
Example:
await Personalize.set({ age: 20 });
setUserId
The setUserId() method allows assigning a custom, externally managed user ID to the current user, overriding the automatically generated ID created during the SDK's first initialization. This is useful for scenarios like when an anonymous user logs in.
If you want to retain previously tracked user attributes after assigning a new user ID, use the preserveUserAttributes option, which merges the current user's attributes into the new ID. In browser environments, this method sets a cookie (cs-personalize-user-id) to persist the user ID across sessions.
Note: You can call this method either before or after initializing the SDK.
For more details, refer to setUserId() with an SDK Instance.
Name | Type | Description |
---|---|---|
userId | string | The new user ID for the current user. |
options | SetUserIdOptions | Pass options to preserve user attributes. |
Example:
await Personalize.setUserId(newUserId, { preserveUserAttributes: true });
getUserId
The getUserId() method retrieves the current user ID.
For more details, refer to getUserId() with an SDK Instance.
Example:
const userId = Personalize.getUserId();
getActiveVariant
The getActiveVariant() method returns the short UID of the active variant for a specified experience, identified by its short UID. It returns null if the experience is not active or there are no variants active for the user.
For more details, refer to getActiveVariant() with an SDK Instance.
Name | Type | Description |
---|---|---|
experienceShortUid | string | The unique identifier for an experience, available in the Personalize Experiences page or through a variant alias. |
Example:
const activeVariant = Personalize.getActiveVariant(experienceShortUid);
getInitializationStatus
The getInitializationStatus() method provides the current status of SDK initialization. The status transitions to initializing when the SDK starts initializing, updates to success upon completion, and changes to error if an issue occurs.
Note: Use this method to verify that the SDK has been fully initialized before calling other SDK methods.
Example:
const initializationPromise = Personalize.init(projectUid); Personalize.getInitializationStatus(); // `initializing`. await initializationPromise; Personalize.getInitializationStatus(); // `success`
addStateToResponse
The addStateToResponse() helper method appends user state information, including the user ID and current manifest, as set-cookie headers to the provided response object. This method is typically used in edge functions to efficiently manage user state tracking.
By using this approach, the Personalize SDK can initialize in the browser without needing a network call to retrieve the manifest.
For more details, refer to addStateToResponse() with an SDK Instance.
Name | Type | Description |
---|---|---|
response | Response | A standard web response object used to append set-cookie headers for managing user state. |
Example:
await Personalize.addStateToResponse(response);
getVariants
The getVariants() method retrieves the active variants as key-value pairs, where the keys are experience short UIDs and the values are variant short UIDs. For inactive experiences, the values will be null.
For more details, refer to getVariants() with an SDK Instance.
Example:
Personalize.getVariants(); // {a: 0, b: 1}
getVariantAliases
The getVariantAliases() method retrieves a list of active experiences represented as variant aliases. These aliases are used by Personalize to identify CMS variants and can be passed to the CMS Delivery API to fetch personalized content entries.
The list is ordered by priority, with higher-priority variants appearing earlier.
For more details, refer to getVariantAliases() with an SDK Instance.
Example:
Personalize.getVariantAliases(); // ['cs_personalize_a_0', 'cs_personalize_b_1']
getVariantParam
The getVariantParam() method returns an opaque variant parameter, formatted as a comma-separated list of active experience and variant short UIDs. This parameter is designed to be easily included in a URL as a query parameter, enabling the transfer of the active variants for the current user.
This method is commonly used in edge functions to streamline the handling of variant information.
For more details, refer to getVariantParam() with an SDK Instance.
Example:
Personalize.getVariantParam(); // 'a_0,b_1'
variantParamToVariantAliases
The variantParamToVariantAliases() method decodes a variant parameter into a list of variant aliases. This parameter, often used as a query parameter in URLs, represents the variants activated for the current user.
This method is typically used in server-side code to transform the variant parameter into a list of aliases, which can then be passed to the CMS Delivery API for fetching personalized content.
Name | Type | Description |
---|---|---|
variantParam | string | The variant param generated by Personalize.getVariantParam() |
Example:
const variantParam = Personalize.getVariantParam(); // 'a_0,b_1' Personalize.variantParamToVariantAliases(variantParam); // ['cs_personalize_a_0', 'cs_personalize_b_1']
reset
The reset() method reverts the SDK to its original state by performing the following actions:
- Deletes the manifest.
- Clears the user ID.
- Removes any associated cookies in browser environments.
This method ensures a clean slate for the SDK's operation.
Example:
await Personalize.init(projectUid); Personalize.getUserId(); // returns a random user ID Personalize.reset(); Personalize.getUserId(); // returns `undefined`
SDK
The SDK class contains the primary functionality of the SDK. An instance of this SDK class is created and returned when you call Personalize.init
getExperiences
The getExperiences() method retrieves a list of experiences, each linked to its active variant's short UID. For inactive experiences, activeVariantShortUid will return null. The list is sorted by experience priority in decreasing order.
Example:
personalizeSdk.getExperiences(); // [{shortUid: 'a', activeVariantShortUid: '0'}]
triggerImpression
The triggerImpression() method records an impression for a specified experience and associates it with the active variant defined in the current user’s manifest. Use this method whenever an experience is displayed to the user to ensure accurate tracking.
Name | Type | Description |
---|---|---|
experienceShortUid | string | The unique identifier of the experience for which the impression is to be recorded. |
Example:
const experienceShortUid = 'a'; await personalizeSdk.triggerImpression(experienceShortUid);
triggerImpressions
The triggerImpressions() method triggers multiple impressions for the given input. If provided with Experience Short UIDs, the impression is sent for the corresponding active variants in the manifest. If provided with Variant Aliases instead, it will use the Experience Short UID and Variant Short UID in the alias to trigger impressions, without referring to the manifest.
Name | Type | Description |
---|---|---|
triggerImpressionOptions | TriggerImpressionOptions | A Javascript object containing either experienceShortUids or aliases. Trigger impressions with either Experience Short UIDs or Variant Aliases. |
Example:
const experienceShortUids = ['a', 'b']; await personalizeSdk.triggerImpressions({ experienceShortUids }); await personalizeSdk.triggerImpressions({ aliases: ['cs_personalize_a_0', 'cs_personalize_b_1'] });
triggerEvent
The triggerEvent() method records important user actions, such as clicking a CTA or scrolling to the end of a page. It requires an eventKey a unique identifier defined in the Personalize Events module, to track conversions, analyze user behavior, and measure A/B test outcomes.
Name | Type | Description |
---|---|---|
eventKey | string | The unique key for the event in Personalize. |
Example:
await personalizeSdk.triggerEvent('clickCTA');
set
The set() method allows you to define user attributes as key-value pairs representing user traits. To use these attributes, ensure that matching keys are created in the Personalize Attributes module. Setting user attributes is an async operation, as they are sent to Personalize’s edge network using the Edge API.
Name | Type | Description |
---|---|---|
clientAttributes | ClientAttributes | An object containing key-value pairs that define user traits on the client. |
Example:
await personalizeSdk.set({ age: 20 });
setUserId
The setUserId() method allows assigning a custom, externally managed user ID to the current user, overriding the automatically generated ID created during the SDK's first initialization. This is useful for scenarios like when an anonymous user logs in.
If you want to retain previously tracked user attributes after assigning a new user ID, use the preserveUserAttributes option, which merges the current user's attributes into the new ID. In browser environments, this method sets a cookie (cs-personalize-user-id) to persist the user ID across sessions.
Note: You can call this method either before or after initializing the SDK.
Name | Type | Description |
---|---|---|
userId | string | The new user ID for the current user. |
options | SetUserIdOptions | To retain previously tracked user data. |
Example:
await personalizeSdk.setUserId(newUserId, { preserveUserAttributes: true });
getUserId
The getUserId() method retrieves the current user ID.
Example:
const userId = personalizeSdk.getUserId();
getActiveVariant
The getActiveVariant() method returns the short UID of the active variant for a specified experience, identified by its short UID. It returns null if the experience is not active or there are no variants active for the user.
Name | Type | Description |
---|---|---|
experienceShortUid | string | The unique identifier for an experience, available in the Personalize Experiences page or through a variant alias. |
Example:
const activeVariant = personalizeSdk.getActiveVariant(experienceShortUid);
addStateToResponse
The addStateToResponse() helper method appends user state information, including the user ID and current manifest, as set-cookie headers to the provided response object. This method is typically used in Edge Functions to efficiently manage user state tracking.
By using this approach, the Personalize SDK can initialize in the browser without needing a network call to retrieve the manifest.
Name | Type | Description |
---|---|---|
response | Response | A standard web response object used to append set-cookie headers for managing user state. |
Example:
await personalizeSdk.addStateToResponse(response);
getVariants
The getVariants() method retrieves the active variants as key-value pairs, where the keys are experience short UIDs and the values are variant short UIDs. For inactive experiences, the values will be null.
Example:
personalizeSdk.getVariants(); // {a: 0, b: 1}
getVariantAliases
The getVariantAliases() method retrieves a list of active experiences represented as variant aliases. These aliases are used by Personalize to identify CMS variants and can be passed to the CMS Delivery API to fetch personalized content entries.
The list is ordered by priority, with higher-priority variants appearing earlier.
Example:
personalizeSdk.getVariantAliases(); // ['cs_personalize_a_0', 'cs_personalize_b_1']
getVariantParam
The getVariantParam() method returns an opaque variant parameter, formatted as a comma-separated list of active experience and variant short UIDs. This parameter is designed to be easily included in a URL as a query parameter, enabling the transfer of the active variants for the current user.
This method is commonly used in edge functions to streamline the handling of variant information.
Example:
personalizeSdk.getVariantParam(); // 'a_0,b_1'
variantParamToVariantAliases
The variantParamToVariantAliases() method decodes a variant parameter into a list of variant aliases. This parameter, often used as a query parameter in URLs, represents the variants activated for the current user.
This method is typically used in server-side code to transform the variant parameter into a list of aliases, which can then be passed to the CMS Delivery API for fetching personalized content.
Name | Type | Description |
---|---|---|
variantParam | string | The variant param generated by Personalize.getVariantParam() |
Example:
const variantParam = personalizeSdk.getVariantParam(); // 'a_0,b_1' personalizeSdk.variantParamToVariantAliases(variantParam); // ['cs_personalize_a_0', 'cs_personalize_b_1']
Types and Interfaces
The Types and Interfaces used and exported by the Personalize Edge SDK.
SetUserIdOptions
The SetUserIdOptions interface provides configuration options for the setUserId method.
Name | Type | Description |
---|---|---|
preserveUserAttributes | boolean | Set to true to merge user attributes from the current user. |
InitOptions
The InitOptions interface specifies configuration options for initializing the SDK. These options allow for customization during the setup process
Name | Type | Description |
---|---|---|
request | Request | A web-standard Request object used to track users and extract attributes like query parameters, referrer, and geolocation in edge functions. |
userId | string | The user ID to be explicitly assigned. |
customVariantQueryParam | string | Specifies a custom name for the variant query parameter |
liveAttributes | ClientAttributes | Specifies the custom attributes object to treat as live attributes. These attributes must be pre-configured in the Personalize project. |
ClientAttributes
The ClientAttributes type alias represents a collection of key-value pairs, where each key is an attribute key that you have defined in the Attributes module, and the corresponding value can be of the type expected by the audience rules.
ManifestExperience
The ManifestExperience type alias defines the structure of an experience within a personalization manifest.
Name | Type | Description |
---|---|---|
shortUid | string | The unique identifier for the experience. |
activeVariantShortUid | string | The unique identifier for the active variant associated with the experience; it can be null if no variant is active. |
Manifest
The Manifest type alias defines the structure of the personalization manifest
Name | Type | Description |
---|---|---|
activeVariants | string | A record mapping experience short UIDs to their corresponding active variant short UIDs |
experiences | ManifestExperience | An array of ManifestExperience objects, each representing an experience and its associated active variant. |
TriggerImpressionsOptions
The TriggerImpressionsOptions type alias defines the structure of the argument passed to the TriggerImpressionsOptions method.
Name | Type | Description |
---|---|---|
experienceShortUids | string[] | A list of Experience Short UIDs. The corresponding active variants are picked from the Manifest. |
aliases | string[] | A list of Variant Aliases. An alias consists of an Experience Short UID and a corresponding Variant Short UID. |
InitializationStatus
The InitializationStatus type alias defines in the Contentstack Personalize SDK represents the current state of the SDK's initialization process. It can have one of the following string values:
- initializing: Indicates that the SDK is in the process of initializing.
- success: Signifies that the SDK has successfully initialized.
- error: Denotes that an error occurred during the initialization.