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

# createRecentSearchesPlugin

> This plugin lets you implement your own storage.

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

The `createRecentSearchesPlugin` plugin lets you implement your own storage.
To connect with the user's [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage),
check [`createLocalStorageRecentSearchesPlugin`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-recent-searches/createLocalStorageRecentSearchesPlugin).

<Card title="Open CodeSandbox" icon="codesandbox" href="https://codesandbox.io/s/github/algolia/autocomplete/tree/next/examples/query-suggestions-with-recent-searches">
  Run and edit the createRecentSearchesPlugin example in CodeSandbox.
</Card>

## Installation

First, you need to install the plugin.

<CodeGroup>
  ```sh npm theme={"system"}
  npm install @algolia/autocomplete-plugin-recent-searches
  ```

  ```sh yarn theme={"system"}
  yarn add @algolia/autocomplete-plugin-recent-searches
  ```
</CodeGroup>

Then import it in your project:

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

If you don't use a package manager, you can use the HTML `script` element:

```html HTML icon=code-xml theme={"system"}
<script
  src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-recent-searches@1.19.9/dist/umd/index.production.js"
  integrity="sha256-jKoLPMdNVipXJ5otUs3DwuZeaX1kytBq2HleXEo4G7E="
  crossorigin="anonymous"
></script>
<script>
  const { createRecentSearchesPlugin } =
    window["@algolia/autocomplete-plugin-recent-searches"];
</script>
```

## Example

This example uses the plugin within [`autocomplete-js`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js).
You're in charge of implementing the storage to fetch and save recent searches.

```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],
});
```

For example, you can connect it to a MongoDB database using [mongoose](https://mongoosejs.com/).

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

mongoose.connect("mongodb://localhost:27017/myapp", { useNewUrlParser: true });

const schema = new mongoose.Schema({
  objectID: String,
  query: String,
  category: {
    type: String,
    default: undefined,
  },
});
const RecentSearchesItem = mongoose.model("RecentSearchesItem", schema);

const recentSearchesPlugin = createRecentSearchesPlugin({
  storage: {
    async getAll(query) {
      const items = await RecentSearchesItem.find({});

      return search({ query, items, limit: 5 });
    },
    onAdd(item) {
      RecentSearchesItem.create(item);
    },
    onRemove(objectID) {
      RecentSearchesItem.deleteOne({ objectID });
    },
  },
});
```

You can combine this plugin with the [Query Suggestions](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-query-suggestions)
plugin to populate the empty screen with recent and popular queries.

```js JavaScript icon=code theme={"system"}
import { liteClient as algoliasearch } from "algoliasearch/lite";
import { autocomplete } from "@algolia/autocomplete-js";
import { createRecentSearchesPlugin } from "@algolia/autocomplete-plugin-recent-searches";
import { createQuerySuggestionsPlugin } from "@algolia/autocomplete-plugin-query-suggestions";

const searchClient = algoliasearch(
  "latency",
  "6be0576ff61c053d5f9a3225e2a90f76",
);
const recentSearchesPlugin = createRecentSearchesPlugin({
  // Implement your own storage
  storage: {
    getAll() {},
    onAdd() {},
    onRemove() {},
  },
});
const querySuggestionsPlugin = createQuerySuggestionsPlugin({
  searchClient,
  indexName: "instant_search_demo_query_suggestions",
  getSearchParams() {
    return recentSearches.data.getAlgoliaSearchParams();
  },
});

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

## Parameters

<ParamField body="storage" type="RecentSearchesStorage" required>
  The storage to fetch from and save recent searches into.

  ```ts TypeScript icon=code theme={"system"}
  type RecentSearchesItem = {
    id: string;
    query: string;
  };
  type RecentSearchesStorage<TItem extends RecentSearchesItem> = {
    onAdd(item: TItem): void;
    onRemove(id: string): void;
    getAll(query?: string): MaybePromise<Array<Highlighted<TItem>>>;
  };
  ```
</ParamField>

<ParamField body="transformSource" type="function">
  ```ts Type definition theme={"system"}
  (params: {
    source: AutocompleteSource,
    state: AutocompleteState,
    onRemove: () => void,
    onTapAhead: () => void,
  })
  ```

  This function takes the original [source](/doc/ui-libraries/autocomplete/core-concepts/sources)
  as a parameter and returns a modified version of that source.

  **Example: change Autocomplete state**

  Usually, when a link in the Autocomplete menu is selected, the menu closes.
  However, to keep the menu visible after a selection is made,
  use `transformSource` to set the `isOpen` [state](/doc/ui-libraries/autocomplete/core-concepts/state):

  ```js JavaScript icon=code theme={"system"}
  const recentSearchesPlugin = createRecentSearchesPlugin({
    storage,
    transformSource({ source, onRemove }) {
      return {
        ...source,
        onSelect({ setIsOpen }) {
          setIsOpen(true);
        },
      };
    },
  });
  ```

  **Example: create links**

  Turns Query Suggestions into clickable Google search links:

  <CodeGroup>
    ```js JavaScript icon=code theme={"system"}
    const recentSearchesPlugin = createRecentSearchesPlugin({
      storage,
      transformSource({ source, onRemove }) {
        return {
          ...source,
          getItemUrl({ item }) {
            return `https://google.com?q=${item.query}`;
          },
          templates: {
            ...source.templates,
            item(params) {
              const { item, html } = params;

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

    ```jsx JSX icon=code theme={"system"}
    const recentSearchesPlugin = createRecentSearchesPlugin({
      storage,
      transformSource({ source, onRemove }) {
        return {
          ...source,
          getItemUrl({ item }) {
            return `https://google.com?q=${item.query}`;
          },
          templates: {
            ...source.templates,
            item(params) {
              const { item } = params;

              return (
                <a
                  classbody="aa-ItemLink"
                  href={`https://google.com?q=${item.query}`}
                >
                  {source.templates.item(params).props.children}
                </a>
              );
            },
          },
        };
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="translations" type="AutocompleteRecentSearchesPluginTranslations">
  ```ts TypeScript icon=code theme={"system"}
  type AutocompleteRecentSearchesPluginTranslations = {
    removeSearchTitle: string; // defaults to 'Remove this search'
    fillQueryTitle: (text: string) => string; // defaults to 'Fill query with "${text}"'
  };
  ```

  A dictionary of translations to support internationalization.
</ParamField>

## Returns

### `data`

<ParamField body="getAlgoliaSearchParams" type="SearchParameters => SearchParameters">
  Optimized [Algolia search parameters](/doc/api-reference/search-api-parameters).
  This is useful when using the plugin along with the [Query Suggestions](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-query-suggestions/createQuerySuggestionsPlugin) plugin.

  This function enhances the provided search parameters by:

  * Excluding Query Suggestions that are already displayed in recent searches.
  * Using a shared hitsPerPage value to get a group limit of Query Suggestions and recent searches.
</ParamField>

<ParamField body="addItem" type="(item: TItem) => void">
  A function that adds an item to the recent searches storage.
</ParamField>

<ParamField body="removeItem" type="(id: string) => void">
  A function that removes an item from the recent searches storage.
</ParamField>

<ParamField body="getAll" type="() => TItem[]">
  A function that returns the items from the recent searches storage.
</ParamField>
