cs-icon.svg

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.

Returns:
Type
Promise<Sdk>
NameTypeDescription

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

Returns:
Type
void
NameTypeDescription

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.

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.
Returns:
Type
ManifestExperience

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.

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.
Returns:
Type
Promise<void>
NameTypeDescription

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.

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.
Returns:
Type
Promise<void>
NameTypeDescription

triggerImpressionOptions

TriggerImpressionOptions

A Javascript object containing either experienceShortUids or aliases. Trigger impressions with either Experience Short UIDs or Variant Aliases.

Example:

const experienceShortUid = 'a';
await personalizeSdk.triggerImpression(experienceShortUid);

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.
Returns:
Type
Promise<void>
NameTypeDescription

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.

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.
Returns:
Type
Promise<void>
NameTypeDescription

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.

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.
Returns:
Type
Promise<void>
NameTypeDescription

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.

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.
Returns:
Type
string | undefined

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.

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.
Returns:
Type
string | null
NameTypeDescription

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.

Returns:
Type
InitializationStatus

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.

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.
Returns:
Type
Promise<void>
NameTypeDescription

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.

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.
Returns:
Type
Record<string, string>

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.

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.
Returns:
Type
string[]

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.

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.
Returns:
Type
string

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.

Returns:
Type
string[]
NameTypeDescription

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.

Warning: The use of reset() method 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.

Returns:
Type
void

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.

Returns:
Type
ManifestExperience

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.

Returns:
Type
Promise<void>
NameTypeDescription

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.

Returns:
Type
Promise<void>
NameTypeDescription

triggerImpressionOptions

TriggerImpressionOptions

A Javascript object containing either experienceShortUids or aliases. Trigger impressions with either Experience Short UIDs or Variant Aliases.

Example:

const experienceShortUid = 'a';
await personalizeSdk.triggerImpression(experienceShortUid);

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.

Returns:
Type
Promise<void>
NameTypeDescription

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.

Returns:
Type
Promise<void>
NameTypeDescription

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.

Returns:
Type
Promise<void>
NameTypeDescription

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.

Returns:
Type
string | undefined

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.

Returns:
Type
string | null
NameTypeDescription

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.

Returns:
Type
Promise<void>
NameTypeDescription

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.

Returns:
Type
Record<string, string>

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.

Returns:
Type
string[]

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.

Returns:
Type
string

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.

Returns:
Type
string[]
NameTypeDescription

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.

NameTypeDescription

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

NameTypeDescription

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

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.

NameTypeDescription

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

NameTypeDescription

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 TriggerImpressionOptions type alias defines the structure of the argument passed to the TriggerImpressionOptions method.

NameTypeDescription

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.