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

# Add recent searches

> Learn how to include recent searches using the recent searches plugin.

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>;

<Tip>
  Autocomplete is also available as an experimental widget in InstantSearch,
  making it easier to integrate into your search experience.
  For more information,
  see the API reference for [InstantSearch.js](/doc/api-reference/widgets/autocomplete/js) or
  [React InstantSearch](/doc/api-reference/widgets/autocomplete/react).
</Tip>

Most autocomplete menus include [suggested searches](/doc/ui-libraries/autocomplete/guides/adding-suggested-searches). You can make the experience more user-friendly by adding recent searches a user has made. This UX lets users easily recall their past searches in case they want to search for them again.

## Before you begin

This guide assumes that you know HTML, CSS, and JavaScript and that you have existing HTML with an input element where you want to implement an autocomplete drop-down menu.

**Using this plugin doesn't require an Algolia application**.
If you plan on including other sections in your autocomplete such as [suggested searches](/doc/ui-libraries/autocomplete/guides/adding-suggested-searches),
you do need an Algolia <Application /> with the [Query Suggestions](/doc/guides/building-search-ui/ui-and-ux-patterns/query-suggestions/js) feature enabled.

## Get started

Begin with the following code.
Create a file called `index.js` in your `src` directory:

```js JavaScript icon=code theme={"system"}
// index.js
import { autocomplete } from "@algolia/autocomplete-js";

autocomplete({
  container: "#autocomplete",
  plugins: [],
  openOnFocus: true,
});
```

This code adds the autocomplete to a DOM element with `autocomplete` as an `id`.
Change the [`container`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-container) to [match your markup](/doc/ui-libraries/autocomplete/core-concepts/basic-configuration-options).
Setting [`openOnFocus`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-open-on-focus) to `true` ensures that the drop-down menu appears as soon as a user focuses the input.

For now, `plugins` is an empty array, but you'll learn how to add the Recent Searches [plugin](/doc/ui-libraries/autocomplete/core-concepts/plugins) next.

## Add recent searches

The Autocomplete library provides the [`createLocalStorageRecentSearchesPlugin`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-recent-searches/createLocalStorageRecentSearchesPlugin) function for creating a recent searches [plugin](/doc/ui-libraries/autocomplete/core-concepts/plugins) out-of-the-box. To use it, you need to provide a `key` and `limit`.

The `key` can be any string and is required to differentiate search histories if you have multiple Autocomplete UI elements on one page.
The `limit` defines the maximum number of recent searches to display.

```js JavaScript icon=code theme={"system"}
import { autocomplete } from "@algolia/autocomplete-js";
import { createLocalStorageRecentSearchesPlugin } from "@algolia/autocomplete-plugin-recent-searches";

const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
  key: "RECENT_SEARCH",
  limit: 5,
});

autocomplete({
  container: "#autocomplete",
  plugins: [recentSearchesPlugin],
  openOnFocus: true,
});
```

Since the `recentSearchesPlugin` reads from [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), you won't see any recent searches in your implementation until you've made some searches.
To submit a search, be sure to press `Enter` on the query.
Once you do, you'll see it appear as a recent search.

## Customize recent searches

The [`createLocalStorageRecentSearchesPlugin`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-recent-searches/createLocalStorageRecentSearchesPlugin) function
creates a functional plugin out of the box.
You may want to customize some aspects of it,
depending on your use case.
To change [`templates`](/doc/ui-libraries/autocomplete/core-concepts/templates) or other [source](/doc/ui-libraries/autocomplete/core-concepts/sources) configuration options, you can use [`transformSource`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-recent-searches/createLocalStorageRecentSearchesPlugin#param-transform-source). The function includes the original `source`, which you should return along with any options you want to add or overwrite.

For example, if you use Autocomplete as an entry point to a search results page,
you can turn recent searches into links by modifying [`getItemUrl`](/doc/ui-libraries/autocomplete/core-concepts/sources#param-get-item-url) and the [`item`](/doc/ui-libraries/autocomplete/core-concepts/templates#param-templates-item) template.

<CodeGroup>
  ```js JavaScript theme={"system"}
  const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
    // ...
    transformSource({ source }) {
      return {
        ...source,
        getItemUrl({ item }) {
          return `/search?q=${item.query}`;
        },
        templates: {
          item(params) {
            const { item, html } = params;

            return html`<a class="aa-ItemLink" href="/search?q=${item.query}">
              ${source.templates.item(params).props.children}
            </a>`;
          },
        },
      };
    },
  });
  ```

  ```jsx JSX theme={"system"}
  const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
    // ...
    transformSource({ source }) {
      return {
        ...source,
        getItemUrl({ item }) {
          return `/search?q=${item.query}`;
        },
        templates: {
          item(params) {
            const { item } = params;

            return (
              <a className="aa-ItemLink" href={`/search?q=${item.query}`}>
                {source.templates.item(params).props.children}
              </a>
            );
          },
        },
      };
    },
  });
  ```
</CodeGroup>

If you use Autocomplete on the same page as your main search and want to avoid reloading the full page when an item is selected,
you can modify your search query state when a user selects an item with [`onSelect`](/doc/ui-libraries/autocomplete/core-concepts/sources#param-on-select):

```js JavaScript icon=code theme={"system"}
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
  // ...
  transformSource({ source }) {
    return {
      ...source,
      onSelect({ item }) {
        // Assuming the refine function updates the search page state.
        refine(item.query);
      },
    };
  },
});
```

## Use your own storage

Sometimes, you may not want to use [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) for your recent search data. You may want to use [session storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) or handle recent searches on your backend. If so, you can use the [`createRecentSearchesPlugin`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-recent-searches/createRecentSearchesPlugin) to implement your own storage:

```js JavaScript icon=code theme={"system"}
import { autocomplete } from "@algolia/autocomplete-js";
import { createRecentSearchesPlugin } from "@algolia/autocomplete-plugin-recent-searches";

const recentSearchesPlugin = createRecentSearchesPlugin({
  // Implement your own storage
  storage: {
    getAll() {},
    onAdd() {},
    onRemove() {},
  },
});

autocomplete({
  container: "#autocomplete",
  openOnFocus: true,
  plugins: [recentSearchesPlugin],
});
```

## Next steps

This tutorial focuses on creating and adding recent searches to an autocomplete menu.
Most autocomplete menus include recent searches in addition to suggested searches and possibly other items.

* [Search suggestions](/doc/ui-libraries/autocomplete/guides/adding-suggested-searches)
* [Multiple results types](/doc/ui-libraries/autocomplete/guides/including-multiple-result-types)
* [Static sources](/doc/ui-libraries/autocomplete/core-concepts/sources#static-sources)
