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

# Send events

> Collect user interactions as events on your website using search-insights.js

export const UserProfile = () => <Tooltip tip="A user profile contains data about a single user, including behavior, preferences, and affinities collected from events. Algolia uses this data to deliver personalized content.">
    user profile
  </Tooltip>;

export const SearchRequest = () => <Tooltip tip="A search request is a single HTTP call to the Algolia Search API that can run one or more search operations. It can include multiple queries, for example, when querying several indices at once.">
    search request
  </Tooltip>;

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

This page shows how to send click and conversion events manually with [`search-insights`](/doc/libraries/search-insights).
For the concepts behind event tracking,
see [Click and conversion events](/doc/guides/sending-events).
For other implementation paths,
see [Choose how to send events](/doc/guides/sending-events/getting-started).

## Set up event collection

Before sending events manually,
make sure your search requests return `queryID` and your frontend can call [`search-insights`](/doc/libraries/search-insights).

Set the [`clickAnalytics`](/doc/api-reference/api-parameters/clickAnalytics?client=javascript) parameter to `true` when making search requests.
This includes the [`queryID`](/doc/guides/sending-events/concepts/event-types#events-related-and-unrelated-to-algolia-requests) parameter in the search response,
which links search-related events to the originating search request.

```js JavaScript icon="code" highlight={7} theme={"system"}
const algoliasearch = require("algoliasearch");
const client = algoliasearch(
  "ALGOLIA_APPLICATION_ID",
  "ALGOLIA_SEARCH_API_KEY",
);
const index = client.initIndex("YourIndexName");

index
  .search("query test", { clickAnalytics: true })
  .then(({ queryID, hits }) => {
    console.log(hits);
    console.log(queryID);
  });
```

Install the [`search-insights`](/doc/libraries/search-insights) library.

<CodeGroup>
  ```html HTML icon=code-xml theme={"system"}
  <script>
    var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@2.17.3/dist/search-insights.min.js";

    !function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e[s]=e[s]||function(){
    (e[s].queue=e[s].queue||[]).push(arguments)},e[s].version=(n.match(/@([^\/]+)\/?/) || [])[1],i=a.createElement(t),c=a.getElementsByTagName(t)[0],
    i.async=1,i.src=n,c.parentNode.insertBefore(i,c)
    }(window,document,"script",ALGOLIA_INSIGHTS_SRC,"aa");
  </script>
  ```

  ```sh NPM theme={"system"}
  npm install search-insights
  ```
</CodeGroup>

After installing [`search-insights`](/doc/libraries/search-insights),
initialize the client in your website.

```js JavaScript icon="code" theme={"system"}
import aa from "search-insights";

aa("init", {
  appId: "ALGOLIA_APPLICATION_ID",
  apiKey: "ALGOLIA_SEARCH_API_KEY",
});
```

For more on tracking `queryID` and `userToken`,
see [Keep track of query IDs](/doc/guides/sending-events/guides/queryid)
and [User token](/doc/guides/sending-events/concepts/usertoken).

## Decide which custom events to send

Map the steps users take through your website and send events for the actions that matter to your business.

Consider the following sequence:

1. A user searches on your homepage and is presented with a list of real estate properties.
2. The user **clicks** on a property to view more details.
3. The user **converts** by contacting the realtor.

In this example, track these events:

* `Property Clicked` by using the `clickedObjectIDsAfterSearch` method.
* `Property Contacted` by using the `convertedObjectIDsAfterSearch` method.

<Note>
  A conversion is any user action that's valuable to your business; a user purchasing from your store or subscribing to your newsletter are examples of common conversions.
  — [GA4 About conversions](https://support.google.com/analytics/answer/9267568?hl=en)
</Note>

## Track query IDs across pages

Conversion events often happen outside the search results page.

* A query ID is returned by the <SearchRequest /> when a user performs a search.
* To associate a conversion with the correct <SearchQuery />, save this query ID and include it in your conversion events.
* To link conversion events back to the originating search request on your search results or category pages, [track query IDs across your pages](/doc/guides/sending-events/guides/queryid).

## Track click events

Click events capture when users indicate they want to view
specific items. Add the following code to track a user navigating to
an item from a search results page:

```js JavaScript icon=code theme={"system"}
window.aa("clickedObjectIDsAfterSearch", {
  index: "YourIndexName",
  eventName: "Item Clicked",

  // Fields from the search response.
  queryID: "YourQueryID",
  objectIDs: ["objectID-1"],
  positions: [1],
});
```

The `queryID` parameter of the [`clickedObjectIDsAfterSearch`](/doc/libraries/search-insights/clicked-object-ids-after-search) method is used by Algolia to relate the event to a prior search
or browse event.

The `objectIDs` parameter of the `clickedObjectIDsAfterSearch` method should contain the ID of the item.
This can be retrieved from the `objectID` field of the [`hits`](/doc/rest-api/search/search-single-index#response-hits) array returned from the search request.

The `positions` parameter of the `clickedObjectIDsAfterSearch` method indicates the position of the item in the search results. For example, if the user clicked on the top result on the page, positions should be `[1]`.

If a user found an item without performing a search—for example, they
browsed there from elsewhere on your site, add the following code to track that:

```js JavaScript icon=code theme={"system"}
window.aa("clickedObjectIDs", {
  index: "YourIndexName",
  eventName: "Item Clicked",
  objectIDs: ["objectID-1"],
});
```

## Track conversion events

An example of a conversion event that may happen after a search:

```js JavaScript icon=code theme={"system"}
// A user contacted the realtor from a property details page
window.aa("convertedObjectIDsAfterSearch", {
  eventName: "Property Contacted",
  index: "YourIndexName",
  queryID: "query-1",
  objectIDs: ["objectID-1"],
});
```

The `window.aa` object is the API client for the Insights API and is globally available
if you enabled automatic events collection.

The `queryID` parameter of the [`convertedObjectIDsAfterSearch`](/doc/libraries/sdk/v1/methods/converted-object-ids-after-search) method is used by Algolia to relate the event to a prior search.

The `objectIDs` parameter of the [`convertedObjectIDsAfterSearch`](/doc/libraries/sdk/v1/methods/converted-object-ids-after-search) method indicates which items were part of the conversion.

The `objectID` parameter is included in the search response for each hit.

If the event isn't directly related to a search, for example, it's triggered on the homepage,
use the `convertedObjectIDs` method instead.

```js JavaScript icon=code theme={"system"}
// A user favorited an item from a homepage recommendation module
window.aa("convertedObjectIDs", {
  eventName: "Item Added To Favorites",
  index: "YourIndexName",
  objectIDs: ["objectID-1"],
});
```

Some other examples of conversion events are:

* `Item Added To Favorites`: a user saved an item.
* `Lead Submitted`: a user completed a lead form.
* `Demo Requested`: a user asked for a product demo.
* `Property Contacted`: a user contacted the realtor.
* `Store Appointment Booked`: a user booked an appointment.

## Track more click events

For Algolia Recommend and Personalization, capture additional click events
when users select individual items:

* On your home page
* From recommendations

To send click events with the Insights client, add the following code
whenever a user clicks on an item—for example,
on your homepage.

```js JavaScript icon=code theme={"system"}
window.aa("clickedObjectIDs", {
  index: "YourIndexName",
  eventName: "Item Clicked",
  objectIDs: ["objectID-1"],
});
```

## Optional: identify known users for Personalization

For effective [personalization](/doc/guides/personalization/classic-personalization/what-is-personalization),
identify users across sessions.
It's best to use an identifier from your authentication system after users sign in.

After getting the identifier from your system,
set it as the `authenticatedUserToken` parameter.

```js JavaScript icon="code" theme={"system"}
// Get a unique, pseudonymous identifier for signed-in users
const authenticatedUserToken = getUserTokenAfterSignIn();
window.aa("setAuthenticatedUserToken", authenticatedUserToken);
```

When you set the `authenticatedUserToken` parameter in the Insights client,
also update the user token you send with your search requests.

```js JavaScript icon="code" theme={"system"}
function getEffectiveUserToken() {
  const userToken = window.aa("getUserToken");
  const authenticatedUserToken = window.aa("getAuthenticatedUserToken");
  return authenticatedUserToken || userToken;
}

index
  .search("query", {
    clickAnalytics: true,
    userToken: getEffectiveUserToken(),
  })
  .then(({ queryID, hits }) => {
    console.log(hits);
    console.log(queryID);
  });
```

If you can't get persistent user identifiers from your system,
you can store the anonymous user token in a cookie **after obtaining user consent**.

```js JavaScript icon="code" theme={"system"}
// If user consented
aa("init", {
  partial: true,
  useCookie: true,
});
```

For more on identity strategy and persistence,
see [User token](/doc/guides/sending-events/concepts/usertoken).

## Optional: send view events for Personalization

Personalization benefits from the same click and conversion events,
plus it can use view events to enrich each <UserProfile />.

Use the following code snippet to track view events,
such as when a user views search results.

```js JavaScript icon="code" theme={"system"}
window.aa("viewedObjectIDs", {
  index: "YourIndexName",
  eventName: "Item Viewed",
  objectIDs: ["objectID-1"],
});
```

<Note>
  You don't need to send a `queryID` when tracking view events.
</Note>
