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

# Analytics

> Track search behavior and user interactions with Algolia Insights

DocSearch integrates with Algolia Insights to provide powerful analytics on search behavior, click patterns, and user interactions.

## Overview

Algolia Insights enables you to:

* Track search queries and click-through rates
* Measure search relevance and effectiveness
* Understand which results users interact with
* Optimize your search experience based on user behavior
* Send custom analytics events

<Note>
  Algolia Insights is built on the `autocomplete-plugin-algolia-insights` package, which integrates seamlessly with DocSearch.
</Note>

## Setup

To enable analytics, pass the `insights` configuration to DocSearch:

```jsx theme={null}
import { DocSearch } from '@docsearch/react';
import { createInsightsClient } from '@algolia/autocomplete-plugin-algolia-insights';
import insightsClient from 'search-insights';

function App() {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_API_KEY"
      indexName="YOUR_INDEX_NAME"
      insights={true}
    />
  );
}
```

<Tip>
  Setting `insights={true}` enables basic click analytics. For advanced use cases, you can pass a custom insights configuration.
</Tip>

## How It Works

When insights are enabled, DocSearch automatically:

1. Adds `clickAnalytics` parameter to search requests
2. Includes `userToken` to identify anonymous users
3. Tracks `clickedObjectIDsAfterSearch` events when users select results
4. Sends events to Algolia Insights API

### Search Request Changes

With insights enabled, search parameters include:

```typescript theme={null}
{
  query: 'search term',
  clickAnalytics: true,
  userToken: 'anonymous-user-id',
  // ... other parameters
}
```

### Click Event Tracking

When a user clicks a search result:

```typescript theme={null}
const insightsClickParams = {
  eventName: 'Item Selected',
  index: 'YOUR_INDEX_NAME',
  items: [hit],
  positions: [position],
  queryID: hit.__autocomplete_queryID,
};

state.context.algoliaInsightsPlugin.insights
  .clickedObjectIDsAfterSearch(insightsClickParams);
```

## Advanced Configuration

For more control over insights tracking, pass a custom configuration:

```jsx theme={null}
import { DocSearch } from '@docsearch/react';
import aa from 'search-insights';

// Initialize insights client
aa('init', {
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_API_KEY',
  useCookie: true,
});

function App() {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_API_KEY"
      indexName="YOUR_INDEX_NAME"
      insights={{
        insightsClient: aa,
        onSelect: (event) => {
          const { item, state } = event;
          
          // Custom analytics logic
          console.log('User selected:', item);
          
          // Send to your own analytics
          gtag('event', 'search_result_click', {
            search_term: state.query,
            result_url: item.url,
          });
        },
      }}
    />
  );
}
```

## Event Types

DocSearch tracks these Algolia Insights events:

### Click Events

**Event Name**: `Item Selected`

Triggered when a user clicks on a search result.

```typescript theme={null}
{
  eventName: 'Item Selected',
  index: 'docs',
  objectIDs: ['unique-hit-id'],
  positions: [1],
  queryID: 'query-id-from-algolia',
}
```

### Search Events

Automatically tracked with `clickAnalytics: true` in search parameters.

## User Token Management

Algolia Insights uses user tokens to track individual users across sessions:

```jsx theme={null}
import aa from 'search-insights';

// Set a custom user token
aa('setUserToken', 'user-12345');

// Or use anonymous token (default)
aa('setUserToken', aa.getAnonymousUserToken());
```

### Custom User Token

If you have authenticated users, set their user ID:

```jsx theme={null}
import { DocSearch } from '@docsearch/react';
import aa from 'search-insights';
import { useEffect } from 'react';

function App({ user }) {
  useEffect(() => {
    if (user?.id) {
      aa('setUserToken', user.id);
    }
  }, [user]);

  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_API_KEY"
      indexName="YOUR_INDEX_NAME"
      insights={true}
    />
  );
}
```

## Custom Analytics Integration

Combine Algolia Insights with your existing analytics platform:

### Google Analytics 4

```jsx theme={null}
import { DocSearch } from '@docsearch/react';

function App() {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_API_KEY"
      indexName="YOUR_INDEX_NAME"
      insights={{
        onSelect: ({ item, state }) => {
          // Send to GA4
          gtag('event', 'search_result_click', {
            search_term: state.query,
            item_id: item.objectID,
            item_name: item.hierarchy.lvl1,
            item_url: item.url,
          });
        },
        onActive: ({ item, state }) => {
          // Track result hover/keyboard navigation
          gtag('event', 'search_result_view', {
            search_term: state.query,
            item_id: item.objectID,
          });
        },
      }}
    />
  );
}
```

### Mixpanel

```jsx theme={null}
import mixpanel from 'mixpanel-browser';

function App() {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_API_KEY"
      indexName="YOUR_INDEX_NAME"
      insights={{
        onSelect: ({ item, state }) => {
          mixpanel.track('Search Result Clicked', {
            query: state.query,
            resultId: item.objectID,
            resultTitle: item.hierarchy.lvl1,
            resultUrl: item.url,
            position: item.__autocomplete_id,
          });
        },
      }}
    />
  );
}
```

