setContext()

Prev Next

setContext() is used to define a contextual variable. Contextual variables are key/value pairs that are used for XGen’s prediction APIs to change a ruleset/filter’s conditions. For example, you might have the rule 'pants' in product_categories. Instead of having to create a new rule for each category, you can replace 'pants' with the key xt_category (xt_ is the prefix for context). Then you can call setContext('category', 'pants') and 'pants' will be put in place of that variable.

The setContext() function prepends xt_ in front of every key that is passed in as this is a requirement for contextual variables.

Context must be configured prior to the prediction API being called. Otherwise, the contextual variables will not be included in the request.

Using contextual variables can increase the latency of the render API. For the best performance, try to limit the possible combinations of variables. For example a “gender” contextual variable will have 2 values and a category ruleset may have 50 values for example. That makes 100 possible combinations. The more variables you have and the more values they have, the worse the render API latency will get.

It is also recommended to remove any unused variables for this reason.

Syntax

setContext(key, value)

Parameters

key

type: string
description: The key that will be used for this contextual variable. Note: xt_ is prepended by default to the key as this is required for contextual variables.

value

type: string
description: The value that the key will be replaced with within the ruleset.

Return Value

This function has no return value.

Examples

Set the Category context

In this example, we are setting the category variable to the value 'pants' so you will be able to use xt_category within the ruleset.

// Create integration (use existing integration if you already created one)
const integration = new XG(...config);

// Get the category
const category = window.productCategory;

// Save the category as a contextual variable
integration.setContext('category', category);