Step 3: Add setContext Object

Setting Context

Now to put this all together we need to set the context client side. To do this you pass in an object to the setContext function. Generally you will do this in the onReady function but setContext can be called any time after the Search library is iniatlized. Here is an example:

<body>
  <div class="search-bar-container"></div>
  <div class="search-results"></div>
  <script>
    const userData = {
      segment: "swift-fan",
      age: "34-55",
      gender: "male",
    };

    const experienceKey = "retail_v2";
    const experienceVersion = "STAGING";
    const apiKey = "a1c14c5c35a224a32f286f7a56acdc04";
    const businessId = "2342169";
    const locale = "en";
    ANSWERS.init({
      apiKey,
      experienceKey,
      businessId,
      experienceVersion,
      onReady: function() {
        this.addComponent("SearchBar", {
          container: ".search-bar-container",
        });
        this.addComponent("UniversalResults", {
          container: ".search-results",
        });

        // SETTING CONTEXT HERE
        this.setContext(userData);
      },
    });
  </script>
</body>

You can see that userData is specified ahead of time and then that object is passed into setContext after the components are rendered.

userData will usually come from some other system like a CDP, CRM or analytics tool.

And that’s it, context is now passed into the backend and an Administrator can add rules to adjust search results based on context.

To see this fully in action, here is a working example:

Feedback