🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / Autocomplete / Guides

Redirecting searches to a URL

Redirects can enhance your autocomplete experience. For example:

  • Searching for “help” redirects users to a support page
  • Searching for a category, such as, “TV” redirects users to a category page
  • Searching for a specific product or brand redirects users to a seasonal promotional page for it
  • Searching for specific keywords related to an ongoing event, such as, “masks”, redirects users to a more specific landing page

This guide explains how to add redirects to Autocomplete using the redirect URL plugin. You can use the plugin with Algolia and non-Algolia sources.

Before you begin

Before you can add redirects to your autocomplete experience, you’ll need:

  • An Algolia index with data
  • An HTML file with a container element for the autocomplete menu
  • If you want to use redirects without the need for further frontend development, you need to set up Rules for redirects

If you don’t have an index yet, follow this guide.

Create an autocomplete instance

First, create an autocomplete instance. Create a new file index.js with the following code:

1
2
3
4
5
6
7
import { autocomplete } from '@algolia/autocomplete-js';

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

This code adds the autocomplete to a DOM element with the id attribute autocomplete. You can use a different selector by changing the container parameter. Setting openOnFocus to true ensures that the drop-down menu appears as soon as a user focuses the input.

Add the redirect plugin to Algolia sources

To add the redirect plugin to Autocomplete, install the autocomplete-plugin-redirect-url package. To create the plugin, call the createRedirectUrlPlugin function, and add it to the list of plugins.

If you’re using this plugin for an Algolia source with Rules with redirects as consequences, you must have a source defined with getSources. The source must have these properties:

See the following code for a complete example:

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
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',
  openOnFocus: true,
  plugins: [redirectUrlPlugin],
  getSources({ query }) {
    return [
      {
        sourceId: 'demo-source',
        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,
                params: {
                  // the rules configured for this demo require this context to prevent triggering in other plugin demos
                  ruleContexts: ['enable-redirect-url'],
                  hitsPerPage: 10,
                },
              },
            ],
          });
        },
      },
    ];
  },
});

Try typing “Algolia” in the search box below. The first item you see is a redirect. Either submitting the form or selecting the redirect item activates a redirection to the URL that was configured for this Rule.

Setting up redirects with non-Algolia sources

If you want to use redirects that are defined in a non-Algolia source, you can configure createRedirectUrlPlugin to customize the redirect response.

Use the transformResponse parameter to map the response from the source to the redirect object that is used by the plugin.

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
import { autocomplete } from '@algolia/autocomplete-js';
import { createRedirectUrlPlugin } from '@algolia/autocomplete-plugin-redirect-url';

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

function transformResponse(response) {
  // assumes your non-Algolia source provides redirect URLs this way
  return response.myRedirectData?.url;
}

const redirectUrlPlugin = createRedirectUrlPlugin({
  transformResponse,
});

autocomplete({
  container: '#autocomplete',
  openOnFocus: true,
  plugins: [redirectUrlPlugin],
  getSources({ query }) {
    return [
      {
        sourceId: 'demo-source',
        templates: {
          item(params) {
            const { item, html } = params;
            return html`<a class="aa-ItemLink">${item.name}</a>`;
          },
        },
        getItemInputValue({ item }) {
          return item.name;
        },
        getItems() {
          return {} // your custom results here...
        },
      },
    ];
  },
});

Control the redirect behavior

It’s possible to have multiple redirect URLs, since redirect criteria may occur for each source and their queries. In these cases, you might want to control which redirect URL is used.

By default, the first source with a redirect with its first query is the redirect. You can change this behavior with the onRedirect callback, which receives the redirects array. This array contains every detected redirect for a given query, collected either automatically for Rules with redirects as consequences or from transformResponse. For example:

1
2
3
4
5
6
7
8
9
10
[
  {
    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'],
  },
]

In this example, a query triggered three redirect URLs in the response which mapped into an array of URLs for each source. In this scenario, you can implement onRedirect to select the URL to redirect to.

The following example shows how to pass an object with options to the onRedirect callback. The options include a navigator object, which handles the redirection to the provided URL. For more information, see Keyboard navigation.

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
52
53
import { autocomplete } from '@algolia/autocomplete-js';
import { createRedirectUrlPlugin } from '@algolia/autocomplete-plugin-redirect-url';

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

function onRedirect(
  redirects,
  { event, navigator, state }
) {
  const item = redirects.find((r) => r.sourceId === 'my-source-with-two-queries');
  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 });
  }
}

const redirectUrlPlugin = createRedirectUrlPlugin({
  onRedirect,
});

autocomplete({
  container: '#autocomplete',
  openOnFocus: true,
  plugins: [redirectUrlPlugin],
  getSources({ query }) {
    return [
      {
        sourceId: 'demo-source',
        templates: {
          item(params) {
            const { item, html } = params;
            return html`<a class="aa-ItemLink">${item.name}</a>`;
          },
        },
        getItemInputValue({ item }) {
          return item.name;
        },
        getItems() {
          return {} // your custom results here...
        },
      },
    ];
  },
});

Customize rendering of redirect items

You can use the templates parameter to change the default rendering of redirect items:

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
import { autocomplete } from '@algolia/autocomplete-js';
import { createRedirectUrlPlugin } from '@algolia/autocomplete-plugin-redirect-url';

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

const templates = {
  item({ html, state }) {
    return html`<a className="myCustomClass">${state.query}</a>`;
  },
};

const redirectUrlPlugin = createRedirectUrlPlugin({
  templates,
});

autocomplete({
  container: '#autocomplete',
  placeholder: 'Search',
  openOnFocus: true,
  plugins: [redirectUrlPlugin],
  getSources({ query }) {
    return [
      {
        sourceId: 'demo-source',
        templates: {
          item(params) {
            const { item, html } = params;
            return html`<a class="aa-ItemLink">${item.name}</a>`;
          },
        },
        getItemInputValue({ item }) {
          return item.name;
        },
        getItems() {
          return {} // your custom results here...
        },
      },
    ];
  },
});
Did you find this page helpful?