Generate a custom search token for Lightning components using Lightning Locker

Search tokens are used by specific authenticated users to perform search queries. If you want to generate a custom search token, for example to send custom data alongside the search token, you need to follow these steps.

Create an Apex class to generate the search token

  1. In Salesforce, access the Developer Console.

  2. In the Developer Console, create a new Apex class ( File > New > Apex Class).

  3. In the new Apex class, enter the following template:

     public with sharing class <MY_APEX_CLASS> {
         // Annotate the method so that it's accessible from the Lightning component
         @AuraEnabled
         public static string getToken() {
             // Generate a token using the Globals Class provided by Coveo.
             // See the Globals Class documentation: https://docs.coveo.com/en/1075/coveo-for-salesforce/globals-class
             Map<String, Object> endpoint = CoveoV2.Globals.getEndpointData();
             endpoint.put('token', CoveoV2.Globals.generateSearchToken());
             return JSON.serialize(endpoint);
         }
     }

    Where you replace <MY_APEX_CLASS> with the name you chose for your Apex class.

  4. In the getToken() class, enter your code to create the custom search token. Modify that code to at least include the searchHub in your token generation steps.

    Warning

    For content security reasons, don’t specify a search hub value as a parameter of the getToken() class (for example, getToken(String searchHub)).

    Example
    public with sharing class <MY_APEX_CLASS> {
        // Annotate the method so that it's accessible from the Lightning component
         @AuraEnabled
         public static string getToken() {
             // Generate a token using the Globals Class provided by Coveo.
             // See the Globals Class documentation: https://docs.coveo.com/en/1075/coveo-for-salesforce/globals-class
            Map<String, Object> endpoint = CoveoV2.Globals.getEndpointData();
            endpoint.put('token', CoveoV2.Globals.generateSearchToken(new Map<String, Object> {
             'searchHub' => '<MY_SEARCH_HUB>'
             }));
            return JSON.serialize(endpoint);
        }
    }

    Where you replace <MY_SEARCH_HUB> with the name of the search hub to enforce in the search token.

    Note that you can specify other parameters in the search token, such as query filters or a query pipeline.

    See Globals Class for instructions.

  5. Save the Apex class.

Create the custom Lightning endpoint handler

Now that you’ve created your Apex class, you must create a custom Lightning endpoint handler to reference your Apex class in your Lightning component.

  1. In the Developer Console, create a Lightning component.

  2. In the component .cmp, add the following code:

    <aura:component controller="<MY_APEX_CLASS>" >
        <!-- GET THE ENDPOINT INITIALIZATION DATA -->
        <aura:method name="getEndpoint" action="{!c.getTokenAction}" access="global">
            <aura:attribute name="name" type="String" />
        </aura:method>
        <!-- RENEW THE ENDPOINT ACCESS TOKEN -->
        <aura:method name="renewAccessToken" action="{!c.getTokenAction}" access="global">
            <aura:attribute name="name" type="String" />
        </aura:method>
    </aura:component>

    Where you replace <MY_APEX_CLASS> with the name of the Apex class you created in previous step.

  3. In the controller.js file, enter the following code:

    ({
        getTokenAction: function(component, event, helper) {
            const getTokenAction = component.get('c.getToken');
            var getTokenPromise = new Promise(function (resolve, reject) {
                getTokenAction.setCallback(this, function (response) {
                    if (response.getState() === 'SUCCESS') {
                        var responseData = response.getReturnValue();
                        resolve(JSON.parse(responseData));
                    } else if (response.getState() === 'ERROR') {
                        reject(Error('Error generating token'));
                    }
                });
            });
    
            $A.enqueueAction(getTokenAction);
            return getTokenPromise;
        }
    });
  4. Save the file.

Your custom Lightning endpoint handler is now ready.

Note

In our simple example, since there’s no difference between the generation and the renewal of a token, we call the same controller.js method twice.

Create a wrapper Lightning component

Now that you have the Apex class to generate the custom search token, you need to create a wrapper Lightning component. This will allow the class to be used as an EndpointHandler by other Lightning components.

Create the Lightning component wrapper

  1. In the Developer Console, create a Lightning component (see Create Lightning Components in the Developer Console).

  2. In the component, add the following code:

    For Coveo for Salesforce versions 2.38 and up:

    <aura:component implements='forceCommunity:availableForAllPageTypes'>
        <aura:attribute name="endpointHandler" type="Aura.Component[]" access="global">
            <c:<MY_CUSTOM_ENDPOINT_HANDLER>></c:<MY_CUSTOM_ENDPOINT_HANDLER>>
        </aura:attribute>
    
        <CoveoV2:SearchUi endpointHandler="{!v.endpointHandler}"/>
    </aura:component>

    Where you replace <MY_CUSTOM_ENDPOINT_HANDLER> by the name of your custom endpoint handler.

    Important

    For more information on how to integrate the Coveo components in a custom Lightning component, see Integrating the Coveo components in a custom Lightning component.

  3. Save the Lightning component.

  4. Access the Advanced Server-Side Configuration panel and select the Bypass above settings to rather generate the search token from a custom Apex Class checkbox. See Add server-side Coveo Lightning component configuration for more information.

What’s next?

For more information on how to add your custom component to your Salesforce organization, see Integrating the Coveo components in a custom Lightning component.