Tracking Commerce Events

The coveo.analytics.js script is used to send events to the Coveo Usage Analytics (Coveo UA) service.

The library accepts a format similar to the Google Analytics tag (also called the analytics.js library).

How the Script Is Used

The first parameter is always a command name, and the other parameters vary depending on the command executed.

Tracking Commerce Events Flow

The init command is used to initialize the script and must be called once in each page. E.g., coveoua('init', <COVEO_API_KEY>);

Some commands allow setting data. For example, the set command allows setting a parameter for the whole page. E.g., coveoua('set', 'currencyCode', 'EUR');

The most important command is send, since it gets cumulated data and sends the event to the Coveo Usage Analytics service. E.g., coveoua('send', 'pageview');

Initialize the Script

You must include the following script tag to load the coveo.analytics library into your page.

<script>
(function(c,o,v,e,O,u,a){
a='coveoua';c[a]=c[a]||function(){(c[a].q=c[a].q|| []).push(arguments)};
c[a].t=Date.now();u=o.createElement(v);u.async=1;u.src=e;
O=o.getElementsByTagName(v)[0];O.parentNode.insertBefore(u,O)
})(window,document,'script','https://static.cloud.coveo.com/coveo.analytics.js/2/coveoua.js')
coveoua('init', <COVEO_API_KEY>);
</script>

The COVEO_API_KEY parameter must be replaced with an API Key or a search token with the Push access level on the Analytics Data domain.

User Authentication

It is recommended to use a search token when impersonating users, since a search token is temporary and encrypted.

The search token is used during the initialization of the script. Simply replace the COVEO_API_KEY value specified in the Initialize the Script section.

The userId field is ignored at all times when using a search token, since Coveo will instead extract the user from the search token itself.

When creating the token, use the following payload for an unauthenticated user:

{
    "userIds": [
        {
            "name": "anonymous",
            "provider": "Email Security Provider",
            "type" : "User"
        }
    ]
}

Use a payload similar to what follows for an authenticated user (replace asmith@example.com with the actual email of the user for whom you are requesting a search token):

 {
   "userIds": [
     {
       "name": "asmith@example.com",
       "provider": "Email Security Provider",
       "type": "User"
     }
   ]
 }

Every Coveo organization comes with a Email Security Provider. Hence, the above examples will be compatible by default. If you are using a custom security identity provider, set the provider parameter to the name of that provider instead.

Using the userId Field With an API Key

An API key with the Push access level on the Analytics Data domain will only accept unauthenticated users. To log events performed by authenticated users, the Allowed access level on the Impersonate domain is required.

Make sure you use the Impersonate domain linked above. Don’t use the Impersonate domain in the Search Service as it will allow users to send queries under any identity.

Provided that the API key has the necessary privileges, use the userId field to log user identities.

  • Leaving the userId field empty will log the event under an anonymous identity.
  • Setting a value in the userId field, such as asmith@example.ca will log the event under that specific identity.

Set Global Fields

Fields can be set with coveoua("set", <FIELD_NAME>, <FIELD_VALUE>)

User Fields Reference

Users fields are related to the current user.

userId (String)

Example: myuser@mycompany.com

Before using the userId field, see User Authentication.

currencyCode (String)

The currency code is a three-letter code that identifies the user’s currency.

The code follows the ISO 4217 standard.

Example: CAD

anonymizeIp (Boolean)

Use to anonymize the IP by removing the last subnet of the current user. Coveo will never store un-encrypted IPs, even when this setting is set to false.

loyaltyCardNumber (String)

The loyalty card number is a unique identifier provided to a returning user.

loyaltyTier (String)

The loyalty tier is a level of membership where users receive perks and benefits depending on their rank.

Example: Platinum

loyaltyCardType (String)

The type of card associated to the loyalty program. This can be the card itself or linked to a credit card.

thirdPartyPersona (String)

This represents additional market segmentation based on user characteristics (demographics, interests, needs or location) not created by Coveo Machine Learning. When you already have a set of segments for your users, pass the information in this field.

companyName (String)

The name of a specific company for business to business sales.

favoriteStore (String)

The primary store selected by a returning user.

storeName (String)

The name of the current store selected by the user.

Page Fields Reference

Page fields are sent using the set command, or alongside a pageview event as in the following command:

coveoua('send', 'pageview', {
    page: '/mypage'
})

page (String)

The path portion of the page URL.

Example: /mycurrentpage

title (String)

The title of the page, default value is retrieved from document.title.

Example: My Super Site

location (String)

