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: Ensure the SDK is initialized before calling any methods other than init() and setEdgeApiUrl.

init

The init() method must be invoked and awaited before using any other SDK features (e.g., setting attributes, triggering events, or 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<void>
NameTypeDescription

projectUid

string

The personalize project UID

options

InitOptions

Options for initialization options

Example:

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');
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, with higher-priority experiences appearing first.

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.

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);

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 Management Console. This allows tracking conversions, analyzing user behavior, and measuring A/B test outcomes.

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 Management Console.

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.

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 getCurrentUserId() method retrieves the current user ID.

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.

Returns:
Type
string | null
NameTypeDescription

experienceShortUid

string

The unique identifier for an experience, available in the Personalize Management Console on the experience details 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.

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.

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.

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.

Returns:
Type
string

Example:

Personalize.getVariantParam(); // 'a_0,b_1'

VariantParamToAliases

The VariantParamToAliases() 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.

Returns:
Type
void

Example:

await Personalize.init(projectUid);
Personalize.getUserId(); // returns a random user ID
Personalize.reset();
Personalize.getUserId(); // returns `undefined`

Types and Interfaces

SetUserIdOptions

The SetUserIdOptions interface provides configuration options for the setUserId method.

NameTypeDescription

preserveUserAttributes

preserveUserAttributes

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 management console, 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.

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.