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

# autocomplete

> Shows search results as users type their query in a search box.

> [!NOTE]
>
> You are viewing the documentation for **InstantSearch.js v4**.
> To upgrade from v3, see the [migration guide](https://www.algolia.com/doc/guides/building-search-ui/upgrade-guides/js.md#upgrade-from-v3-to-v4).
> Looking for the v3 version of this page?
> [View the v3 docs](https://algolia.com/old-docs/deprecated/instantsearch/js/v3/api-reference/autocomplete).

```ts Signature theme={"system"}
autocomplete({
  container: string | HTMLElement;
  // Optional parameters
  indices?: array,
  feeds?: array,
  showQuerySuggestions?: object,
  showPromptSuggestions?: object,
  showRecent?: boolean | object,
  transformItems?: function,
  onSelect?: function,
  getSearchPageURL?: function,
  searchParameters?: object,
  templates?: object,
  cssClasses?: object,
  escapeHTML?: boolean,
  placeholder?: string,
  autofocus?: boolean,
  detachedMediaQuery?: string,
  translations?: object,
  aiMode?: boolean,
  requiresSearch?: boolean,
})
```

## Import

```js Package manager theme={"system"}
import { autocomplete } from "instantsearch.js/es/widgets";
```

```js CDN theme={"system"}
const { autocomplete } = instantsearch.widgets;
// or directly use instantsearch.widgets.autocomplete()
```

## About this widget

The `autocomplete` widget is one of the most common widgets in a search UI.
With this widget, users can get search results as they type their query.

This widget includes a `showQuerySuggestions` feature that displays query suggestions from a separate index (An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.).

> [!NOTE]
>
> The widget defers registering and querying its indices until the user first focuses the search input.
> This avoids unnecessary network requests on page load.
> When [`autofocus`](#param-autofocus) is enabled, the input is focused on load, so the indices are registered immediately.

## Examples

```jsx theme={"system"}
autocomplete({
  container: '#autocomplete',
  showQuerySuggestions: {
    indexName: 'query_suggestions',
    getURL: (item) => `/search?q=${item.query}`,
  },
  indices: [
    {
      indexName: 'instant_search',
      getQuery: (item) => item.name,
      getURL: (item) => `/search?q=${item.name}`,
      templates: {
        header: (_, { html }) => html`<div>Products</div>`,
        item: ({ item, onSelect }, { html }) =>
          html`<div onClick=${onSelect}>${item.name}</div>`,
      },
    },
  ],
})
```

## Options

**container** `string | HTMLElement` *required*

The CSS Selector or `HTMLElement` to insert the widget into.

```js string theme={"system"}
autocomplete({
  container: "#autocomplete",
});
```

```js HTMLElement theme={"system"}
autocomplete({
  container: document.querySelector("#autocomplete"),
});
```

**indices** `array`

An array of objects that define the indices to query and how to display the results.
Use either `indices` or [`feeds`](#param-feeds).

* `indexName`: the name of the index to query
* `getQuery`: preprocess the query before it's sent for search
* `getURL`: update the URL to send the search request
* `searchParameters`: additional [search parameters](https://www.algolia.com/doc/api-reference/api-parameters) to send with the search request
* `templates`: the [templates](#templates) to use for the index
* `cssClasses`: CSS classes to customize the appearance.
  * `root`: the index section root element.
  * `list`: the list of results.
  * `header`: the section header.
  * `item`: each result item.
  * `noResults`: the no results element.

```js JavaScript icon=code theme={"system"}
autocomplete({
  indices: [
    {
      indexName: "instant_search",
      getQuery: (item) => item.name,
      getURL: (item) => `/search?q=${item.name}`,
      searchParameters: {
        hitsPerPage: 5,
      },
      templates: {
        header: ({ items }, { html }) =>
          html`<div>Products (${items.length} results)</div>`,
        item: ({ item, onSelect }, { html, components }) =>
          html`<div onClick=${onSelect}>
            ${components.ReverseHighlight({ hit: item, attribute: 'name' })}
          </div>`,
      },
    },
  ],
});
```

**feeds** `array`

An array of feed configurations that populate the panel from a single [multifeed composition](https://www.algolia.com/doc/guides/compositions/multifeed-compositions.md) response instead of querying separate `indices`.
Use `feeds` to display several result sets that come from one composition.

The `feeds` and `indices` options are mutually exclusive.
To use `feeds`, you need a composition-based InstantSearch instance (the `compositionID` option must be set on [`instantsearch`](https://www.algolia.com/doc/api-reference/widgets/instantsearch/js)).
See the [`feeds`](https://www.algolia.com/doc/api-reference/widgets/feeds/js) widget for the standalone equivalent.

Each feed configuration supports these properties:

* `feedID`: the ID of the feed in the composition response. Each `feedID` must be unique, including feed IDs used in `showQuerySuggestions` and `showPromptSuggestions`.
* `getQuery`: preprocess the query before it's sent for search.
* `getURL`: update the URL to send the search request.
* `templates`: the [templates](#templates) to use for the feed.
* `cssClasses`: CSS classes to customize the appearance.
  * `root`: the feed section root element.
  * `list`: the list of results.
  * `header`: the section header.
  * `item`: each result item.
  * `noResults`: the no results element.

```js JavaScript icon=code theme={"system"}
autocomplete({
  feeds: [
    {
      feedID: "products",
      getQuery: (item) => item.name,
      getURL: (item) => `/search?q=${item.name}`,
      templates: {
        header: ({ items }, { html }) =>
          html`<div>Products (${items.length} results)</div>`,
        item: ({ item, onSelect }, { html, components }) =>
          html`<div onClick=${onSelect}>
            ${components.ReverseHighlight({ hit: item, attribute: 'name' })}
          </div>`,
      },
    },
  ],
});
```

**showQuerySuggestions** `object`

Configures the query suggestions feature.

When `feeds` is set, reference the suggestions feed with `feedID` instead of `indexName`.

* `indexName`: the name of the index to query for suggestions.
* `feedID`: the ID of the suggestions feed in the composition response. Use this property when `feeds` is set. It replaces `indexName`.
* `getURL`: update the URL to send the search request.
* `templates`: the [templates](#templates) to use for the suggestions.
* `cssClasses`: CSS classes to customize the appearance.
  * `root`: the index section root element.
  * `list`: the list of results.
  * `header`: the section header.
  * `item`: each result item.
  * `noResults`: the no results element.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  showQuerySuggestions: {
    indexName: "query_suggestions",
    getURL: (item) => `/search?q=${item.query}`,
    templates: {
      header: ({ items }, { html }) =>
        html`Suggestions (${items.length} results)`,
      item: ({ item, onSelect }, { html, components }) =>
        html`<div onClick=${onSelect}>
          ${components.ReverseHighlight({ hit: item, attribute: 'query' })}
        </div>`,
    },
  },
});
```

**showPromptSuggestions** `object`

Configures the prompt suggestions feature.
Shows prompt suggestions from a separate index (An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.).
When users select a suggestion,
it's sent to a [Chat](https://www.algolia.com/doc/api-reference/widgets/chat/js.md) widget in the same index.

When `feeds` is set, reference the prompt suggestions feed with `feedID` instead of `indexName`.

* `indexName`: the name of the index to query for prompt suggestions.
* `feedID`: the ID of the suggestions feed in the composition response. Use this property when `feeds` is set. It replaces `indexName`.
* `getURL`: a function that returns the URL to open when a user selects a prompt suggestion.
* `templates`: the [templates](#templates) to use for the prompt suggestions.
* `cssClasses`: CSS classes to customize the appearance.
  * `root`: the index section root element.
  * `list`: the list of results.
  * `header`: the section header.
  * `item`: each result item.
  * `noResults`: the no results element.
* `searchParameters`: additional [search parameters](https://www.algolia.com/doc/api-reference/api-parameters) to send with the request when `indices` is set.

> [!NOTE]
>
> To open the chat and send messages, `showPromptSuggestions` requires a `chat()` widget in the same index.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  showPromptSuggestions: {
    indexName: "prompt_suggestions",
    templates: {
      header: ({ items }, { html }) =>
        html`Ask me anything (${items.length} suggestions)`,
      item: ({ item, onSelect }, { html }) =>
        html`<div onClick=${onSelect}>${item.prompt}</div>`,
    },
  },
});
```

**showRecent** `boolean | object`

Configures the recent searches feature.
Displays previously searched queries stored in local storage.

When set to `true`, uses default settings. When set to an object, you can configure:

* `storageKey`: the key to use in local storage (default: `ais.recentSearches`)
* `templates`: the [templates](#templates) to use for the recent searches
  * `header`: template for the header above the recent searches list
  * `item`: template for each recent search item
* `cssClasses`: CSS classes to customize the appearance.
  * `root`: the index section root element.
  * `list`: the list of results.
  * `header`: the section header.
  * `item`: each result item.
  * `noResults`: the no results element.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  showRecent: true,
});

// With customization
autocomplete({
  // ...
  showRecent: {
    storageKey: 'my-app-recent-searches',
    templates: {
      header: ({ items }, { html }) =>
        html`<div>Recent Searches</div>`,
      item: ({ item, onSelect, onRemoveRecentSearch }, { html, components }) =>
        html`<div>
          <button onClick=${onSelect}>
            ${components.ReverseHighlight({ hit: item, attribute: 'query' })}
          </button>
          <button onClick=${onRemoveRecentSearch}>×</button>
        </div>`,
    },
  },
});
```

**transformItems** `function`

Transforms the items before they're displayed.
This function receives an array of index configurations with their hits and should return an array in the same format.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  transformItems(indices) {
    return indices.map((index) => ({
      ...index,
      hits: index.hits.map((hit) => ({
        ...hit,
        _highlightResult: {
          ...hit._highlightResult,
          name: {
            ...hit._highlightResult.name,
            value: hit._highlightResult.name.value.toUpperCase(),
          },
        },
      })),
    }));
  },
});
```

**searchParameters** `object`

Additional [search parameters](https://www.algolia.com/doc/api-reference/api-parameters) to send with the search request for every index.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  searchParameters: {
    hitsPerPage: 5,
  },
});
```

**templates** `object`

The [templates](#templates) to use for the widget.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  templates: {
    // ...
  },
});
```

**cssClasses** `object`

The [CSS classes you can override](https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js.md#style-your-widgets)
and pass to the widget's elements.
It's useful to style widgets with class-based CSS frameworks like [Bootstrap](https://getbootstrap.com)
or [Tailwind CSS](https://tailwindcss.com).

**Root and detached shell:**

* `root`: the widget's root element.
* `detachedOverlay`: the detached overlay backdrop.
* `detachedContainer`: the detached container.
* `detachedFormContainer`: the detached form container.
* `detachedSearchButton`: the detached search button.
* `detachedSearchButtonIcon`: the detached search button icon wrapper.
* `detachedSearchButtonSearchIcon`: the detached search button search icon.
* `detachedSearchButtonPlaceholder`: the detached search button placeholder.
* `detachedSearchButtonQuery`: the detached search button query.
* `detachedSearchButtonClear`: the detached search button clear button.
* `detachedSearchButtonClearIcon`: the detached search button clear icon.

**Panel:**

* `panel`: the panel root element.
* `panelOpen`: the panel root element when open.
* `panelLayout`: the panel layout element.

**Search form:**

* `form`: the search form.
* `inputWrapperPrefix`: the input prefix area (contains submit button and loading indicator).
* `backButton`: the back button (detached mode).
* `backButtonIcon`: the back button icon.
* `label`: the submit label.
* `submitButton`: the submit button.
* `submitButtonIcon`: the submit button icon.
* `loadingIndicator`: the loading indicator.
* `loadingIndicatorIcon`: the loading indicator icon.
* `inputWrapper`: the input wrapper.
* `input`: the search input.
* `inputWrapperSuffix`: the input suffix area (contains reset button and AI mode button).
* `resetButton`: the reset/clear button.
* `resetButtonIcon`: the reset/clear button icon.
* `aiModeButton`: the AI mode button.
* `aiModeButtonIcon`: the AI mode button icon.
* `aiModeButtonLabel`: the AI mode button label.

Each source (`indices`, `showQuerySuggestions`, `showPromptSuggestions`, `showRecent`) also accepts its own `cssClasses` for styling result items.
See their respective options for details.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  cssClasses: {
    root: "MyCustomAutocomplete",
    form: "MyCustomAutocompleteForm",
    input: "MyCustomAutocompleteInput",
    submitButton: "MyCustomAutocompleteSubmit",
    resetButton: "MyCustomAutocompleteReset",
    panel: "MyCustomAutocompletePanel",
  },
});
```

**escapeHTML** `boolean` (default: true)

Whether to escape HTML in the item templates.
Set this to `false` only if you fully trust your data and templates.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  escapeHTML: false,
});
```

**onSelect** `function`

A function that's called when the user selects an item. If not provided, the default implementation:

* navigates to the URL of an item if the index configuration defines `getURL()`
* or navigates to the URL of the search page if autocomplete isn't in a search page and `getSearchPageURL()` is defined
* or otherwise refines the query

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  onSelect({ query, setQuery, url }) {
    if (inSearchPage && !url) {
      setQuery(query);
      return;
    }
    
    window.location.href = url || `/search?q=${query}`;
  },
});
```

**getSearchPageURL** `function`

A function that returns the URL of the search page for a given search state.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  getSearchPageURL(nextUiState) {
    return `/search?q=${qs.stringify(nextUiState)}`;
  },
});
```

**placeholder** `string`

Placeholder text for the search input.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  placeholder: "Search for products...",
});
```

**autofocus** `boolean` (default: false)

Whether to focus the input and open the panel by default.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  autofocus: true,
});
```

**detachedMediaQuery** `string` (default: (max-width: 680px))

Media query to enable detached (mobile) mode.
When the media query matches, the autocomplete switches to a full-screen overlay with a modal interface optimized for mobile devices.
In detached mode, the search form shows a back button (`.ais-AutocompleteBackButton`) to close the overlay.

Set to an empty string to turn off detached mode.
When omitted, it defaults to the CSS variable `--ais-autocomplete-detached-media-query`, or `"(max-width: 680px)"` if the variable isn't set.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  detachedMediaQuery: "(max-width: 768px)",
});

// Disable detached mode
autocomplete({
  // ...
  detachedMediaQuery: "",
});
```

**translations** `object`

Text labels for detached mode controls.

* `detachedCancelButtonText`: label for the detached cancel button.
* `detachedSearchButtonTitle`: title for the detached search button.
* `detachedClearButtonTitle`: title for the detached clear button.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  translations: {
    detachedCancelButtonText: "Close",
    detachedSearchButtonTitle: "Search",
    detachedClearButtonTitle: "Reset",
  },
});
```

**aiMode** `boolean` (default: false)

Whether to show an AI Mode button in the search input.
When users click this button, it opens the [Chat](https://www.algolia.com/doc/api-reference/widgets/chat/js.md) widget and sends the current query.

To use this option, add a `chat()` widget on the same index.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  aiMode: true,
});
```

**requiresSearch** `boolean` (default: true)

Whether the widget makes InstantSearch require a main search request.
By default (`true`), the widget contributes to the main search.
Set it to `false` to opt the widget out of the main search: if it's the only widget on the page, no main search request is sent.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  requiresSearch: false,
});
```

