Skip to main content

beforeInstantSearchAsyncFunction

Use this hook to run asynchronous work (for example, an external API request) before InstantSearch sets any parameters. Add several await statements to run tasks in sequence.

Parameters

This hook doesn’t accept parameters.

Returns

This hook doesn’t return a value. Return a Promise to delay InstantSearch until your work completes.

Examples

Return a Promise to pause InstantSearch while you run async work.
JavaScript
const sleep = (ms, hookName) =>
	new Promise((resolve) => {
		console.log("sleeping for ", ms, hookName);
		setTimeout(resolve, ms);
	});
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchAsyncFunction",
		async () => {
			console.log(
				"----------- beforeInstantSearchAsyncFunction started ----------------",
			);
			await sleep(1000, "beforeInstantSearchAsyncFunction");
		},
	);
});

beforeInstantSearchConfigurationOptions

Changes InstantSearch options.

Parameters

options
object
InstantSearch configuration options.

Returns

options
object
Modified configuration options.

Examples

Update InstantSearch options before it initializes.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchConfigurationOptions",
		(options) => {
			// Modify default options, then return them
			options.numberLocale = "fr";
			options.stalledSearchDelay = 500;

			return options;
		},
	);
});

beforeInstantSearchOptions

Changes the following parameters:

Parameters

options
object
InstantSearch options with the following properties:
  • colors
  • distinct
  • facets
  • hitsPerPage
  • selector
  • sortOrders

Returns

options
object
Modified InstantSearch options.

beforeInstantSearchAllowParamsArray

Preserves URL parameters when navigating through the search results.

Parameters

allowParamsArray
string[]
URL parameter names to preserve.

Returns

allowParamsArray
string[]
Modified parameter names.

Examples

Add ref to the allowlist so InstantSearch preserves it in the URL.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchAllowParamsArray",
		function () {
			// Add a new search parameter
			const allowParamsArray = [...arguments, "ref"];
			return allowParamsArray;
		},
	);
});

beforeInstantSearchFiltersString

Changes the filter parameter of the search results page.

Parameters

defaultFilter
string
Default (may be empty).

Returns

filters
string
Filters to apply.

Examples

Append a price filter to the existing filter string, if present.
JavaScript
// Modify default `defaultFilter` if it exists
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchFiltersString",
		(defaultFilter) => {
			// Modify or replace the default string, then return a string
			if (defaultFilter) {
				return defaultFilter + " AND price > 5";
			} else {
				return "price > 5";
			}
		},
	);
});

beforeInstantSearchMainTemplate

Template for the main template container. If you’re using the facet display feature, include a div with class="ais-facets-container" to display the facets.

Parameters

_defaultTemplate
Default template.
data
object
Contains facets and configuration.
html
Tagged template function for rendering HTML.

Returns

template
Template to render.

Examples

Return a custom page layout that includes facet, stats, and results containers.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchMainTemplate",
		(_defaultTemplate, data, html) => html`
      <div class="ais-page">
        <h1 class="ais-h2">${algoliaShopify.translations.searchTitle}</h1>
        <div class="ais-input">
          <div class="ais-search-box-container"></div>
          <div class="ais-input-button">
            <div class="ais-clear-input-icon"></div>
          </div>
        </div>
        <div class="ais-facets-button">
          ${algoliaShopify.translations.showFilters}
        </div>
        <div class="ais-facets">
          <div class="ais-clear-refinements-container"></div>
          <div class="ais-current-refined-values-container"></div>
          ${
						algoliaShopify.config.app_blocks_dynamic_widgets_beta_enabled
							? html`
                <div class="ais-dynamic-widgets-container"></div>
              `
							: data.facets.map(
									(facet) =>
										html`
                    <div
                      class="ais-facet-dropdown-wrapper ais-facet-${facet.type} ais-facet-${facet.escapedName}"
                    >
                      <label
                        for="${facet.escapedName}"
                        class="ais-range-slider--header ais-facet--header ais-header"
                        >${facet.title}</label
                      >
                      <input
                        class="ais-dropdown-checkbox"
                        type="checkbox"
                        id="${facet.escapedName}"
                        name="dropdown"
                      />
                      <div
                        class="ais-facet-${facet.escapedName}-container ais-facet-dropdown-container"
                      ></div>
                    </div>
                  `,
								)
					}
        </div>
        <div class="ais-block">
          <div class="ais-search-header">
            <div class="ais-stats-container"></div>
            <div class="ais-change-display">
              <span class="ais-change-display-block ais-change-display-selected"
                ><i class="fa fa-th-large"></i
              ></span>
              <span class="ais-change-display-list"
                ><i class="fa fa-th-list"></i
              ></span>
            </div>
            <div class="ais-sort">
              ${
								data.multipleSortOrders
									? html`
                    ${algoliaShopify.translations.sortBy}
                    <span class="ais-sort-orders-container"></span>
                  `
									: html`
                    ${algoliaShopify.translations.sortBy}
                    ${algoliaShopify.translations.relevance}
                  `
							}
            </div>
          </div>
          <div class="ais-hits-container ais-results-as-block"></div>
        </div>
        <div class="ais-pagination-container"></div>
      </div>
    `,
	);
});

