> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Segment

> Send events to the Algolia Insights API with Segment.

export const Application = () => <Tooltip tip="An Algolia application is a self-contained environment with its own indices, configuration, and API keys. Applications don't share data or settings with each other.">
    application
  </Tooltip>;

If you're using Twilio Segment to track user interactions on your website or app,
you can set up Algolia as a destination to forward [click and conversion events](/doc/guides/sending-events).

<Columns>
  <Card title="Open CodeSandbox" icon="codesandbox" href="https://codesandbox.io/s/github/algolia/doc-code-samples/tree/master/instantsearch.js/segment-connector">
    Run and edit the Segment example in CodeSandbox.
  </Card>

  <Card title="Explore source code" icon="github" href="https://github.com/algolia/doc-code-samples/tree/master/instantsearch.js/segment-connector">
    Browse the source for the Segment example on GitHub.
  </Card>
</Columns>

To integrating Algolia with Segment:

1. Enable the Algolia destination in Segment.
2. Enable click analytics for your searches.
3. Identify users.
4. Augment your Segment events with Algolia-related data.

## Enable the Algolia destination in Segment

To add the Algolia destination to Segment, follow these steps:

1. Sign in to your Segment web app and select the workspace you want to work in.

2. Select the source you want to set up and click **Add Destination**.

   <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/segment/1-sources.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=0fd78a8d1f60484afef879a9a3412c54" alt="Screenshot of the Segment dashboard showing the 'JavaScript' source with a 'Copy Snippet' button and 'Destinations' section." width="1415" height="751" data-path="images/guides/segment/1-sources.png" />

3. Search for the Algolia destination and select it to add it.

   <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/segment/2-destinations.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=6f61f3e53878963de9fd8b7d6c35add0" alt="Screenshot of the Segment Catalog page showing the 'Algolia' destination listed under 'Requested destinations' with 213 votes." width="1416" height="754" data-path="images/guides/segment/2-destinations.png" />

