Modify Requests and Responses

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 Headless sends them to the Coveo APIs, or you may want to modify responses before Headless controllers use them. This article explains how to do so.

Modify Requests

To modify requests sent to the Coveo Search or Usage Analytics APIs, use the preprocessRequest method of the target engine configuration (see search, recommendation, product recommendation or product listing, depending on your use case).

const engine = buildSearchEngine({
  configuration: {
    // ...
    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;
    },
  },
});

Modify Responses

If you’re using the search engine, you can 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.

const engine = buildSearchEngine({
  configuration: {
    // ...
    search: {
      preprocessSearchResponseMiddleware: (response) => {
        response.body.results.forEach((result) => {
          // E.g., modify the result object
          return result;
        });
        return response;
      },
      preprocessFacetSearchResponseMiddleware: (response) => response,
      preprocessQuerySuggestResponseMiddleware: (response) => response,
    },
  },
});
What's Next for Me?