beforeInstantSearchProductTemplate

Template for product hits in the search results. When using this template, also call algoliaShopify.helpers.handleItemClick(item) to properly handle events.

Parameters

_defaultTemplate
Default template.
hit
object
Product hit.
html
Tagged template function for rendering HTML.
components
object
InstantSearch components (like Highlight).

Returns

template
Template to render.

Examples

Return a custom product-hit template and call algoliaShopify.helpers.handleItemClick(hit) to track events.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchProductTemplate",
		(_defaultTemplate, hit, html, components) => html`
      <div
        class="ais-hit ais-product"
        data-algolia-index="${hit.index}"
        data-algolia-position="${hit.productPosition}"
        data-algolia-queryid="${hit.queryID}"
        data-algolia-objectid="${hit.objectID}"
        data-handle="${hit.handle}"
        data-variant-id="${hit.objectID}"
        data-distinct="${hit._distinct}"
        data-product-id="${hit.id}"
        onClick="${() => algoliaShopify.helpers.handleItemClick(hit)}"
      >
        <img
          class="ais-hit--picture"
          src="${algoliaShopify.helpers.mediumImage(hit)}"
          alt="${hit.title} - ${hit.variant_title}"
        />

        <div class="ais-hit--details">
          <p class="ais-hit--title">
            <a
              data-algolia-index="${hit.index}"
              data-algolia-position="${hit.productPosition}"
              data-algolia-queryid="${hit.queryID}"
              data-algolia-objectid="${hit.objectID}"
              href="${algoliaShopify.helpers.instantsearchLink(hit)}"
              title="${algoliaShopify.helpers.fullTitle(
								hit.title,
								hit._distinct,
								hit.variant_title,
							)}"
            >
              ${components.Highlight({ attribute: "title", hit })}
              ${algoliaShopify.helpers.variantTitleAddition(hit, hit._distinct)}
            </a>
          </p>
          <p
            class="ais-hit--subtitle"
            title="${hit.product_type}${algoliaShopify.translation_helpers.by(
							hit.vendor,
						)}"
          >
            ${components.Highlight({ attribute: "product_type", hit })}
            ${
							hit.vendor &&
							html`
                <span> ${algoliaShopify.translations.by} </span>
              `
						}
            ${hit.vendor && components.Highlight({ attribute: "vendor", hit })}
          </p>
          <p class="ais-hit--price">
            <b>${algoliaShopify.helpers.displayPrice(hit, hit._distinct)}</b>
            ${
							!hit._distinct &&
							html`
                <span class="ais-hit--price-striked"
                  ><span
                    >${algoliaShopify.helpers.displayStrikedPrice(
											hit.price,
											hit.compare_at_price,
										)}</span
                  ></span
                >
              `
						}
            ${
							!hit._distinct &&
							html`
                <span class="ais-hit--price-discount"
                  >${algoliaShopify.helpers.displayDiscount(
										hit.price,
										hit.compare_at_price,
										hit.price_ratio,
									)}</span
                >
              `
						}
          </p>
          <!-- Extra info examples - Remove the display: none to show them -->
          <p class="ais-hit--info" style="display: none">
            ${
							hit.sku &&
							html`
                <span class="algolia-sku"
                  >${components.Highlight({ attribute: "sku", hit })}</span
                >
              `
						}
            ${
							hit.barcode &&
							html`
                <span class="algolia-barcode"
                  >${components.Highlight({ attribute: "barcode", hit })}</span
                >
              `
						}
            ${
							hit.weight &&
							html`
                <span class="algolia-weight">${hit.weight}</span>
              `
						}
            ${
							!hit.taxable &&
							html`
                <span class="algolia-taxable"
                  >${algoliaShopify.translations.taxFree}</span
                >
              `
						}
          </p>
          <!-- Tags example - Remove the display: none to show them -->
          <p class="ais-hit--tags" style="display: none">
            ${hit?._highlightResult.tags?.map(
							(tag) =>
								html`
                  <span class="ais-hit--tag">${tag.value}</span>
                `,
						)}
          </p>
          ${
						!hit._distinct &&
						html`
              <form
                id="algolia-add-to-cart-${hit.objectID}"
                style="display: none;"
                action="/cart/add"
                method="post"
                enctype="multipart/form-data"
              >
                <input type="hidden" name="id" value="${hit.objectID}" />
              </form>
              <p class="ais-hit--cart">
                ${
									hit.can_order
										? html`
                      <button
                        class="ais-hit--cart-button"
                        data-form-id="algolia-add-to-cart-${hit.objectID}"
                      >
                        ${algoliaShopify.translations.addToCart}
                      </button>
                    `
										: html`
                      <button
                        class="ais-hit--cart-button ais-hit--cart-button__disabled"
                      >
                        ${algoliaShopify.translations.outOfStock}
                      </button>
                    `
								}
              </p>
            `
					}
        </div>
      </div>
    `,
	);
});

