@xgenai/sdk-core
v1.6.6
Published
A core package for the XGen SDK that provides functionality for interacting with the XGen API.
Readme
XGen Ai JavaScript SDK Core Package
Official JavaScript SDK Core Package (browser and node) for interacting with the XGen API.
Installation
Browser (manually via script tag)
<script src="/path/to/dist/sdk-core.umd.cjs"></script>
<script type="text/javascript">
const xg = new XGenClient({
//params
})
...
</script>OR if you are using ES modules:
<script type="module">
import XGenClient from '/path/to/dist/sdk-core.js'
const xg = new XGenClient({
//params
})
...
</script>Node.js (via npm)
npm install @xgenai/sdk-core --save// Using ES modules (default)
import XGenClient from '@xgenai/sdk-core';
// OR if you are using CommonJS modules
const XGenClient = require('@xgenai/sdk-core');🔧 For Node < 17 you'll need to load a
fetch()polyfill. We recommend lquixada/cross-fetch:// npm install cross-fetch --save import 'cross-fetch/polyfill';
Usage
import XGenClient from '@xgenai/sdk-core';
const xg = new XGenClient({
key: '<your_api_key>',
secret: '<your_api_secret>',
clientId: '<your_client_id>',
trackerId: '<your_tracker_id>',
getEnv: 'stage', //optional: 'stage' or 'prod' or a function that returns the environment (`stage` or `prod`)
authStore: new LocalCookieAuthStore(), //default - can pass in a custom auth store instance
});
// get recommendations by element id
const result = await xg.recommend.getResultsById({ elementId: '<element_id>' });
// and much more...More detailed API docs and copy-paste examples could be found in the API documentation for each service.
Extras
Error handling
All services return a standard Promise-based response, so the error handling is straightforward:
xg.recommend
.getResultsById({ elementId: '<element_id>' })
.then((result) => {
// success...
console.log('Result:', result);
})
.catch((error) => {
// error...
console.log('Error:', error);
});
// OR if you are using the async/await syntax:
try {
const result = xg.recommend.getResultsById({ elementId: '<element_id>' });
console.log('Result:', result);
} catch (error) {
console.log('Error:', error);
}The response error is normalized and always returned as ResponseError object with the following public fields that you could use:
ResponseError {
url: string, // requested url
status: number, // response status code
response: { ... }, // the API JSON error response
isAbort: boolean, // is abort/cancellation error
originalError: Error|null, // the original non-normalized error
}Auth store
The SDK keeps track of the authenticated token and auth model for you via the xg.authStore instance.
LocalCookieAuthStore (default)
The default LocalCookieAuthStore uses the browser's document.cookie storage if available, otherwise - will fallback to runtime/memory (aka. on page refresh or service restart you'll have to authenticate again).
Default cookie names
xgen_token- token value and expiration datexgen_user- user value and expiration datexgen_session- session value and expiration date
LocalCookieAuthStore customization options
params
keyPrefix?: string; tokenSuffix?: string; userSuffix?: string; sessionSuffix?: string; generateUserId?: () => string; addAlternateUserId?: () => string | undefined; getUserExpiration?: () => number; getSessionExpiration?: () => number;
cookieOptions
path?: string; domain?: string; secure?: boolean;
Example:
const authStore = new LocalCookieAuthStore({ params: { keyPrefix: 'custom_', } cookieOptions: { path: '/', domain: 'example.com', secure: true, }, });
Custom auth store
In some situations it could be easier to create your own custom auth store. For this you can extend BaseAuthStore and pass the new custom instance as constructor argument to the client:
import XGenClient, { BaseAuthStore } from '@xgenai/sdk-core';
class CustomAuthStore extends BaseAuthStore {
save({ tokenRecord, userRecord, sessionRecord }) {
super.save({ tokenRecord, userRecord, sessionRecord });
// your custom business logic...
}
}
const xg = new XGenClient({
// ...other params
authStore: new CustomAuthStore(),
});Common auth store fields and methods
The default xg.authStore extends BaseAuthStore and has the following public members that you can use:
BaseAuthStore {
// base fields
token: TokenRecord|null // the access_token and expiration
user: UserRecord|null // the userId, userType, expiration, and alternateUserId (if applicable)
sessionId: SessionRecord|null // the session id and expiration
isExpired: boolean // checks if the record is expired
// main methods
clear() // "logout" the authenticated record
save({tokenRecord, userRecord, sessionRecord}) // update the store with the new auth data
// cookie parse and serialize helpers
loadFromCookie(cookieHeader)
exportToCookie(options = {})
// overidable properties methods via constructor
keyPrefix: string
tokenSuffix: string
userSuffix: string
sessionSuffix: string
generateUserId(): string // custom userId generation
addAlternateuserId(): string // custom alternate userId generation
getUserExpiration(): number // custom function to generate a user expiration date - Defaults to 395 days from now
getSessionExpiration(): number // custom function to generate a session expiration date - Defaults to 30 minutes from now
}To "logout" the authenticated record you can call xg.authStore.clear().
To manually cancel pending requests, you could use xg.cancelAll() or xg.cancel(requestKey).
Custom Cookie names
import XGenClient, {LocalCookieAuthStore} from '@xgenai/sdk-core';
const authStore = new LocalCookieAuthStore({
keyPrefix = 'custom_',
tokenSuffix = 'my-token-key',
userSuffix = 'my-user-key',
sessionSuffix = 'my-session-key',
})🔧 Now the cookie keys stored in the browser will be.
custom_my-token-key- Stores authentication token and expiration datecustom_my-user-key- Contains user information and expiration datecustom_my-session-key- Maintains session data and expiration date
Custom methods
import XGenClient, { LocalCookieAuthStore } from '@xgenai/sdk-core';
const authStore = new LocalCookieAuthStore({
generateUserId: () => 'custom_user_id',
addAlternateUserId: () => 'custom_alternate_user_id',
getUserExpiration: () => Date.now() + 1000 * 60 * 60 * 24 * 20, // 20 days from now
getSessionExpiration: () => Date.now() + 1000 * 60 * 60, // 1 hour from now
});Send hooks
Sometimes you may want to modify the request data globally or to customize the response.
To accomplish this, the SDK provides 2 function hooks:
beforeSend- triggered right before sending thefetchrequest, allowing you to inspect/modify the request config.const xg = new XGenClient({ /* params */ }); xg.beforeSend = function (url, options) { // For list of the possible request options properties check // https://developer.mozilla.org/en-US/docs/Web/API/fetch#options options.headers = Object.assign({}, options.headers, { 'X-Custom-Header': 'example', }); return { url, options }; };afterSend- triggered after successfully sending thefetchrequest, allowing you to inspect/modify the response object and its parsed data.const xg = new XGenClient({ /* params */ }); xg.afterSend = function (response, data) { // do something with the response state console.log(response.status); return Object.assign(data, { // extend the data... newField: 'This is added to the data of the response', }); };
SSR integration
Unfortunately, there is no "one size fits all" solution because each framework handle SSR differently (and even in a single framework there is more than one way of doing things).
But in general, the idea is to use a cookie based flow:
- Create a new
XGenClientinstance for each server-side request - "Load/Feed" your
xg.authStorewith data from the request cookie - Perform your application server-side actions
- Before returning the response to the client, update the cookie with the latest
xg.authStorestate
All BaseAuthStore instances have 2 helper methods that
should make working with cookies a little bit easier:
// update the store with the parsed data from the cookie string
xg.authStore.loadFromCookie('xgen_token=...;xgen_user=...;xgen_session=...');
// exports the store data as cookie, with option to extend the default SameSite, Secure, HttpOnly, Path and Expires attributes
xg.authStore.exportToCookie({ httpOnly: false }); // Output: 'xgen_token=...;xgen_user=...;xgen_session=...'Below you can find an example of how to integrate on the server:
One way to integrate with Express could be to create the XGen client in a middleware
and pass it to the other routes using the res.locals.
note: Your server will need to handle CORS
- set the allowed origin and
credentials: trueon your server- Make sure to include
credentials: includewhen making the fetch call- When calling
xg.authStore.exportToCookie()make sure you pass the option to switchsameSite: false
xg.authStore.exportToCookie({secure: true, sameSite: false, httpOnly: true, path: '/'})
// src/index.ts
import express from 'express';
import XGenClient, { type ClientParams } from '@xgenai/sdk-core';
// locals typescript
declare global {
namespace Express {
interface Locals {
xg: XGenClient;
}
}
}
const clientParams: ClientParams = {
key: 'ec5eda77fa13cce055f4443855c84c2a',
secret: 'fed4ddef035229a50b08e6a5437c4ad90b324e6206543e4fda088b2f54a2fdac5f06e367874bdf950fbcb17265df9787bcec68474701307b70581e4e25abd814',
clientId: 'bcf4fb5ef8bac6e63ba6884f58e4b100',
trackerId: 'eacd363314004c9a96c31f72e04f8fcc',
getEnv: () => 'stage',
};
export const app = express();
const port = 3000;
// Middleware
app.use((req, res, next) => {
const xg = new XGenClient(clientParams);
if (xg) {
res.locals.xg = xg;
}
xg.authStore.loadFromCookie(req.headers.cookie || '');
next();
});
// Routes
app.get('/', (_, res) => {
res.send('Healthy!');
});
app.get('/products', async (_, res) => {
try {
const recommendations = await res.locals.xg.recommend.getResultsById({
elementId: '<element_id>',
});
res.setHeader('Set-Cookie', res.locals.xg.authStore.exportToCookie());
res.send(recommendations);
} catch (err) {
console.error(err);
res.send(err);
}
});
// Server
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});One way to integrate with SvelteKit SSR could be to create the XGen client in a hook handle
and pass it to the other server-side actions using the event.locals.
// src/hooks.server.js
import XGenClient from '@xgenai/sdk-core';
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
event.locals.xg = new XGenClient({
/*params*/
});
// load the store data from the request cookie string
event.locals.xg.authStore.loadFromCookie(event.request.headers.get('cookie') || '');
const response = await resolve(event);
// send back the default 'xgen_token', 'xgen_user', 'xgen_session' cookies to the client with the latest store state
event.locals.xg.authStore
.exportToCookie()
.forEach((cookie) => response.headers.append('set-cookie', cookie));
return response;
}And then, in some of your server-side actions, you could directly access the previously created event.locals.xg instance:
// src/routes/recommendations/+server.js
/**
* Creates a `POST /recommendations` server-side endpoint
*
* @type {import('./$types').RequestHandler}
*/
export async function POST({ request, locals }) {
const { email, password } = await request.json();
const results = await xg.recommend.getResultsById({ elementId: '<element_id>' });
return new Response(results);
}For proper locals.xg type detection, you can also add XGenClient in your your global types definition:
// src/app.d.ts
import XGenClient from '@xgenai/sdk-core';
declare global {
declare namespace App {
interface Locals {
xg: XGenClient;
}
}
}Definitions
Creating new client instance
const xg = new XGenClient({
key: '<your_api_key>',
secret: '<your_api_secret>',
clientId: '<your_client_id>',
trackerId: '<your_tracker_id>',
getEnv: () => 'stage', // optional: function that returns the environment (`stage` or `prod`) - defaults to 'prod'
authStore: new LocalCookieAuthStore(), // optional - can pass in a custom auth store instance - defaults to LocalCookieAuthStore
});Instance methods
| Method | Description |
| :--------------------- | :---------------------------------------------------- |
| xg.cancelAll() | Cancels all pending requests. |
| xg.cancel(cancelKey) | Cancels single request by its cancellation token key. |
Services
Each service call returns a
Promiseobject with the API response.
Recommend Service
Methods
// Returns a recommendation response mapped by element IDs.
xg.recommend.getResults({ elementIds: ['<element_id_1>', '<element_id_2>'], { pathname: '/en-us/' } });
// Returns a recommendation response for the given element ID.
xg.recommend.getResultsById({ elementId: '<element_id>', { pathname: '/en-us/' } });getResults
Description: Gets recommendation results by a list of elementIds.
Parameters
| Name | Type | Required | Description |
| ----------------------------- | -------- | ----------- | ------------------------------------------------------------------------------------------------------------------- |
| elementIds | string[] | ✅ (for v2) | The IDs of the elements |
| containerIds | string[] | ✅ (for v3) | The IDs of the containers |
| options | object | ✅ | Options object that allows you to control the search result response |
| ↳ options.version | v1 or v2 | ❌ | The version of the API to use. v2 corresponds with the experience api, while v3 corresponds with the containers api |
| ↳ options.pathname | string | ❌ | The pathname that includes the locale (default to 'default' locale) |
| ↳ options.queryString | string | ❌ | The query string of the page |
| ↳ options.collection | string | ❌ | The collection to get items from |
| ↳ options.locale | string | ❌ | The locale to get items from |
| ↳ options.exclude | string[] | ❌ | Product codes to exclude from the recommendations |
| ↳ options.recentlyViewed | string[] | ❌ | Product codes of recently viewed items |
| ↳ options.productCode | string | ❌ | Product code of the currently viewed product |
| ↳ options.targetProductCode | string[] | ❌ | Product code of the target product (for instance, the most recently added product to cart) |
| ↳ options.context | object | ❌ | Dynamic contextual information |
| queryId | string | ❌ | An optional queryId passed to cancel a request |
Returns
A Promise resolving to a Recommendations object:
{
// v2
[key: string]: {
items: RecommendProduct[];
title: string;
ruleEngine: string;
ruleset: string;
};
// v3
[key: string]: {
items: RecommendProduct[];
title: string;
};
}getResultsById
Description: Gets recommendation results by a single elementId.
Parameters
| Name | Type | Required | Description |
| ----------------------------- | -------- | ----------- | ------------------------------------------------------------------------------------------------------------------- |
| elementId | string | ✅ (for v2) | The ID of the element |
| containerId | string | ✅ (for v3) | The ID of the element |
| options | object | ✅ | Options object that allows you to control the search result response |
| ↳ options.version | v1 or v2 | ❌ | The version of the API to use. v2 corresponds with the experience api, while v3 corresponds with the containers api |
| ↳ options.pathname | string | ❌ | The pathname that includes the locale (default to 'default' locale) |
| ↳ options.queryString | string | ❌ | The query string of the page |
| ↳ options.collection | string | ❌ | The collection to get items from |
| ↳ options.locale | number | ❌ | The locale to get items from |
| ↳ options.exclude | string[] | ❌ | Product codes to exclude from the recommendations |
| ↳ options.recentlyViewed | string[] | ❌ | Product codes of recently viewed items |
| ↳ options.productCode | string | ❌ | Product code of the currently viewed product |
| ↳ options.targetProductCode | string[] | ❌ | Product code of the target product (for instance, the most recently added product to cart) |
| ↳ options.context | object | ❌ | Dynamic contextual information |
| queryId | string | ❌ | An optional queryId passed to cancel a request |
Returns
A Promise resolving to a Recommendations object:
{
// v2
items: RecommendProduct[];
title: string;
ruleset: string;
ruleEngine: string;
// v3
items: RecommendProduct[];
title: string;
}Search Service
Methods
// Returns a search response containing the results
xg.search.getResults({
query: 'coat',
options: { collection: '<collection>', deploymentId: '<deployment_id>', locale: '<locale>' // Locale is used for tracking purposes },
});
// Returns a list of property values for the given collection
xg.search.getResultValues({ collection: '<collection>' });
// Returns a search response for the given category and collection
xg.search.getCategoryPage({ category: 'coat', collection: '<collection>' });
// Returns a list of trending search terms for the given collection
xg.search.getTrendingSearches({ collection: '<collection>' });getResults
Description: Gets recommendation results by a single elementId.
Parameters
| Name | Type | Required | Description |
| --------------------------- | ------------------------ | -------- | -------------------------------------------------------------------- |
| query | string | ✅ | The ID of the element |
| options | object | ✅ | Options object that allows you to control the search result response |
| ↳ options.collection | string | ✅ | The collection to get items from |
| ↳ options.locale | string | ✅ | The locale used for tracking purposes |
| ↳ options.deploymentId | string | ✅ | The deploymentId |
| ↳ options.page | number | ❌ | The page of results |
| ↳ options.facets | boolean | ❌ | If facets should be returned or not |
| ↳ options.forceDeepSearch | boolean | ❌ | If deep search should be forced |
| ↳ options.sortBy | 'price' | 'update_date' | ❌ | Sort by price or update date |
| ↳ options.sortOrder | 'asc' | 'desc' | ❌ | Sort order |
| ↳ options.context | object | ❌ | Dynamic contextual information |
| queryId | string | ❌ | An optional queryId passed to cancel a request |
Returns
A Promise resolving to the object below:
{
items: SearchProduct[];
facets: { [key: string]: unknown };
isFromCache: boolean;
page: number;
keyword: string;
isUrlRedirect: boolean;
urlRedirect: string;
isQueryTranslated: boolean;
isCachedFilterApplied: boolean;
isKeywordConfigApplied: boolean;
behaviorId: string;
responseEngine: string;
totalResults: number;
sortedBy: string;
variantMapping?: { [key: string]: string };
searchTermMatches?: string[];
filter: { [key: string]: unknown };
}getResultValues
Description: Gets the possible properties of a search result.
Parameters
| Name | Type | Required | Description |
| ------------ | ------ | -------- | ---------------------------- |
| collection | string | ✅ | Collection to get items from |
Returns
A Promise resolving to the object below:
{
[key: string]: {
name: string;
count: number;
}
}getCategoryPage
Description: Gets results for a specific category page.
Parameters
| Name | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------------------------- |
| category | string | ✅ | Category to get items from |
| collection | string | ✅ | Collection to get items from |
| page | number | ❌ | Page number |
| queryId | string | ❌ | Optional queryId passed to cancel a request |
Returns
A Promise resolving to the object below:
{
items: SearchProduct[];
facets: { [key: string]: unknown };
isFromCache: boolean;
page: number;
keyword: string;
isUrlRedirect: boolean;
urlRedirect: string;
isQueryTranslated: boolean;
isCachedFilterApplied: boolean;
isKeywordConfigApplied: boolean;
behaviorId: string;
responseEngine: string;
totalResults: number;
sortedBy: string;
variantMapping?: { [key: string]: string };
searchTermMatches?: string[];
filter: { [key: string]: unknown };
}getTrendingSearches
Description: Gets the popular searches.
Parameters
| Name | Type | Required | Description |
| ------------ | ------ | -------- | ---------------------------- |
| collection | string | ✅ | Collection to get items from |
Returns
A Promise resolving to the array below:
string[];getSearchSuggestions
Description: Gets search suggestions based off search events.
Parameters
| Name | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------------------------- |
| collection | string | ✅ | Collection to get items from |
| query | string | ✅ | The query to get suggestions for |
| queryId | string | ❌ | Optional queryId passed to cancel a request |
Returns
A Promise resolving to the array below:
string[];Track Service
Methods
There are 3 ways to pass the locale to the track service events: Note: The locale is a required field for all track events, but it is optional to pass directly in each event because there are 3 way to set the locale:
- Pass the locale directly as a parameter (see examples below)
- Use the
xg.track.setLocale(<locale>: string)method to set the locale for any subsequent track events - Set the locale when creating the XGenClient instance
cons xg = new XGenClient({ // ...other params, locale: () => '<locale>', // or locale: '<locale>', })
There are also 3 ways to pass the group that a user belongs to: Note: The group is not required, but is useful for segmenting users during A/B testing.
- Pass the group directly as a parameter. Example:
xg.track.pageView({ group: '<group>' }) - Use the
xg.track.setGroup(<group>: string)method to set the group for any subsequent track events - Set the group when creating the XGenClient instance
cons xg = new XGenClient({ // ...other params, group: () => '<group>', // or group: '<group>', })
// tracks a page view event.
xg.track.pageView({ locale });
// tracks the view of a item/product
xg.track.itemView({ item, context, locale });
// tracks the view of a category
xg.track.categoryView({ category, items, context, locale });
// tracks an add to cart event for an item/product
xg.track.addToCart({ item, context, locale });
// tracks a purchase order event for item(s)/product(s)
xg.track.purchaseOrder({ items, orderId, tax, discount, context, locale });
// tracks the view of a specific dom element
xg.track.elementView({ element, context, locale });
// tracks the render of a specific dom element
xg.track.elementRender({ element, context, locale });
// tracks the click of a specific dom element
xg.track.elementClick({ element, item, context, locale });
// tracks a search query event (tracked by default when calling xg.search.getResults())
xg.track.searchQuery({ query, queryId, deploymentId, page, context, locale });
// tracks the results of a search query (tracked by default when calling xg.search.getResults())
xg.track.searchResult({ query, queryId, deploymentId, page, context, locale });
// tracks a click of a search item/product
xg.track.searchClick({ query, queryId, deploymentId, page, item, items, context, locale });
// tracks a group assignment event
xg.track.groupAssignment({ group, previousGroup, context, locale });
// tracks a custom event
xg.track.customEvent({ category, action, name, value, locale });
// batch tracking - this will batch tracking events until send() is called
const batch = xg.track.createBatch();
batch.pageView();
batch.itemView({ item, context });
// optionally takes in a locale, group, url, and referrer to send the tracking events for
//ex. batch.send({locale: 'en', url: 'https://example.com/pdp', referrer: 'https://example.com/, group: 'group'})
batch.send();All Tracking Events Return
{
message: string;
success: boolean;
}pageView
Description: Tracks a page view event.
- This is an event that fires each time a new page is viewed by the user.
Parameters
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ---------------------------------- |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
itemView
Description: Tracks a item/product view event.
- This is an event that fires each time a item/product is viewed by the user (Product detail page view).
Parameters
| Name | Type | Required | Description |
| ----------------- | ------ | -------- | ----------------------------------------- |
| item | object | ✅ | The item/product to track |
| ↳ item.id | string | ✅ | The id of the item/product |
| ↳ item.name | string | ✅ | The name of the item/product |
| ↳ item.price | string | ✅ | The price of the item/product |
| ↳ item.currency | string | ✅ | The currency of the item/product. Ex. USD |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
categoryView
Description: Tracks a category view event.
- This is an event that fires each time a category/plp page is viewed by the user.
Parameters
| Name | Type | Required | Description |
| ---------- | -------- | -------- | ------------------------------------------------ |
| category | string | ✅ | The category to track |
| items | string[] | ✅ | The ids of the first few category items/products |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
addToCart
Description: Tracks an add to cart event.
- This is an event that fires each time an item/product is added to the cart.
Parameters
| Name | Type | Required | Description |
| ----------------- | ------ | -------- | ----------------------------------------- |
| item | object | ✅ | The item/product to track |
| ↳ item.id | string | ✅ | The id of the item/product |
| ↳ item.name | string | ✅ | The name of the item/product |
| ↳ item.price | string | ✅ | The price of the item/product |
| ↳ item.currency | string | ✅ | The currency of the item/product. Ex. USD |
| ↳ item.quantity | number | ✅ | The quantity of the item/product |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
purchaseOrder
Description: Tracks an add to cart event.
- This is an event that fires each time an order is placed.
Parameters
| Name | Type | Required | Description |
| ----------------- | ------ | -------- | ----------------------------------------- |
| items | item[] | ✅ | The array of items/products to track |
| ↳ item.id | string | ✅ | The id of the item/product |
| ↳ item.name | string | ✅ | The name of the item/product |
| ↳ item.price | string | ✅ | The price of the item/product |
| ↳ item.currency | string | ✅ | The currency of the item/product. Ex. USD |
| ↳ item.quantity | number | ✅ | The quantity of the item/product |
| orderId | string | ✅ | The unique identifier of the order |
| tax | number | ❌ | The tax amount of the order |
| discount | number | ❌ | The discount amount of the order |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
elementView
Description: Tracks the view of a specific dom node.
- This is an event that fires when a recommendation element is viewed by the user (element is visible in the viewport).
Parameters
| Name | Type | Required | Description |
| ----------------- | -------- | -------- | ------------------------------------------------------ |
| element | object | ✅ | Information about the dom node to track |
| ↳ element.id | string | ✅ | The id of the dom node |
| ↳ element.items | string[] | ❌ | An array of the items/product ids shown in the element |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
elementRender
Description: Tracks the render of a specific dom node.
- This is an event that fires when a recommendation element is rendered (element is in dom and able to be viewed).
Parameters
| Name | Type | Required | Description |
| ----------------- | -------- | -------- | ------------------------------------------------------ |
| element | object | ✅ | Information about the dom node to track |
| ↳ element.id | string | ✅ | The id of the dom node |
| ↳ element.items | string[] | ❌ | An array of the items/product ids shown in the element |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
elementClick
Description: Tracks the click of a specific dom node.
- This is an event that fires when a recommendation element item/product is clicked by the user.
Parameters
| Name | Type | Required | Description |
| ----------------- | -------- | -------- | ------------------------------------------------------ |
| element | object | ✅ | Information about the dom node to track |
| ↳ element.id | string | ✅ | The id of the dom node |
| ↳ element.items | string[] | ❌ | An array of the items/product ids shown in the element |
| item | string | ✅ | The id of the item/product clicked |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
searchQuery
Description: Tracks the search query. This is an event right before the search request is sent.
- This is an event that fires when a search query is executed by the user.
Parameters
| Name | Type | Required | Description |
| ---------------- | ------- | -------- | ------------------------------------------- |
| query | object | ✅ | Information about the dom node to track |
| queryId | string | ✅ | The id of the search query |
| deploymentId | string | ✅ | The id of the deployment |
| isTypeToSearch | boolean | ❌ | Whether the query is a type-to-search query |
| page | number | ❌ | The page number of the search query |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
searchResult
Description: Tracks the results of the search request.
- This is an event that fires when the search results are returned to the user.
Parameters
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ------------------------------------------------------- |
| query | object | ✅ | Information about the dom node to track |
| queryId | string | ✅ | The id of the search query |
| deploymentId | string | ✅ | The id of the deployment |
| items | string[] | ✅ | An array of the items/product ids in the search results |
| isTypeToSearch | boolean | ❌ | Whether the query is a type-to-search query |
| page | number | ❌ | The page number of the search query |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
searchClick
Description: Tracks a click event on a search result.
- This is an event that fires when a search item/product is clicked by the user.
Parameters
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ------------------------------------------------------- |
| query | object | ✅ | Information about the dom node to track |
| queryId | string | ✅ | The id of the search query |
| deploymentId | string | ✅ | The id of the deployment |
| item | string | ✅ | The id of the item/product clicked |
| items | string[] | ❌ | An array of the items/product ids in the search results |
| isTypeToSearch | boolean | ❌ | Whether the query is a type-to-search query |
| page | number | ❌ | The page number of the search query |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
groupAssignment
Description: Tracks when a group is assigned to a user.
- This is an event that fires when a user is assigned to a group.
Parameters
| Name | Type | Required | Description |
| --------------- | ------ | -------- | ---------------------------------- |
| group | object | ✅ | The group of the user |
| previousGroup | object | ❌ | The previous group of the user |
| locale | object | ❌ | The locale to track |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
customEvent
Description: Tracks a custom event.
- This is an event that can be used to track any custom event.
Parameters
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ------------------------------------ |
| category | string | ✅ | The category of the event type |
| action | string | ✅ | The action of the event |
| name | string | ✅ | The name of the event |
| value | string | ✅ | The value of the event |
| context | object | ❌ | Dynamic information about the event. |
| locale | object | ❌ | The locale to track |
| group | object | ❌ | The group of the user |
| url | object | ❌ | The url where the event took place |
| referrer | object | ❌ | The referrer url of the event |
