Access Headless Through Quantic

The Quantic library uses Coveo Headless to interface with Coveo. For advanced customizations not possible in Quantic components, you can leverage the Headless library directly through Quantic. This article provides an example meant to help you do so.

The following is the JavaScript file of an example Quantic component that wraps the Headless context controller to pass custom context.

// setContext.js
import { LightningElement, api } from 'lwc';
import { registerComponentForInit, initializeWithHeadless } from 'c/quanticHeadlessLoader'; 1
 
export default class MyCustomContextComponent extends LightningElement {
  @api engineId = 'my-search-page'; 2
 
  contextController; 3
 
  connectedCallback() { 4
    registerComponentForInit(this, this.engineId);
  }
 
  renderedCallback() { 5
    initializeWithHeadless(this, this.engineId, this.initialize);
  }
 
  initialize = (engine) => {
    this.contextController = CoveoHeadless.buildContext(engine); 6
    this.contextController.set({ 7
      ageGroup: '30-45',
      interests: ['sports', 'camping', 'electronics']
    });
  }
}
1 Two functions you’ll need to connect your component with Coveo Headless.
2 Define the Headless engine ID property and assign it a default value. The @api decorator lets you expose that parameter publicly, making it accessible by parent components. In the end, the engine ID used by your setContext component must be the same as the one used by the components whose context you want to modify.
3 The variable you’ll use as a context controller.
4 You must define this callback and the following one when wrapping Headless components to connect your components with the Headless state. The registerComponentForInit function registers your component for future initialization using the specified engine.
5 The initializeWithHeadless callback will execute your initialize function after the engine instance is created. This reliably sets the context before your interface sends a query or logs an event.
6 The Headless buildContext method returns a context controller attached to your Headless engine.
7 Set the target context with your controller.

Once included in the target pages, this component passes custom context when making search requests and logging Usage Analytics events.

// ...
"context": {
  "ageGroup":"30-45",
  "interests" :["sports","camping","electronics"]
  },
// ...
Tip

Since the Coveo Quantic components wrap Headless components, you can have a look at the Quantic components themselves to see more examples.

What's next for me?