The full URL of the page, default value is retrieved from document.location.

Example: https://www.mysupersite.com/home

Global Custom Fields Reference

The custom field allows users to add additional custom values as an object. Everything in this field will be unfolded to the parent object and then sent to coveoua.

To set custom fields for the whole page, use the set command, passing the custom string as a second argument, and an object containing the desired key-value pairs as a third argument.

On custom user data

  coveoua('set', 'custom',  {
    visitorAge: 18,
    rewardsMember: true
}); 
// sets the `custom` field for each top-level object

When you use the send command

coveoua('send', 'pageview');

The following data is sent to coveoua

visitorAge: 18,
rewardsMember: true

Add Product Data

The coveoua('ec:addProduct', <DATA>) command allows you to include the relevant product data in the event you’re about to send.

Product Fields Reference

Product fields are set with the ec:addProduct command.

id (String, Required)

The SKU used to uniquely identify your product.

Example: 001-red

name (String, Optional)

Example: Very nice shoe

brand (String, Optional)

Example: Coveo

category (String, Optional)

Represents a grouping of products having particular shared characteristics.

Field format Examples
Single "sport"
Hierarchical "sport / hiking / apparel"
Multi-value "sport / hiking / apparel | sport / climbing / apparel"

Ensure you are not sending events that include breadcrumbs with temporary categories or events, such as sales or clearance items.

variant (String, Optional)

A string that defines the variant of the product.

Example: 001-red-8_wide

list (String, Optional)

The list that the associated products belong to. For an example of this parameter, see Measuring Events on a Search-Driven Listing Page.

price (Numeric, Optional)

Example: 12.34

quantity (Numeric, Optional)

Example: 12

coupon (String, Optional)

The name of the coupon used on this specific product.

Example: PROMO-1234

position (Numeric, Optional)

The item’s position. For example, the first displayed in a list should have position: 1.

Example: 2

For products and impressions, only a position greater than or equal to 1 is valid. If position: 0 is passed, it’ll be removed and not sent through the API with the item.

Transaction Fields Reference

id (String, Required)

An identifier used to track a specific transaction.

Example: transaction-1234

affiliation (String, Optional)

Example: Shoe Store

revenue (Numeric, Optional)

The total value of the transaction, including taxes and shipping.

Example: 123.21

tax (Numeric, Optional)

The total transaction tax.

Example: 8.23

shipping (Numeric, Optional)

The transaction shipping cost.

Example: 5.00

coupon (String, Optional)

The name of the coupon used on the whole transaction.

Example: PROMO-FREE-SHIPPING-2020

Review Fields Reference

Reviews fields provide customers the opportunity to rate and comment on products they have purchased.

reviewRating (Numeric, Optional)

A rating described on a numeric scale from 0 to 10.

When using a different rating method, for example a review of 0 to 5 stars, ensure you convert the score to a base of 10.

reviewComment (String, Optional)

A written summary of a user’s experience with a product or service.

Custom Fields Reference

The custom field allows users to add additional custom values as an object. Everything in this field will be unfolded to the parent object and then sent to coveoua.

To set custom fields in a product impression, use the ec:addProduct command, and add a custom object containing the desired key-value pairs in your main product impression object.

On custom product data, when you use the ec:addProduct command

  coveoua('ec:addProduct', {
    'id': '001-red',
    'name': 'A very nice pair of shoes',
    'brand': 'Coveo',
    'category': 'Running shoes',
    'price': 90.22,
    'variant': '001-red-8_wide',
    'custom' : {
      'onSale' : false
    }
});

When you use the send command

coveoua('send', 'event');

It will send the following data

id: '001-red',
name: 'A very nice pair of shoes',
brand: 'Coveo',
category: 'Running shoes',
price: 90.22,
variant: '001-red-8_wide',
onSale : false

Set the Action

The coveoua('ec:setAction', <ACTION>) command allows you to set the executed action on your data.

Action Types

Action Description
'click' The user clicked on a product.
'detail' The user accessed a detailed view of the product.
'quickview' The user accessed a quick view of the product.
'add' or 'remove' The user added or removed a product from their cart.
'purchase' or 'refund' The sale or return of one or more products.
'bookmark_add' or 'bookmark_remove' The user added or removed a product from their bookmark.
'compare_add' or 'compare_remove' The user added a product to compare to another or removed one.
'rating_add' or 'rating_remove' The user added or removed a rating or score on a product.
'review_add' or 'review_remove' The user added or removed a review on a product.
'quote' The user asked for a quote regarding a given product (E.g., asked for a price on a large quantity of products in return for a discount).
'checkout' The user initiated the checkout process for one or more products.
'checkout_option' The user selected an option value for a given checkout step (E.g., selecting payment options or shipping methods).

