0

I am trying to use the JSS Tracking API, according to https://jss.sitecore.com/docs/fundamentals/services/tracking, with Sitecore XP 9.1. Following the example code:

import { trackingApi } from '@sitecore-jss/sitecore-jss-tracking';

const trackingApiOptions = {
  host: config.sitecoreApiHost,
  querystringParams: {
    sc_apikey: config.sitecoreApiKey,
  },
};

trackingApi
  // note the events are an array - batching is supported
  .trackEvent([{ eventId: 'Download' }], trackingApiOptions)
  .then(() => console.log('Page event pushed'))
  .catch((error) => console.error(error));

I get the following error in the browser console log:

TypeError: fetcher is not a function errors. 

When I assign the fetcher in the options (using node-fetch), I get a server-side error:

Exception: System.Web.HttpException
Message: A public action method 'event' was not found on controller 'Sitecore.JavaScriptServices.Tracker.Controllers.JssTrackerController'.
Source: System.Web.Mvc

and the following CORS error in my browser:

Access to fetch at 'http://sitecore/sitecore/api/jss/track/event?sc_apikey=%7B1F33A17A-47FC-44E4-9E72-96833F787ADB%7D' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The Event method in Sitecore.JavaScriptServices.Tracker.Controllers only supports POST and not GET, but the trackingApi is performing a GET request.

Any clues? What configuration am I missing?

PS. Using plain Javascript and not Typescript.

0

Turns out that the client-side CORS error is a false-positive. The actual problem is that the fetcher is performing a GET iso a POST. My fix for it:

import fetch from 'node-fetch';

async function myFetcher(url, data) {
    return await fetch(url, {
        method: 'post', 
        headers: {
            'Content-Type' : 'application/json'
        }, 
        body:  JSON.stringify(data)
    });
}

const trackingApiOptions = {
  host: config.sitecoreApiHost,
  querystringParams: {
    sc_apikey: config.sitecoreApiKey,
  },
  fetcher: myFetcher
};

trackingApi.trackEvent(events, trackingApiOptions);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.