4. Go to the [Algolia dashboard](https://dashboard.algolia.com/explorer/browse) and select your Algolia <Application />.

5. Copy your application ID and search API key [from the dashboard](https://dashboard.algolia.com/account/api-keys/) and paste it into Segment.

   <img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/segment/3-configuration.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=ad5f12ecbf595f5fa813dac15d3aeeb1" alt="Screenshot of the 'Algolia Insights' settings page with fields for Name, app ID, API key, and QueryID QueryString Name, and an Enable Destination toggle." width="3014" height="1704" data-path="images/guides/segment/3-configuration.png" />

For more information about adding destinations, see:

* [Send Segment data to destinations](https://segment.com/docs/connections/destinations/add-destination/)
* [Algolia Insights destination](https://segment.com/docs/connections/destinations/catalog/actions-algolia-insights/)

## Enable click analytics for your searches

To relate click and conversion events to searches,
Algolia needs a [query ID](/doc/guides/sending-events/guides/queryid).
To get the `queryID` parameter for a search,
set the [`clickAnalytics`](/doc/api-reference/api-parameters/clickAnalytics) parameter to `true`:

<CodeGroup>
  ```js JavaScript theme={"system"}
  index
    .search("YourSearchQuery", {
      userToken: "user-1",
      clickAnalytics: true,
    })
    .then(({ hits, queryID }) => {
      console.log(hits, queryID);
    });
  ```

  ```js InstantSearch.js theme={"system"}
  instantsearch.widgets.configure({
    clickAnalytics: true,
    userToken: "user-1",
  });
  ```

  ```jsx React InstantSearch theme={"system"}
  import { Configure } from "react-instantsearch";

  <Configure clickAnalytics={true} userToken={"user-1"} />;
  ```

  ```vue Vue InstantSearch theme={"system"}
  <ais-configure
    :click-analytics.camel="true"
    user-token.camel="user-1"
  />
  ```
</CodeGroup>

## Identify users

If you use Segment's `analytics.identify()` function to identify users,
use the same identifier for Algolia by passing it as the [`userToken`](/doc/api-reference/api-parameters/userToken) parameter with your search.
For example, if you want to use [Personalization](/doc/guides/personalization/classic-personalization/personalizing-results#turn-on-personalization-in-production):

<CodeGroup>
  ```js JavaScript theme={"system"}
  index
    .search("YourSearchQuery", {
      userToken: "user-1",
      enablePersonalization: true,
    })
    .then(({ hits }) => {
      console.log(hits);
    });
  ```

  ```js InstantSearch.js theme={"system"}
  instantsearch.widgets.configure({
    enablePersonalization: true,
    userToken: "user-1",
  });
  ```

  ```jsx React InstantSearch theme={"system"}
  <Configure enablePersonalization={true} userToken={"user-1"} />;
  ```

  ```vue Vue InstantSearch theme={"system"}
  <ais-configure
    :enable-personalization.camel="true"
    user-token.camel="user-1"
  />
  ```
</CodeGroup>

## Augment your Segment events with Algolia-related data

Algolia requires these properties that aren't part of the regular Segment specifications:

| Property       | Type                                                                                                                                               | Required? |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------- |
| `index`        | `string`                                                                                                                                           | Yes       |
| `eventType`    | value: `'view'`, `'click'`, or `'conversion'`                                                                                                      | Yes       |
| `eventSubtype` | value: `'addToCart'` or `'purchase'` (only applicable to `'conversion'` events)                                                                    | No        |
| `queryID`      | `string`                                                                                                                                           | No        |
| `objectIDs`    | `string[]` **or** `objectID`: `string`                                                                                                             | No        |
| `positions`    | `number[]` **or** `position`: `number`                                                                                                             | No        |
| `filters`      | `Array<{ type: string; value: string; }>` **or** `string[]` (`${type}:${value}`. For example, `brand:apple`)                                       | No        |
| `objectData`   | See the [Insights API reference](/doc/rest-api/insights) for the `objectData` parameter (only applicable to `'addToCart'` and `'purchase'` events) | No        |

You can get these properties with the following code:

<CodeGroup>
  ```js JavaScript theme={"system"}
  index
    .search("query", {
      userToken: "user-1",
    })
    .then(({ hits, queryID, hitsPerPage, page }) => {
      hits.map((hit, index) => {
        const position = index + 1 + page * hitsPerPage;
        const objectID = hit.objectID;
      });
    });
  ```

  ```js InstantSearch.js theme={"system"}
  // Required: InstantSearch.js >= 4.8.3

  search.use(
    instantsearch.middlewares.createInsightsMiddleware({
      insightsClient: null,
      onEvent(event) {
        const { widgetType, eventType, payload, hits } = event;

        if (widgetType === "ais.hits" && eventType === "view") {
          analytics.track("Product List Viewed", {
            index: payload.index,
            eventType: 'view',
            queryID: payload.queryID,
            objectIDs: payload.objectIDs,
            positions: payload.positions,

            // the rest
          });
        } else if (/* ... */) {
          // ...
        }
      },
    })
  );

  // index
  // eventType
  // queryID
  // objectIDs
  // positions
  // filters
  ```

  ```jsx React InstantSearch theme={"system"}
  function debounce(fn, delay) {
    let timerId;
    return function(...args) {
      if (timerId) {
        clearTimeout(timerId);
      }
      timerId = setTimeout(() => {
        fn(...args);
        timerId = null;
      }, delay);
    };
  }

  const debouncedHitsRender = debounce(({ hits }) => {
    if (hits.length > 0) {
      analytics.track("Product List Viewed", {
        index: '<index-name>',
        eventType: 'view',
        queryID: hits[0].__queryID,
        objectIDs: hits.map(hit => hit.objectID),
        positions: hits.map(hit => hit.__position),

        // the rest
      });
    }
  }, 500);

  const SendViewEvent = connectHits((...args) => {
    debouncedHitsRender(...args);
    return null;
  });

  // ...

  const Hit = ({ hit }) => (
    <article>
      <h1>{hit.name}</h1>

      <button
        onClick={() =>
          analytics.track("Product Clicked", {
            index: '<index-name>',
            eventType: 'click',
            queryID: hit.__queryID
            objectID: hit.objectID,
            position: hit.__position,

            // the rest
          })
        }
      >
        Add to favorite
      </button>
    </article>
  );

  // ...

  <Configure clickAnalytics />
  <SendViewEvent />
  <Hits hitComponent={Hit} />
  ```

  ```vue Vue InstantSearch theme={"system"}
  <!-- Required: Vue InstantSearch >= 3.7.0 -->

  <template>
    <ais-instant-search
      :index-name="<index-name>"
      :search-client="searchClient"
      :middlewares="middlewares"
    >
      <!-- widgets -->
    </ais-instant-search>
  </template>

  <script>
  import {
    createInsightsMiddleware,
  } from 'instantsearch.js/es/middlewares';

  const insightsMiddleware = createInsightsMiddleware({
    insightsClient: aa,
    onEvent(event) {
      const { widgetType, eventType, payload, hits } = event;

      if (widgetType === "ais.hits" && eventType === "view") {
        analytics.track("Product List Viewed", {
          index: payload.index,
          eventType: 'view',
          queryID: payload.queryID,
          objectIDs: payload.objectIDs,
          positions: payload.positions,

          // the rest
        });
      } else if (/* ... */) {
        // ...
      }
    }
  });

  export default {
    data() {
      return {
        // ...
        middlewares: [insightsMiddleware]
      }
    },
  }
  </script>
  ```
</CodeGroup>

The following code is an example of a click event tracked with Segment that includes all the necessary Algolia-related properties:

```js JavaScript icon=code theme={"system"}
analytics.track("Product Clicked", {
  product_id: "507f1f77bcf86cd799439011",
  sku: "G-32",
  category: "Games",
  name: "Monopoly: 3rd Edition",
  brand: "Hasbro",
  variant: "200 pieces",
  price: 18.99,
  quantity: 1,
  coupon: "MAYDEALS",
  position: 3,
  url: "https://www.example.com/product/path",
  image_url: "https://www.example.com/product/path.jpg",
  // Algolia-related properties
  index: "my-algolia-index", // [!code ++]
  eventType: "click", // [!code ++]
  queryID: "fd0bbaadc287937s7671d00f1d053b88", // [!code ++]
  objectID: "131280270", // [!code ++]
});
```

Refer to Segment's [Algolia Insights destination](https://segment.com/docs/connections/destinations/catalog/actions-algolia-insights/#track) documentation for details on which Segment events are supported by default.

## Debug events with Segment

If you have administrator permissions for your Segment source,
you can send test events.
To do this, select your source and click **Validate**.
Select **Algolia Insights** as the destination.

<img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/segment/debugging-1.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=97ede7ddf66ac90d607f4175d4696b46" alt="Screenshot of a dialog box titled 'Select the Destination you want to validate the event in' with a drop-down menu for 'Algolia Insights' and 'Cancel' and 'Next' buttons." width="1148" height="688" data-path="images/guides/segment/debugging-1.png" />

Now, you can send a test event using the **Event builder** or **JSON** editor.

<img src="https://mintcdn.com/algolia/u8QjGPGZbKOqOFEr/images/guides/segment/debugging-2.png?fit=max&auto=format&n=u8QjGPGZbKOqOFEr&q=85&s=781edc46d904f22863937d0ec91b6ccd" alt="Send a test event to the Algolia Insights destination" width="1148" height="688" data-path="images/guides/segment/debugging-2.png" />

A green box with the status "200 OK" means that Segment successfully sent a test event to the Algolia Insights destination.
To check, if the event delivery was successful, go to the [**Event Delivery**](https://segment.com/docs/connections/event-delivery/) tab.

For example, sending an event with a wrong query ID shows a delivery issue.

<video controls>
  <source src="https://mintcdn.com/algolia/i8QBUoaIRr-QIxRo/videos/event-delivery.webm?fit=max&auto=format&n=i8QBUoaIRr-QIxRo&q=85&s=4b4f9dfd101ab686162fffd3764a802c" type="video/webm" data-path="videos/event-delivery.webm" />

  <source src="https://mintcdn.com/algolia/i8QBUoaIRr-QIxRo/videos/event-delivery.mp4?fit=max&auto=format&n=i8QBUoaIRr-QIxRo&q=85&s=d414eb7181bad712ad581a37697e9320" type="video/mp4" data-path="videos/event-delivery.mp4" />
</video>

To check if Algolia receives your events correctly,
go to the [**Events Debugger**](https://dashboard.algolia.com/events/debugger) in the Algolia dashboard.
