Personalize
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.
Notes:
- When you pass tags, the SDK requests only experiences that carry at least one matching tag (OR semantics).
- Unmatched experiences are excluded before audience evaluation.
- Tag matching is case-insensitive, and you can specify a maximum of 10 tags per request.
- See Working with Experience Tags for usage patterns.
| Name | Type | Description |
|---|---|---|
| projectUid | string | The personalize project UID. |
| options | InitOptions | Options for initialization. |
// Basic initialization
const personalizeSdk = await Personalize.init(projectUid, { request });
// With experience tag filtering
const personalizeSdk = await Personalize.init(projectUid, { request, tags: ['env:production'] });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. |
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.
Warning The use of getExperiences() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the getExperiences() method within the SDK instance. For more details, refer to getExperiences() with an SDK Instance.
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.
Warning The use of triggerImpression() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the triggerImpression() method within the SDK instance. 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. |
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.
Warning The use of triggerImpressions() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the triggerImpressions() method within the SDK instance. 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. |
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.
Warning The use of triggerEvent() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the triggerEvent() method within the SDK instance. For more details, refer to triggerEvent() with an SDK Instance.
| Name | Type | Description |
|---|---|---|
| eventKey | string | Key for the event in Personalize. |
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.
Warning The use of set() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the set() method within the SDK instance. 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. |
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.
Warning The use of setUserId() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the setUserId() method within the SDK instance. 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. |
await Personalize.setUserId(newUserId, { preserveUserAttributes: true });getUserId
The getUserId() method retrieves the current user ID.
Warning The use of getUserId() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the getUserId() method within the SDK instance. For more details, refer to getUserId() with an SDK Instance.
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.
Warning The use of getActiveVariant() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the getActiveVariant() method within the SDK instance. 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. |
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.
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.
Warning The use of addStateToResponse() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the addStateToResponse() method within the SDK instance. 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. |
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.
Warning The use of getVariants() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the getVariants() method within the SDK instance. For more details, refer to getVariants() with an SDK Instance.
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.
Warning The use of getVariantAliases() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the getVariantAliases() method within the SDK instance. For more details, refer to getVariantAliases() with an SDK Instance.
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.
Warning The use of getVariantParam() as a global function in the global Personalize namespace is deprecated. To ensure compatibility and future support, initialize the SDK and use the getVariantParam() method within the SDK instance. For more details, refer to getVariantParam() with an SDK Instance.
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(). |
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.
Warning The use of reset() in the global Personalize namespace is deprecated. As part of the transition to use the SDK instance, Personalize.reset() is no longer required and will be removed in a future release.
await Personalize.init(projectUid); Personalize.getUserId(); // returns a random user ID Personalize.reset(); Personalize.getUserId(); // returns `undefined`