In order to dispatch these events to Coveo UA, either a pageview or generic event has to be sent.

Add Impression Data

The Coveo Search APIs log impressions automatically to Coveo. However, there are some scenarios where manually logging impressions is required or recommended:

  • When you want to log them for another analytics engine outside of Coveo (like with Google Analytics).
  • You have a proxy (or equivalent process) that adds client-side data to product data.
  • The list is not using Coveo to power the results, and you would like to compare impressions with and without Coveo.

To send an impressions manually, use the following command:

coveoua('ec:addImpression', <DATA>)

Where you replace <DATA> with the product impression object containing the relevant fields.

The command captures visible items on the page the moment the user completes an action. For example, selecting a product, viewing a page, or other recommendations.

Impression Fields Reference

Product fields are set with the ec:addImpression command.

id (String, Required)

The SKU used to uniquely identify your product.

Example: 001-red

name (String, Optional)

Example: Very nice shoe

brand (String, Optional)

Example: Coveo

category (String, Optional)

Example: Shoe

variant (String, Optional)

A string that defines the variant of the product.

Example: 001-red-8_wide

list (String, Optional)

The list that the associated products belong to. For an example of this parameter, see Measuring Events on a Search-Driven Listing Page.

price (Numeric, Optional)

Example: 12.34

position (Numeric, Optional)

The item’s position. For example, the first displayed in a list should have position: 1.

Example: 2

For products and impressions, only a position greater than or equal to 1 is valid. If position: 0 is passed, it’ll be removed from the payload.

Dispatch the Event

Sending a Page View

To send a page view event, you can use the following command:

coveoua('send', 'pageview', <PAGE>, <FIELDS_OBJECT>);

Where:

<PAGE> (String, Optional) should be set when the end user navigates to a new page in a Single Page Application (SPA).

<FIELDS> (Object, Optional) contains additional metadata to send along with the event (see Fields Reference).

  • The following command sends an event that includes the current page’s information, such as the title, location and referer.

      coveoua('send', 'pageview');
    
  • In a Single-Page Application (SPA), you must first use the set command to notify the script that the current page has changed when the URL is dynamically updated:

      coveoua('set', 'page', '/mycurrentpage');
      coveoua('send', 'pageview');
    

Sending a Generic Event

To send any type of event, you can use the following command:

coveoua('send', 'event', <FIELDS_OBJECT>);

Examples

Measuring a Product Details View

The user has viewed the details of the product and you want to measure this type of user interaction. However, data has only been set by the previous commands. It has to be sent with either a pageview or with a generic event.

In your commerce application, a user has just opened the detailed view of a certain pair of red running shoes.

First use the ec:addProduct command to include the relevant product data in the event you’re about to send:

coveoua('ec:addProduct', {
    'id': '001-red',
    'name': 'A very nice pair of shoes',
    'brand': 'Coveo',
    'category': 'Running shoes',
    'price': 90.22,
    'variant': '001-red-8_wide',
    'position': 1
});

Then use the ec:setAction command to specify that the action done on this data is a product details view:

coveoua('ec:setAction', 'detail');

Finally, use the send command to send the event to Coveo UA.

If the user interaction didn’t open a new page, use event as an action:

coveoua('send', 'event');

Otherwise, use pageview:

coveoua('send', 'pageview');

Measuring an Addition to the Cart

The user has added a product to the cart and you want to measure this type of user interaction. Since the page is already loaded and the page view event logged, the data must be sent on a generic event.

In your commerce application, a user has just added a certain pair of red running shoes to the cart.

First use the ec:addProduct command to include the relevant product data in the event you’re about to send:

coveoua('ec:addProduct', {
    'id': '001-red',
    'name': 'A very nice pair of shoes',
    'brand': 'Coveo',
    'category': 'Running shoes',
    'variant': '001-red-8_wide',
    'price': 90.22,
    'quantity': 1
});

Then use the ec:setAction command to specify that the action done on this data is an addition to the cart:

coveoua('ec:setAction', 'add');

Finally, use the send command to send the event to Coveo UA.

coveoua('send', 'event');

Measuring a Removal from the Cart

The user has removed a product from the cart and you want to measure this type of user interaction. Since the page is already loaded and the page view event logged, the data must be sent on a generic event.

In your commerce application, a user has just removed a certain pair of red running shoes from the cart.

