- 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
Before you begin
Before adding redirects, you need an Algolia index with data and an HTML file with a container element for the Autocomplete menu.If you want to use redirects without further frontend development,
set up rules for redirects
Create an autocomplete instance
First, create an autocomplete instance. Create a new fileindex.js with the following code:
JavaScript
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 theautocomplete-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:
Set up redirects with non-Algolia sources
If you want to use redirects that are defined in a non-Algolia source, you can configurecreateRedirectUrlPlugin
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.
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 theonRedirect 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:
JavaScript
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.
Customize rendering of redirect items
You can use thetemplates
parameter to change the default rendering of redirect items: