> ## 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.

# docsearch()

> Initialize DocSearch on your documentation site

The `docsearch()` function is the main entry point for integrating DocSearch into vanilla JavaScript applications. It mounts a DocSearch component to a DOM element and returns an instance for programmatic control.

## Function Signature

```typescript theme={null}
function docsearch(props: DocSearchProps): DocSearchInstance
```

## Parameters

The `docsearch()` function accepts a single `DocSearchProps` object with the following properties:

### Core Configuration

<ParamField path="container" type="string | HTMLElement" required>
  The DOM element or CSS selector where DocSearch will be mounted.

  ```javascript theme={null}
  container: '#docsearch'
  // or
  container: document.getElementById('docsearch')
  ```
</ParamField>

<ParamField path="appId" type="string" required>
  Your Algolia application ID.
</ParamField>

<ParamField path="apiKey" type="string" required>
  Public API key with search permissions for your index.
</ParamField>

<ParamField path="indexName" type="string">
  Name of the Algolia index to query.

  <Warning>Deprecated: Use `indices` property instead. Will be removed in a future version.</Warning>
</ParamField>

<ParamField path="indices" type="Array<DocSearchIndex | string>">
  List of indices and optional search parameters to be used for search.

  ```typescript theme={null}
  indices: [
    'my-index',
    {
      name: 'blog-index',
      searchParameters: { facetFilters: ['type:blog'] }
    }
  ]
  ```
</ParamField>

### Search Customization

<ParamField path="searchParameters" type="SearchParamsObject">
  Additional Algolia search parameters to merge into each query.

  <Warning>Deprecated: Use `indices` property instead. Will be removed in a future version.</Warning>
</ParamField>

<ParamField path="placeholder" type="string">
  Placeholder text for the search input.
</ParamField>

<ParamField path="maxResultsPerGroup" type="number">
  Maximum number of hits to display per source/group.
</ParamField>

<ParamField path="initialQuery" type="string">
  Query string to prefill when opening the modal.
</ParamField>

<ParamField path="disableUserPersonalization" type="boolean">
  Disable storage and usage of recent and favorite searches.
</ParamField>

<ParamField path="recentSearchesLimit" type="number" default={7}>
  Maximum number of recent searches to save and display.
</ParamField>

<ParamField path="recentSearchesWithFavoritesLimit" type="number" default={4}>
  Maximum number of recent searches to display when there are favorited searches.
</ParamField>

### Ask AI Configuration

<ParamField path="askAi" type="DocSearchAskAi | string">
  Configuration for Ask AI mode. Pass a string assistant ID or a full config object.

  ```typescript theme={null}
  askAi: 'your-assistant-id'
  // or
  askAi: {
    assistantId: 'your-assistant-id',
    indexName: 'ai-index',
    apiKey: 'ai-api-key',
    appId: 'ai-app-id',
    suggestedQuestions: true,
    searchParameters: {
      facetFilters: ['type:docs']
    }
  }
  ```

  <Expandable title="DocSearchAskAi Properties">
    * `assistantId` (required): The assistant ID to use
    * `indexName`: Index name for AI feature (defaults to main index)
    * `apiKey`: API key for AI feature (defaults to main API key)
    * `appId`: App ID for AI feature (defaults to main app ID)
    * `suggestedQuestions`: Enable suggested questions (default: false)
    * `searchParameters`: Search parameters for AI queries
    * `agentStudio`: Enable Agent Studio backend (experimental)
  </Expandable>
</ParamField>

### Customization Functions

<ParamField path="transformItems" type="(items: DocSearchHit[]) => DocSearchHit[]">
  Hook to post-process hits before rendering.

  ```javascript theme={null}
  transformItems: (items) => {
    return items.map(item => ({
      ...item,
      content: item.content?.toUpperCase()
    }));
  }
  ```
</ParamField>

<ParamField path="hitComponent" type="function">
  Custom component to render an individual hit. Supports multiple template patterns:

  ```javascript theme={null}
  // HTML template with html helper
  hitComponent({ hit, children }, { html }) {
    return html`<div class="custom-hit">${children}</div>`;
  }

  // JSX-like template
  hitComponent({ hit, children }) {
    return <div className="custom-hit">{children}</div>;
  }
  ```

  **Parameters:**

  * `props.hit`: The search hit object
  * `props.children`: Default hit rendering
  * `helpers.html`: HTML template helper
</ParamField>

<ParamField path="resultsFooterComponent" type="function">
  Custom component rendered at the bottom of the results panel.

  ```javascript theme={null}
  resultsFooterComponent({ state }, { html }) {
    return html`<div>Total results: ${state.collections.length}</div>`;
  }
  ```

  **Parameters:**

  * `props.state`: Autocomplete state object
  * `helpers.html`: HTML template helper
</ParamField>

<ParamField path="transformSearchClient" type="(searchClient: DocSearchTransformClient) => DocSearchTransformClient">
  Hook to wrap or modify the Algolia search client.

  ```javascript theme={null}
  transformSearchClient: (searchClient) => {
    searchClient.addAlgoliaAgent('my-app', '1.0.0');
    return searchClient;
  }
  ```
</ParamField>

<ParamField path="getMissingResultsUrl" type="({ query }: { query: string }) => string">
  Builds a URL to report missing results for a given query.

  ```javascript theme={null}
  getMissingResultsUrl: ({ query }) => {
    return `https://github.com/myorg/docs/issues/new?title=Missing: ${query}`;
  }
  ```
</ParamField>

<ParamField path="navigator" type="AutocompleteNavigator">
  Custom navigator for controlling link navigation. Useful for client-side routing.

  ```javascript theme={null}
  navigator: {
    navigate({ itemUrl }) {
      router.push(itemUrl);
    }
  }
  ```
</ParamField>

### Styling and Theming

<ParamField path="theme" type="DocSearchTheme">
  Theme overrides applied to the modal and related components.

  ```javascript theme={null}
  theme: {
    primaryColor: '#5468ff',
    backgroundColor: '#ffffff'
  }
  ```
</ParamField>

<ParamField path="translations" type="DocSearchTranslations">
  Localized strings for the button and modal UI.

  ```javascript theme={null}
  translations: {
    button: {
      buttonText: 'Search',
      buttonAriaLabel: 'Search'
    },
    modal: {
      searchBox: {
        resetButtonTitle: 'Clear',
        cancelButtonText: 'Cancel'
      }
    }
  }
  ```
</ParamField>

### Lifecycle Callbacks

<ParamField path="onReady" type="() => void">
  Called once DocSearch is mounted and ready for interaction.
</ParamField>

<ParamField path="onOpen" type="() => void">
  Called when the modal opens.
</ParamField>

<ParamField path="onClose" type="() => void">
  Called when the modal closes.
</ParamField>

<ParamField path="interceptAskAiEvent" type="(initialMessage: InitialAskAiMessage) => boolean | void">
  Intercept Ask AI requests (e.g., submitting a prompt or selecting a suggested question).

  Return `true` to prevent the default modal Ask AI flow. Useful for routing Ask AI into a different UI (e.g., sidepanel) without flicker.
</ParamField>

### Advanced Options

<ParamField path="environment" type="typeof window">
  The browser environment object. Useful for testing or SSR scenarios.
</ParamField>

<ParamField path="portalContainer" type="DocumentFragment | Element">
  The container element where the modal should be portaled. Defaults to `document.body`.
</ParamField>

<ParamField path="insights" type="AutocompleteInsights">
  Insights client integration options to send analytics events.
</ParamField>

<ParamField path="keyboardShortcuts" type="DocSearchModalShortcuts">
  Configuration for keyboard shortcuts. Allows enabling/disabling specific shortcuts.

  ```javascript theme={null}
  keyboardShortcuts: {
    'Ctrl/Cmd+K': true,  // Toggle modal
    '/': false           // Disable / shortcut
  }
  ```

  **Default:** `{ 'Ctrl/Cmd+K': true, '/': true }`
</ParamField>

## Return Value

<ResponseField name="DocSearchInstance" type="object">
  Returns a [DocSearchInstance](/api/docsearch-instance) object with methods and properties for programmatic control.

  ```typescript theme={null}
  interface DocSearchInstance {
    readonly isReady: boolean;
    readonly isOpen: boolean;
    open(): void;
    close(): void;
    openAskAi(initialMessage?: InitialAskAiMessage): void;
    destroy(): void;
  }
  ```
</ResponseField>

## Usage Examples

<CodeGroup>
  ```javascript Basic Setup theme={null}
  import docsearch from '@docsearch/js';
  import '@docsearch/css';

  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_SEARCH_API_KEY',
    indexName: 'YOUR_INDEX_NAME'
  });
  ```

  ```javascript Multiple Indices theme={null}
  import docsearch from '@docsearch/js';

  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_SEARCH_API_KEY',
    indices: [
      'docs',
      {
        name: 'blog',
        searchParameters: {
          facetFilters: ['type:post']
        }
      }
    ]
  });
  ```

  ```javascript With Ask AI theme={null}
  import docsearch from '@docsearch/js';

  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_SEARCH_API_KEY',
    indexName: 'docs',
    askAi: {
      assistantId: 'YOUR_ASSISTANT_ID',
      suggestedQuestions: true
    }
  });
  ```

  ```javascript With Callbacks theme={null}
  import docsearch from '@docsearch/js';

  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_SEARCH_API_KEY',
    indexName: 'docs',
    onReady() {
      console.log('DocSearch is ready');
    },
    onOpen() {
      console.log('Search modal opened');
    },
    onClose() {
      console.log('Search modal closed');
    }
  });
  ```

  ```javascript Custom Styling theme={null}
  import docsearch from '@docsearch/js';

  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_SEARCH_API_KEY',
    indexName: 'docs',
    theme: {
      primaryColor: '#5468ff',
      backgroundColor: '#ffffff'
    },
    translations: {
      button: {
        buttonText: 'Search docs'
      }
    }
  });
  ```

  ```javascript Programmatic Control theme={null}
  import docsearch from '@docsearch/js';

  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_SEARCH_API_KEY',
    indexName: 'docs'
  });

  // Open the search modal programmatically
  document.getElementById('custom-button').addEventListener('click', () => {
    search.open();
  });

  // Check if search is ready
  if (search.isReady) {
    console.log('DocSearch is ready');
  }

  // Cleanup on page unload
  window.addEventListener('beforeunload', () => {
    search.destroy();
  });
  ```
</CodeGroup>

## TypeScript Types

```typescript theme={null}
export interface DocSearchProps extends DocSearchCallbacks {
  container: HTMLElement | string;
  appId: string;
  apiKey: string;
  indexName?: string;
  indices?: Array<DocSearchIndex | string>;
  askAi?: DocSearchAskAi | string;
  theme?: DocSearchTheme;
  placeholder?: string;
  searchParameters?: SearchParamsObject;
  maxResultsPerGroup?: number;
  transformItems?: (items: DocSearchHit[]) => DocSearchHit[];
  hitComponent?: (props: HitComponentProps, helpers?: TemplateHelpers) => JSX.Element;
  resultsFooterComponent?: (props: FooterComponentProps, helpers?: TemplateHelpers) => JSX.Element | null;
  transformSearchClient?: (searchClient: DocSearchTransformClient) => DocSearchTransformClient;
  disableUserPersonalization?: boolean;
  initialQuery?: string;
  navigator?: AutocompleteNavigator;
  translations?: DocSearchTranslations;
  getMissingResultsUrl?: ({ query }: { query: string }) => string;
  insights?: AutocompleteInsights;
  portalContainer?: DocumentFragment | Element;
  recentSearchesLimit?: number;
  recentSearchesWithFavoritesLimit?: number;
  keyboardShortcuts?: DocSearchModalShortcuts;
  environment?: typeof window;
  interceptAskAiEvent?: (initialMessage: InitialAskAiMessage) => boolean | void;
}

export interface DocSearchCallbacks {
  onReady?: () => void;
  onOpen?: () => void;
  onClose?: () => void;
}

export interface DocSearchIndex {
  name: string;
  searchParameters?: SearchParamsObject;
}
```

## Related

* [DocSearchInstance](/api/docsearch-instance) - Methods and properties for programmatic control
* [Getting Started](/quickstart) - Installation and basic setup
