Track events in JSS apps using the Tracking API

Version: 20.x

You can use the JSS Tracking API to track events, goals, outcomes, campaigns, and page/route views.

To track events in a JSS page or component:

  1. Configure the Tracking API, providing the Sitecore API host and the Sitecore API key:

    RequestResponse
    import { trackingApi } from '@sitecore-jss/sitecore-jss/tracking
    
    const trackingApiOptions = {
      host: config.sitecoreApiHost,
      querystringParams: {
        sc_apikey: config.sitecoreApiKey,
      },
    };
    
  2. To track a simple event, call the trackEvent method of the JSS Tracking API with a parameter of the type EventInstance. For example, to track the click of a Download button:

    RequestResponse
    trackingApi
      .trackEvent(
        [
          { eventId: 'Download' }
        ], 
        trackingApiOptions
      )
      .then(() => console.log('Clicked Download button'))
      .catch((error) => console.error(error));

    The trackEvent method accepts an array of events. For example, to track the click of a button and a page view, you can add the page view event to the array:

    RequestResponse
    [
      { eventId: 'Download' },
      { pageId: '{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}', url: '/' }
    ]
    

Do you have some feedback for us?

If you have suggestions for improving this article,