Initializing a Recommendation Component

When you want to take advantage of Coveo Machine Learning recommendations in a website page, you must add a Coveo JavaScript Search Framework Recommendation component to the page (see Coveo Machine Learning Event Recommendations Deployment Overview and Coveo Machine Learning Recommendations Complete Code Sample).

Once you added the Recommendation component HTML markup in your page (see Integrating a Recommendation Component in a Website Page), you still need to adapt and include the following code to your page head to initialize and render the Recommendation component (with the configureCloudEndpoint method).

<script>
  // Replace by the unique identifier of your Coveo Cloud organization.
  const organizationId = "mycoveocloudv2organization";
  // Replace by an API key with the *Execute query* and *Usage analytics write* privileges, 
  // or by a function that returns a valid search token.
  const accessToken = "*********-****-****-****-************";
  document.addEventListener("DOMContentLoaded", function() {
    Coveo.SearchEndpoint.configureCloudV2Endpoint(organizationId, accessToken);
    Coveo.initRecommendation(document.querySelector("#recommendation"));
  });
</script>

When you include the Recommendation component within a Coveo JavaScript Search interface, the initRecommendation requires a second parameter to indicate the main search interface element:

var searchInterfaceElement = document.querySelector('#search'); // Adjust if needed 
Coveo.initRecommendation(recommendationElement, searchInterfaceElement);

Ensure to adapt the variables:

  • accessToken

    An appropriate Coveo Cloud API key or search token that can execute queries and push usage analytics events on your organization (see Get an API key).

    When the search or website page in which you include the Recommendation component requires user authentication to be able to return secured results, you must use a search token that is generated for each user to initialize the component.

    A developer must set up a server-side mechanism to generate the search tokens using an API key that also carries the Search - Impersonate privilege (see Search Token Authentication).

  • organizationID

    The identifier of your Coveo Cloud organization.

    The Organization ID value, as it appears in the administration Console Settings panel (see Review the Organization ID)

  • endpointURI

    https://platform.cloud.coveo.com/rest/search

  • #recommendation

    Adjust the querySelector value if the HTML element with the CoveoRecommendation class does not have the id="recommendation" attribute.