beforeInstantSearchNoResultTemplate

Template for when there are no results.

Parameters

_defaultTemplate
Default template.
html
Tagged template function for rendering HTML.

Returns

template
Template to render.

Examples

Replace the default empty state with a custom template.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchNoResultTemplate",
		(_defaultTemplate, html) => html`
      <div class="ais-hit-empty">
        <div class="ais-hit-empty--title">
          ${algoliaShopify.translations.noResultFound}
        </div>
        <div class="ais-hit-empty--clears">
          ${algoliaShopify.translations.try} ${" "}
          <a class="ais-hit-empty--clear-filters ais-link">
            ${algoliaShopify.translations.clearFilters} ${" "}
          </a>
          ${algoliaShopify.translations.or} ${" "}
          <a class="ais-hit-empty--clear-input ais-link">
            ${algoliaShopify.translations.changeInput}
          </a>
        </div>
      </div>
    `,
	);
});

beforeInstantSearchStatsTemplate

Template for search stats

Parameters

_defaultTemplate
Default template.
data
object
Contains search statistics, for example nbHits, page, and hitsPerPage.
html
Tagged template function for rendering HTML.

Returns

template
Template to render.

Examples

Customize the stats template for one or many results.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchStatsTemplate",
		(_defaultTemplate, data, html) => html`
      ${
				data.hasOneResult &&
				html`
          <span class="ais-stats--nb-results">
            1 result found
          </span>
        `
			}
      ${
				data.hasManyResults &&
				html`
          ${data.page * data.hitsPerPage + 1} - ${" "}
          ${Math.min((data.page + 1) * data.hitsPerPage, data.nbHits)} ${" "}
          out of
          <span class="ais-stats--nb-results">
            ${" "} ${algoliaShopify.helpers.formatNumber(data.nbHits)} ${" "}
            results found
          </span>
        `
			}
      ${" "} in ${data.processingTimeMS / 1000}s
    `,
	);
});

beforeInstantSearchTransformItems

Change items before they’re rendered.

Parameters

transformedItems
array
Search result items.
items
array
Original items.

Returns

items
array
Modified items.

Examples

Set can_order to false for items with inventory_quantity equal to 0.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchTransformItems",
		(transformedItems, items) => {
			// Mark out-of-stock items
			return transformedItems.map((item) => {
				if (item.inventory_quantity === 0) {
					item.can_order = false;
				}
				return item;
			});
		},
	);
});

beforeInstantSearchStartAddWidgets

Add InstantSearch widgets to the search results page. You can add the following widgets:
  • rangeSlider
  • menu
  • refinementList
  • searchBox
  • stats
  • sortBy
  • clearRefinements
  • panel
  • hits
  • pagination
  • configure

Returns

widgets
array
InstantSearch widgets.

Examples

Add a searchBox widget before InstantSearch adds default widgets.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchStartAddWidgets",
		() => {
			// Not all widgets are available
			const { searchBox } = window.algoliaShopify.externals.widgets;

			const searchBoxWidget = searchBox({
				container: "#search-box",
			});

			return [searchBoxWidget];
		},
	);
});

afterInstantSearchStartRemoveDefaultWidgets

Remove default widgets from the search results page. You can remove these widgets (widget.$$widgetType):
  • ais.sortBy
  • ais.searchBox
  • ais.stats
  • ais.hits
  • ais.pagination

