@coveo/headless
    Preparing search index...

    Modify requests and responses

    You may also want to modify responses before Headless controllers use them. This article explains how to do so.

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

    Important

    The preprocessRequest method is a powerful tool, and it can be leveraged to do things that should be done in a different manner. For example, you can use it to set aq, but you should use the Headless AdvancedSearchQuery action instead.

    If you have to use preprocessRequest, you should code defensively. For example, you can implement try...catch to prevent errors.

    const engine = buildSearchEngine({
    configuration: {
    // ...
    preprocessRequest: (request, clientOrigin, metadata) => { ①
    if (metadata?.method === 'search' && 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;
    },
    },
    });
    1. Initialize the function with its parameters:
      • request: The HTTP request sent to Coveo. See preprocess-request.ts.

      • clientOrigin: The origin of the request. See preprocess-request.ts.

      • metadata: Optional metadata consisting of two properties:

        • method: The method called on the client.
        • origin: The origin of the client that helps to distinguish between features while using the same method.

        See search-metadata.ts.

    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,
    },
    },
    });