First use the ec:addProduct command to include the relevant product data in the event you’re about to send:

coveoua('ec:addProduct', {
    'id': '001-red',
    'name': 'A very nice pair of shoes',
    'brand': 'Coveo',
    'category': 'Running shoes',
    'variant': '001-red-8_wide',
    'price': 90.22,
    'quantity': 1
});

You then use the ec:setAction command to specify that the action done on this data is a product was removed from the cart:

coveoua('ec:setAction', 'remove');

Finally, use the send command to send the event to Coveo UA.

coveoua('send', 'event');

Measuring Purchases

The user has completed a purchase and you want to measure this type of user interaction. However, data has only been set by the previous commands. It has to be sent with either a pageview or with a generic event.

In your commerce application, a user has completed a conversion and purchased a pair of red running shoes.

First use the ec:addProduct command to include the relevant product data in the event you’re about to send:

coveoua('ec:addProduct', {
    'id': '001-red',
    'name': 'A very nice pair of shoes',
    'category': 'Running shoes',
    'brand': 'Coveo',
    'variant': '001-red-8_wide',
    'price': 22.99,
    'quantity': 1
});

You then use the ec:setAction command to specify that the action done on this data is a product purchase:

coveoua('ec:setAction', 'purchase', {
    'id': 'transaction-1234',
    'affiliation': 'My Shoe Store',
    'revenue': '12.34',
    'tax': '1.85',
    'shipping': '5.00',
    'coupon': 'PROMO-1234',
});

Finally, you use the send command to send the event to Coveo UA.

If the user interaction didn’t open a new page, use event as an action:

coveoua('send', 'event');

Otherwise, use pageview:

coveoua('send', 'pageview');

Measuring Events on a Search-Driven Listing Page

Similar to adding product data, to record user interactions within a Coveo-powered product listing page, the events you send must include the unique search identifier searchUid of the query that generated the listing page.

If your listing page is powered by the Coveo JavaScript Search Framework, use the getlastResults method on the QueryController instance to retrieve the searchUid:

const root = document.getElementById(<MY_SEARCH_INTERFACE_ID>);
const queryController =  Coveo.get(root, Coveo.SearchInterface).queryController;
const searchUid = queryController.getLastResults().searchUid;

Then, when you specify the action done on the data, set the list field to coveo:search:<YOUR_SEARCHUID>

// ...
coveoua('ec:setAction', 'click', {
  list: `coveo:search:${searchUid}`
});

You want to measure an add to cart event on a product listing page powered by the Coveo JavaScript Search Framework.

// First, you retrieve the listing page's searchUid.
const root = document.getElementById(<MY_SEARCH_INTERFACE_ID>);
const queryController =  Coveo.get(root, Coveo.SearchInterface).queryController;
const searchUid = queryController.getLastResults().searchUid;
 
// Then, you add the relevant product data.
coveoua('ec:addProduct', {
  'id': '001-red',
  'name': 'A very nice pair of shoes',
  'brand': 'Coveo',
  'category': 'Running shoes',
  'price': 90.22,
  'variant': '001-red-8_wide',
  'quantity': 2
});
 
// Next, you define the action done on the data.
// This is where you set the 'list' field.
coveoua('ec:setAction', 'add', {
  list: `coveo:search:${searchUid}`
});
 
// Finally, you send the event.
coveoua('send', 'event');

If you’re developing directly against the search API, you will find the searchUid in the JSON query response body:

{
  "totalCount" : 10,
  "totalCountFiltered" : 10,
  "duration" : 92,
  "indexDuration" : 23,
  "requestDuration" : 42,
  "searchUid" : "dda6ff39-eeed-436e-88cf-7bc77a36418e",
  ...
}

Measuring Product Impressions

Use the ec:addImpression command and provide the product details in one or more impression field objects.

// add the relevant product data.
coveoua('ec:addImpression', {
  'id': '001-red',
  'name': 'A very nice pair of shoes',
  'brand': 'Coveo',
  'category': 'Running shoes',
  'price': 90.22,
  'variant': '001-red-8_wide',
  'list': 'New Products'
  'position': 1
});
 
coveoua('ec:addImpression', {
  'id': '001-black',
  'name': 'A very nice pair of shoes',
  'brand': 'Coveo',
  'category': 'Running shoes',
  'price': 90.22,
  'variant': '001-black-13_wide',
  'list': 'New Products'
  'position': 2
});

Then use the send command to send the event to Coveo UA.

coveoua('send', 'event');
Recommended Articles