Parameters

defaultWidgets
array
Default InstantSearch widgets.

Returns

widgets
array
Widgets to remove.

Examples

Remove the default pagination widget.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"afterInstantSearchStartRemoveDefaultWidgets",
		(defaultWidgets) => {
			// Find and return the default pagination widget to remove it
			const defaultPaginationWidget = defaultWidgets.find(
				(widget) => widget.$$widgetType === "ais.pagination",
			);

			return [defaultPaginationWidget];
		},
	);
});

beforeInstantSearchFacetSearchablePlaceholder

Changes the searchablePlaceholder for facet search.

Parameters

placeholder
string
Default placeholder text.

Returns

placeholder
string
Modified placeholder text.

Examples

Override the facet search placeholder text.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchFacetSearchablePlaceholder",
		(placeholder) => "Search facets:",
	);
});

beforeInstantSearchFacetParamsOptions

Update widget parameters before they’re rendered.

Parameters

params
object
Widget parameters. Parameters depend on the widget type. Use facet.type to determine the widget.
facet
object
Facet metadata (read-only):

Returns

params
object
Modified widget parameters.

Examples

Adjust facet widget parameters based on facet.title or facet.type.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchFacetParamsOptions",
		(params, facet) => {
			if (facet.title == "Tags") {
				return {
					...params,
					limit: 5,
					templates: {
						searchableNoResults(data, { html }) {
							return html`<span>No results</span>`;
						},
					},
				};
			}

			if (facet.title == "Vendor") {
				return {
					...params,
					transformItems(items) {
						return items.map((item) => ({
							...item,
							label: item.label.toUpperCase(),
						}));
					},
				};
			}

			if (facet.type == "slider") {
				return {
					...params,
					pips: false,
					tooltips: true,
				};
			}

			return {
				...params,
			};
		},
	);
});

beforeInstantSearchFacetPanelOptions

Update the panel parameters before they’re rendered.

Parameters

params
object
Panel parameters. For more information, see panel.
facet
object
Facet metadata (read-only):
  • title
  • name

Returns

params
object
Modified panel parameters.

Examples

Customize panel templates like header, footer, and searchableNoResults.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchFacetPanelOptions",
		(params, facet) => {
			if (facet.name == "tags" || facet.title == "Tags") {
				return {
					...params,
					templates: {
						// To avoid duplicate headers use the `beforeInstantSearchMainTemplate` hook and remove the  'ais-facet-dropdown-wrapper' container
						header(options, { html }) {
							if (options.results) {
								return html`<span class="ais-facet--header">Tags Header (${options.results.nbHits} results)</span>`;
							}
						},
					},
				};
			}

			if (facet.type == "disjunctive") {
				return {
					...params,
					templates: {
						footer(options, { html }) {
							if (options.results) {
								return html`<span class="ais-facet--footer">Disjunctive footer (${options.results.nbHits} results)</span>`;
							}
						},
						searchableNoResults(data, { html }) {
							return html`<span>No results</span>`;
						},
					},
				};
			}

			return {
				...params,
			};
		},
	);
});

beforeInstantSearchInitSearchSortOrders

Transform sort order before they’re rendered.

Parameters

sortOrders
array
Sort order objects, each with:
  • name (string): display name for the sort order
  • value (string): name for the sort order

Returns

sortOrders
array
Modified sort orders.

Examples

Add a custom sort option to the sort-by widget.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchInitSearchSortOrders",
		(sortOrders) => {
			// Add a custom sort order
			sortOrders.push({
				name: "Most Popular",
				value: "shopify_products_popularity_desc",
			});
			return sortOrders;
		},
	);
});

beforeInstantSearchInitCollectionSortOrders

Transform the sort order for collections.

Parameters

sortOrders
array
Sort order objects, each with:
  • name (string): display name for the sort order
  • value (string): name for the sort order

Returns

sortOrders
array
Modified sort orders.

Examples

Add a custom sort option for collections.
JavaScript
document.addEventListener("algolia.hooks.initialize", () => {
	algoliaShopify.hooks.registerHook(
		"beforeInstantSearchInitCollectionSortOrders",
		(sortOrders) => {
			// Add a custom collection sort order
			sortOrders.push({
				name: "Newest First",
				value: "shopify_collections_created_at_desc",
			});
			return sortOrders;
		},
	);
});

afterInstantSearchHitClickAction (deprecated)

