Context

Prev Next

“Context” refers to variables within XGen’s SDK that change the behavior of elements depending on the context in which they are in. For example, if you are on a “Shirts” category page you would want to show different products then if you were on a “Pants” category page. Context is used within element’s rulesets and can be used to change the merchandising rules for an element’s predictions. The context in this object will be applied when the page has been matched.

Functions within the context object can be async and will be awaited for before the primary XGen API is called. This will not affect what page is being matched since context runs after a page has been matched.

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

context: {
  key1: value1,
  key2: () => value2,
  key3: async () => await value3
}

Usage

In the context object pass in the name of the variable as the key. Then you can either set the item to the value you want to return, or set the item to a function that returns the value you want. The value must be a string.

Within rulesets, all contextual variables will have an xt_ prefix. This means if you have category as a key, you will need to use it as xt_category within the ruleset.

Example

context: {
  gender: 'male',
  category: () => {
    const urlSegments = location.pathname.split('/');
    const category = urlSegments.reverse().find(segment => segment !== '');
    return category;
  },
  microCategory: async () => {
    const response = await fetch('/microCategory').then(r => r.json);
    return response.microCategory;
  }

}

In this example, the variable xt_gender will be equivalent to 'male', xt_category will be the last segment of the URL, and xt_microCategory will be the value from that API that is called.