UI libraries / Autocomplete / API reference / autocomplete-plugin-redirect-url

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

Redirection works automatically with Algolia Rules with Redirect consequences. You can customize this plugin to work with other sources.

Installation

First, install the plugin:

1
2
3
yarn add @algolia/autocomplete-plugin-redirect-url
# or
npm install @algolia/autocomplete-plugin-redirect-url

Import it in your project:

1
import { createRedirectUrlPlugin } from '@algolia/autocomplete-plugin-redirect-url';

Add a CSS theme:

The theme is compatible with the autocomplete-theme-classic package.

1
import '@algolia/autocomplete-theme-classic';

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

1
2
3
4
5
6
7
8
9
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-theme-classic"
/>

<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-redirect-url"></script>
<script>
  const { createRedirectUrlPlugin } = window['@algolia/autocomplete-plugin-redirect-url'];
</script>

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { autocomplete, getAlgoliaResults } from '@algolia/autocomplete-js';
import { createRedirectUrlPlugin } from '@algolia/autocomplete-plugin-redirect-url';
import 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
                },
              },
            ],
          });
        },
      },
    ];
  },
});

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

Redirects are stored into the state’s context with the following form:

1
2
3
4
5
{
  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 query then state.context.redirectUrlPlugin will look like:

1
2
3
4
5
6
{
  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 will not 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:

1
2
3
4
5
6
{
  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 and how to implement your own.

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 parameter. This callback function gets passed the values directly from state.context.redirectUrlPlugin.data.

Parameters

Parameter Description
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.

The following example adds redirects to all items from the my-source source. The first occurrence of the URL starting with https://www.algolia.com is used as redirect URL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 });
    }
  },
});
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.
1
2
3
4
5
const redirectUrlPlugin = createRedirectUrlPlugin({
  transformResponse(response) {
    return response.myRedirectData?.url;
  },
});
templates
type: SourceTemplates<RedirectUrlItem>

Change the default template for rendering redirect items.

1
2
3
4
5
6
7
const redirectUrlPlugin = createRedirectUrlPlugin({
  templates: {
    item({ html, state }) {
      return html`<a className="myCustomClass">${state.query}</a>`;
    },
  },
});
Did you find this page helpful?