Modify requests and responses

This is for:

Developer

For advanced use cases such as modifying request bodies with custom parameters or logging data to third parties, you may want to modify requests before Atomic sends them to the Coveo APIs, or you may want to modify responses before Atomic components use them. This article explains how you can do so by using Headless engine configuration methods.

Modify Requests

To modify requests sent to the Coveo Search API or the Usage Analytics Write API, use the preprocessRequest method of the search engine configuration when initializing your interface.

<script>
  (async () => {
    await customElements.whenDefined('atomic-search-interface');
    const searchInterface = document.querySelector(
      'atomic-search-interface'
    );
 
    // Initialization
    await searchInterface.initialize({
      accessToken: 'xx564559b1-0045-48e1-953c-3addd1ee4457',
      organizationId: 'searchuisamples',
      preprocessRequest: (request, clientOrigin) => {
        if (clientOrigin === 'searchApiFetch') {
          const body = JSON.parse(request.body);
          // E.g., modify facet requests
          // body.facets = [...];
          request.body = JSON.stringify(body);
        }
 
        if (clientOrigin === 'analyticsFetch') {
          // E.g., send data to a third party
        }
 
        return request;
      },
      // ...
   });
 
    // Trigger a first search
    searchInterface.executeFirstSearch();
  })();
</script>

Modify Responses

You can also leverage the search configuration options to modify search API responses before Headless controllers use them. Use the preprocessSearchResponseMiddleware, preprocessFacetSearchMiddleware or preprocessQuerySuggestResponseMiddleware method, depending on the target endpoint.

<script>
  (async () => {
    await customElements.whenDefined('atomic-search-interface');
    const searchInterface = document.querySelector(
      'atomic-search-interface'
    );
 
    // Initialization
    await searchInterface.initialize({
      accessToken: 'xx564559b1-0045-48e1-953c-3addd1ee4457',
      organizationId: 'searchuisamples',
      // ...
      search: {
        preprocessSearchResponseMiddleware: (response) => {
          response.body.results.forEach((result) => {
            // E.g., modify the result object
            return result;
          });
          return response;
        },
        preprocessFacetSearchResponseMiddleware: (response) => response,
        preprocessQuerySuggestResponseMiddleware: (response) => response,
     },
   });
 
    // Trigger a first search
    searchInterface.executeFirstSearch();
  })();
</script>