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

# createRedirectUrlPlugin

> The Redirect URL plugin lets you redirect your Autocomplete results to a specified URL.

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </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>

The Redirect URL plugin lets you redirect your Autocomplete results to a specified URL.

Redirection works automatically with Algolia Rules with [redirect consequences](/doc/guides/managing-results/rules/merchandising-and-promoting#redirect-to-url).
You can customize this plugin to work with other sources.

## Installation

First, install the plugin:

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

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

Import it in your project:

```js JavaScript icon=code theme={"system"}
import { createRedirectUrlPlugin } from "@algolia/autocomplete-plugin-redirect-url";
```

Add a CSS theme:

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

The theme is compatible with the [`autocomplete-theme-classic`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-theme-classic) package.

If you don't use a package manager, add the following `script` elements to your HTML:

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

## Examples

<CodeGroup>
  ```js JavaScript theme={"system"}
  import { autocomplete, getAlgoliaResults } from "@algolia/autocomplete-js";
  import { createRedirectUrlPlugin } from "@algolia/autocomplete-plugin-redirect-url";
  import { liteClient as algoliasearch } from "algoliasearch/lite";

  import "@algolia/autocomplete-theme-classic";

  const appId = "latency";
  const apiKey = "6be0576ff61c053d5f9a3225e2a90f76";
  const searchClient = algoliasearch(appId, apiKey);

  const redirectUrlPlugin = createRedirectUrlPlugin();

  autocomplete({
    container: "#autocomplete",
    placeholder: "Search",
    openOnFocus: true,
    plugins: [redirectUrlPlugin],
    getSources({ query }) {
      return [
        {
          sourceId: "products",
          templates: {
            item(params) {
              const { item, html } = params;

              return html`<a class="aa-ItemLink">${item.name}</a>`;
            },
          },
          getItemInputValue({ item }) {
            return item.name;
          },
          getItems() {
            return getAlgoliaResults({
              searchClient,
              queries: [
                {
                  indexName: "instant_search",
                  query,
                  // note: these params are optional and relevant to the source and data used for this demo
                  params: {
                    ruleContexts: ["enable-redirect-url"], // triggers rules configured only with this context
                    hitsPerPage: 10, // prevents the dropdown from displaying too many items
                  },
                },
              ],
            });
          },
        },
      ];
    },
  });
  ```

  ```jsx JSX theme={"system"}
  import { autocomplete, getAlgoliaResults } from "@algolia/autocomplete-js";
  import { createRedirectUrlPlugin } from "@algolia/autocomplete-plugin-redirect-url";
  import { liteClient as algoliasearch } from "algoliasearch/lite";

  import "@algolia/autocomplete-theme-classic";

  const appId = "latency";
  const apiKey = "6be0576ff61c053d5f9a3225e2a90f76";
  const searchClient = algoliasearch(appId, apiKey);

  const redirectUrlPlugin = createRedirectUrlPlugin();

  autocomplete({
    container: "#autocomplete",
    placeholder: "Search",
    openOnFocus: true,
    plugins: [redirectUrlPlugin],
    getSources({ query }) {
      return [
        {
          sourceId: "products",
          templates: {
            item(params) {
              const { item } = params;

              return <a class="aa-ItemLink">${item.name}</a>;
            },
          },
          getItemInputValue({ item }) {
            return item.name;
          },
          getItems() {
            return getAlgoliaResults({
              searchClient,
              queries: [
                {
                  indexName: "instant_search",
                  query,
                  // These parameterss are optional and relevant to the source and data used for this demo
                  params: {
                    ruleContexts: ["enable-redirect-url"], // Triggers rules configured only with this context
                    hitsPerPage: 10, // Prevents the drop-down menu from displaying too many items
                  },
                },
              ],
            });
          },
        },
      ];
    },
  });
  ```
</CodeGroup>

The Redirect URL plugin is initialized with the `createRedirectUrlPlugin` function.
This will handle all Algolia rules that have redirect consequences without the need for any extra configuration.
Note that this plugin requires a source to be provided to `autocomplete` with the `sourceId`, `templates`, `getItemInputValue`, and `getItems` parameters to work.

By default, redirect data is mapped to `response.renderingContent?.redirect?.url` from Algolia's response.
If you've defined redirects differently in your Rules,
you can change the mapping with the [`transformResponse`](#param-transform-response) parameter.

Redirects are stored into the state's [context](/doc/ui-libraries/autocomplete/core-concepts/context) with the following form:

```js JavaScript icon=code theme={"system"}
{
  data: [{ sourceId: "my-source", urls: ["https://www.algolia.com"] }];
}
```

If your Autocomplete source is configured with multiple sources and
there are redirects triggered on both for the current <SearchQuery />
then `state.context.redirectUrlPlugin` will look like:

```js JavaScript icon=code theme={"system"}
{
  data: [
    { sourceId: "my-source-1", urls: ["https://www.algolia.com"] },
    { sourceId: "my-source-2", urls: ["https://www.algolia.com/hello-world"] },
  ];
}
```

Notice `data` now has two items in the array, which correspond to each source.
Each entry has the `sourceId` provided to maintain that mapping.
If you have two sources and one of them lacks a redirect,
then note that rather than be listed with an empty `urls` array,
it won't be listed in `state.context.redirectUrlPlugin` at all.

If you go a step further and have multiple sources configured with multiple queries,
and redirects are found for each, then `state.context.redirectUrlPlugin` may now look like:

```js JavaScript icon=code theme={"system"}
{
  data: [
    { sourceId: "my-source-with-one-query", urls: ["https://www.algolia.com"] },
    {
      sourceId: "my-source-with-two-queries",
      urls: ["https://www.algolia.com", "https://www.algolia.com/hello-world"],
    },
  ];
}
```

Notice in the preceding example that there are still two entries.
However, in the second source, there are two redirect objects in the `urls` array.
These correspond to two queries that were made in the source configuration.

The second parameter provides access to the following properties,
`{ event, navigator, state }`. `navigator` handles the actual redirection with the provided URL.
For more information, see [Integrating keyboard navigation](/doc/ui-libraries/autocomplete/core-concepts/keyboard-navigation).

Redirects are triggered when users either submits the form or selects the redirect item from the drop-down menu.
By default, the first possible redirect is chosen
(the first source in `state.context.redirectUrlPlugin.data` and its first URL),
but this behavior can be overridden with the [`onRedirect`](#param-on-redirect) parameter.
This callback function gets passed the values directly from `state.context.redirectUrlPlugin.data`.

## Parameters

<ParamField body="onRedirect" type="(redirects: RedirectUrlItem[], options: OnRedirectOptions<RedirectUrlItem>) => void">
  The function that runs when triggering a redirect—either when submitting the form or when selecting an item.

  By default, the first redirect URL is used.
  When a search might trigger a redirect from multiple sources,
  you can use `onRedirect` to control which redirect URL to use.

  ```js JavaScript icon=code theme={"system"}
  const redirectUrlPlugin = createRedirectUrlPlugin({
    onRedirect(redirects, { event, navigator, state }) {
      const item = redirects.find(({ sourceId }) => sourceId === "my-source");

      const itemUrl = item?.urls?.find((url) =>
        url.startsWith("https://www.algolia.com"),
      );

      if (!itemUrl) {
        return;
      }

      if (event.metaKey || event.ctrlKey) {
        navigator.navigateNewTab({ itemUrl, item, state });
      } else if (event.shiftKey) {
        navigator.navigateNewWindow({ itemUrl, item, state });
      } else {
        navigator.navigate({ itemUrl, item, state });
      }
    },
  });
  ```
</ParamField>

<ParamField body="transformResponse" type="(response: TransformResponseParams<TItem>) => string | undefined">
  A callback function for mapping a response to a redirect URL.

  * This is useful if you have a non-Algolia source.
  * Can be used with Algolia sources as well if using custom user data instead of a redirect consequence.
  * Gets passed the redirect data this plugin processes and stores in `state.context.redirectUrlPlugin.data`.
  * Overrides mapping the redirect URL provided from a rule with a redirect consequence.

  ```js JavaScript icon=code theme={"system"}
  const redirectUrlPlugin = createRedirectUrlPlugin({
    transformResponse(response) {
      return response.myRedirectData?.url;
    },
  });
  ```
</ParamField>

<ParamField body="templates" type="SourceTemplates<RedirectUrlItem>">
  Change the default template for rendering redirect items.

  <CodeGroup>
    ```js JavaScript theme={"system"}
    const redirectUrlPlugin = createRedirectUrlPlugin({
      templates: {
        item({ html, state }) {
          return html`<a className="myCustomClass">${state.query}</a>`;
        },
      },
    });
    ```

    ```jsx JSX theme={"system"}
    const redirectUrlPlugin = createRedirectUrlPlugin({
      templates: {
        item({ state }) {
          return <a className="myCustomClass">${state.query}</a>;
        },
      },
    });
    ```
  </CodeGroup>
</ParamField>