This hook is deprecated. Use beforeInstantSearchProductTemplate instead.
Runs after a user clicks a search result. Return a function to override the default click behavior.

Parameters

_
any
First parameter (unused).
hit
object
Product search result (hit) that was clicked.

Returns

onClick
Function to run on click.

beforeInstantSearchFacetItemTemplate (deprecated)

This hook is deprecated. Use beforeInstantSearchFacetParamsOptions instead. The refinementList widget can be added as a parameter in the template object.
Template for rendering facet items.

Parameters

_defaultTemplate
Default template.
item
object
Facet.
html
Tagged template function for rendering HTML.

beforeInstantSearchShowMoreTemplate (deprecated)

This hook is deprecated. Use beforeInstantSearchFacetParamsOptions instead. The refinementList widget can be added as a parameter within the template object.
Template for the showMoreText button.

Parameters

_defaultTemplate
Default template.
data
object
Contains the isShowingMore property.
html
Tagged template function for rendering HTML.

beforeInstantSearchFacetLimitNumber (deprecated)

This hook is deprecated. Use beforeInstantSearchFacetParamsOptions instead. The refinementList widget can be added as a parameter.
Changes the limit (default: 10).

Parameters

limit
number
default:"10"
Default limit.

Returns

limit
number
New limit.

beforeISFacetSearchablePlaceholderString (deprecated)

This hook is deprecated. Use beforeInstantSearchFacetSearchablePlaceholder or beforeInstantSearchFacetParamsOptions instead. The searchablePlaceholder option can be added as a parameter in the template object.
Changes the searchablePlaceholder.

Parameters

placeholder
string
Default placeholder text.

Returns

placeholder
string
Modified placeholder text.

beforeISFacetSearchableNoResultsString (deprecated)

This hook is deprecated. Use beforeInstantSearchFacetParamsOptions instead. The searchableNoResults option can be added as a parameter in the template object.
Changes the searchableNoResults.

Parameters

noResultsText
string
Default “no results” text.

Returns

noResultsText
string
Modified “no results” text (string or template literal).

beforeInstantSearchFacetHeaderString (deprecated)

This hook is deprecated. Use beforeInstantSearchFacetPanelOptions instead. The header parameter can be added as a parameter in the template object. To avoid duplicate headers, use the beforeInstantSearchMainTemplate hook and remove the ais-facet-dropdown-wrapper container.
Changes the facet header string.

Parameters

headerString
string
Default facet header.

Returns

headerString
string
Modified facet header.

beforeInstantSearchFacetTransformItemsOptions (deprecated)

This hook is deprecated. Use beforeInstantSearchFacetParamsOptions instead. Use transformItems as a parameter to transform the data.
Transforms items before they’re rendered.

Parameters

options
object
Transform items options.

Returns

options
object
Modified options.

beforeISTransformItems (deprecated)

This hook is deprecated. Use beforeInstantSearchTransformItems instead.
Change items before they’re rendered.

Parameters

transformedItems
array
Transformed items.
items
array
Original items.

Returns

items
array
Modified items.

afterISStartRemoveDefaultWidget (deprecated)

This hook is deprecated. Use afterInstantSearchStartRemoveDefaultWidgets instead.
Remove default widgets from the search results page. You can remove these widgets (widget.widgetType):
  • ais.sortBy
  • ais.searchBox
  • ais.stats
  • ais.hits
  • ais.pagination

Parameters

defaultWidgets
array
Default InstantSearch widgets.

Returns

widgets
array
Widgets to remove.

beforeISearchInitSortOrdersArray (deprecated)

This hook is deprecated. Use beforeInstantSearchInitSearchSortOrders instead.
Transform sort order before they’re rendered.

Parameters

sortOrders
array
Sort orders.

Returns

sortOrders
array
Modified sort orders.

beforeISStartAddWidgetArray (deprecated)

This hook is deprecated. Use beforeInstantSearchStartAddWidgets instead.
Add InstantSearch widgets to the search results page. You can add the following widgets:
  • rangeSlider
  • menu
  • refinementList
  • searchBox
  • stats
  • sortBy
  • clearRefinements
  • panel
  • hits
  • pagination
  • configure

Returns

widgets
array
InstantSearch widgets.

beforeISInitCollectionSortOrdersArray (deprecated)

This hook is deprecated. Use beforeInstantSearchInitCollectionSortOrders instead.
Transform the sort order for collections.

Parameters

sortOrders
array
Sort orders.

Returns

sortOrders
array
Modified sort orders.

See also

Last modified on February 19, 2026