### Segment

```jsx theme={null}
import analytics from '@segment/analytics-next';

function App() {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_API_KEY"
      indexName="YOUR_INDEX_NAME"
      insights={{
        onSelect: ({ item, state }) => {
          analytics.track('Search Result Selected', {
            query: state.query,
            objectID: item.objectID,
            title: item.hierarchy.lvl1,
            url: item.url,
          });
        },
      }}
    />
  );
}
```

## Implementation Details

Here's how DocSearch implements insights tracking internally:

### Enable Click Analytics

```typescript theme={null}
const insightsActive = insights;

if (insightsActive) {
  searchParams = {
    ...searchParams,
    clickAnalytics: true,
  };
}
```

### Track Click Events

```typescript theme={null}
const onItemClick = React.useCallback(
  (item: InternalDocSearchHit) => {
    if (!state.context.algoliaInsightsPlugin || !item.__autocomplete_id) {
      return;
    }

    const insightsItem = item as AlgoliaInsightsHit;

    const insightsClickParams = {
      eventName: 'Item Selected',
      index: insightsItem.__autocomplete_indexName,
      items: [insightsItem],
      positions: [item.__autocomplete_id],
      queryID: insightsItem.__autocomplete_queryID,
    };

    state.context.algoliaInsightsPlugin.insights
      .clickedObjectIDsAfterSearch(insightsClickParams);
  },
  [state.context.algoliaInsightsPlugin],
);
```

### Initialize Autocomplete with Insights

```typescript theme={null}
const autocomplete = createAutocomplete({
  id: 'docsearch',
  insights: Boolean(insights),
  // ... other options
});
```

## Viewing Analytics Data

Access your search analytics in the Algolia dashboard:

<Steps>
  <Step title="Navigate to Analytics">
    Go to your Algolia dashboard and select your index
  </Step>

  <Step title="View Search Analytics">
    Click on "Analytics" in the sidebar to see:

    * Top searches
    * Search with no results
    * Click-through rates
    * Popular results
  </Step>

  <Step title="Enable Click Analytics">
    Make sure "Click Analytics" is enabled in your index settings
  </Step>
</Steps>

## Privacy Considerations

<Note>
  When using insights, consider privacy regulations like GDPR and CCPA:

  * User tokens should be anonymized or hashed
  * Provide opt-out mechanisms for tracking
  * Include analytics disclosure in your privacy policy
  * Consider cookie consent requirements
</Note>

### Cookie-less Tracking

```jsx theme={null}
import aa from 'search-insights';

aa('init', {
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_API_KEY',
  useCookie: false, // Disable cookies
});
```

### Conditional Tracking

```jsx theme={null}
function App({ hasAnalyticsConsent }) {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_API_KEY"
      indexName="YOUR_INDEX_NAME"
      insights={hasAnalyticsConsent}
    />
  );
}
```

## Troubleshooting

### Events Not Showing Up

<Steps>
  <Step title="Verify insights enabled">
    Check that `insights={true}` or insights object is passed to DocSearch
  </Step>

  <Step title="Check API key permissions">
    Ensure your API key has search and analytics permissions
  </Step>

  <Step title="Verify queryID">
    Click events require a `queryID` from search results
  </Step>

  <Step title="Check network requests">
    Look for requests to `insights.algolia.io` in browser DevTools
  </Step>
</Steps>

### Click Analytics Not Working

Make sure `clickAnalytics` is enabled in your search parameters:

```jsx theme={null}
<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_API_KEY"
  indices={[
    {
      name: 'YOUR_INDEX_NAME',
      searchParameters: {
        clickAnalytics: true,
      },
    },
  ]}
  insights={true}
/>
```

## Best Practices

<Steps>
  <Step title="Always enable insights">
    Enable insights from day one to build a baseline of analytics data.
  </Step>

  <Step title="Use consistent user tokens">
    For authenticated users, use their user ID as the token for accurate tracking across sessions.
  </Step>

  <Step title="Combine with custom analytics">
    Use both Algolia Insights and your existing analytics platform for comprehensive tracking.
  </Step>

  <Step title="Monitor search quality">
    Regularly review analytics to identify searches with low click-through rates or no results.
  </Step>

  <Step title="Respect user privacy">
    Implement proper consent mechanisms and provide opt-out options.
  </Step>

  <Step title="Test in development">
    Test insights events in development using browser DevTools to verify they're being sent correctly.
  </Step>
</Steps>

## TypeScript Interface

```typescript theme={null}
import type { AutocompleteOptions } from '@algolia/autocomplete-core';
import type { InternalDocSearchHit } from './types';

export interface DocSearchProps {
  /**
   * Insights client integration options to send analytics events.
   */
  insights?: AutocompleteOptions<InternalDocSearchHit>['insights'];
  // ... other props
}
```

The `insights` prop accepts the same configuration as the Autocomplete Insights plugin, giving you full control over analytics behavior.
