Sending Apex context to a JavaScript search interface

You may want to have access to some Apex variables in your JavaScript Search interface. You can use the search context, a map of Apex values to do this as shown in the following example.


In an on-premises Coveo REST Search API, you define a trusted application with its secret key. You want to use the secret key to request a search token from your Apex page, and then use the received search token in your JavaScript search interface to set the accessToken to authorize the page to communicate with the REST Search API.

Here is how to do that:

  1. In Salesforce, create an Apex class (see Adding an Apex Class) that allows you to get the token and create a search context with the token in it.

    public class MySearchController {
      class UserId{
        public String name {get; set;}
        public String provider {get; set;}
        public String type {get; set;}
        public UserId(String name, String provider, String type){
   = name;
            this.provider = provider;
            this.type = type;
      class TokenResponse {
        public String token;
      public SearchContext getContext(){
        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', 'Bearer the_secret_key_for_the_application');
        req.setHeader('Content-Type', 'application/json');
        List<UserId> userIds = new List<UserId>();
        userIds.add(new UserId('', 'Email Security Provider', 'User'));
        Map<String,Object> body = new Map<String, Object>();
        body.put('userIds', userIds);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        String token = ((TokenResponse)JSON.deserialize(res.getBody(), TokenResponse.class)).token;
        SearchContext context = new SearchContext();
        return context;
  2. Create a new Visualforce page (see Defining Visualforce Pages) that adds the search context in the component from the controller.

    <apex:page standardstylesheets="false" sidebar="false" docType="html-5.0" controller="MySearchController">
        <Coveo:SearchInterface mobile="false" searchContext="{!context}" />
  3. Using the Interface Editor (see Accessing the Interface Editor for a Search API Hosted Page):

    1. Select the Advanced Mode, and then select the Code tab.

    2. In the page code, add the following code to set the token in the search interface endpoint options.

      <script type="text/javascript">
          Coveo.Rest.SearchEndpoint.endpoints['default'].options.accessToken = Coveo.context.token