## Templates

You can customize parts of a widget's UI using the Templates API.

Each template includes an `html` function,
which you can use as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates).
This function safely renders templates as HTML strings and works directly in the browser—no build step required.
For details, see [Templating your UI](https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js.md#templating-your-ui).

> [!NOTE]
>
> The `html` function is available in InstantSearch.js version 4.46.0 or later.

**panel** `function`

Use the `template` option to customize how the panel is rendered.
This is useful when implementing layouts with multiple rows or columns.

The template receives an object containing:

* `elements`: a key-value dictionary of indices to render. These include regular index names, and special elements like `recent`, `suggestions`, and `promptSuggestions`, if applicable.
* `indices`: an array containing the data for each index.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  templates: {
    panel: ({ elements, indices }, { html }) => html`
      <div>
        <p>My custom panel</p>
        <div class="left">${elements.suggestions}</div>
        <div class="right">${elements.instant_search}</div>
      </div>
    `,
  },
});
```

**indices\[\*].templates.header** `function`

The template to use for the header, before the list of items for that index.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  indices: [
    {
      // ...
      templates: {
        header: ({ items }, { html }) => {
          return html`<div>Products (${items.length} results)</div>`;
        }
      },
    },
  ],
});
```

**indices\[\*].templates.item** `function`

The template to use for each item that's returned by the search query on that index.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  indices: [
    {
      // ...
      templates: {
        item: ({ item, onSelect }, { html, components }) => {
          return html`<div onClick=${onSelect}>
            ${components.ReverseHighlight({ hit: item, attribute: 'name' })}
          </div>`;
        }
      },
    },
  ],
});
```

**indices\[\*].templates.noResults** `function`

The template to use when an index doesn't return any results.
If an index defines a `noResults` template,
the panel stays visible even when all indices don't return any results,
so you can display a helpful message.

```js JavaScript icon=code theme={"system"}
autocomplete({
  // ...
  indices: [
    {
      // ...
      templates: {
        noResults: (_, { html }) => {
          return html`<div>No results found. Try a different query.</div>`;
        }
      },
    },
  ],
});
```
