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

# InstantSearch custom hooks

> Custom hooks that change the behavior of the search results page.

> [!NOTE]
>
> Autocomplete, InstantSearch, and Recommend in the Algolia app blocks now support version 5 of the Algolia API client.
> Most stores only need to switch the [search client version setting](https://www.algolia.com/doc/integration/shopify/getting-started/configuration.md#search-client-version) to **Version 5**.
> If you use custom storefront JavaScript, follow the [version 5 upgrade guide](https://www.algolia.com/doc/libraries/sdk/upgrade/javascript.md).
> Support for version 4 ends on August 14, 2026.

When you connect a composition, the app removes `distinct`, `facetingAfterDistinct`, `highlightPreTag`, and `highlightPostTag` from search requests.
For more information, see [Use compositions with the Shopify app](https://www.algolia.com/doc/integration/shopify/going-further/composition.md#limitations).

## `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

> [accordion] Delay InstantSearch until an async task completes
>
> Return a `Promise` to pause InstantSearch while you run async work.
>
> ```js JavaScript icon=code theme={"system"}
> 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](https://www.algolia.com/doc/api-reference/widgets/instantsearch/js.md#options).

### Returns

**options** `object`

Modified configuration options.

### Examples

> [accordion] Customize InstantSearch configuration options
>
> Update InstantSearch options before it initializes.
>
> ```js JavaScript icon=code theme={"system"}
> 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`
* `swatchRowLimit`

### Returns

**options** `object`

Modified InstantSearch options.

### Examples

> [accordion] Show fewer swatch chips in the row
>
> `swatchRowLimit` sets how many swatch chips a product-level card shows in its row.
> The rest go behind the `+N` button that opens the overflow panel.
> Set it to `0` to remove the cap, so the row holds every option and no panel renders.
>
> Every option stays on the card either way.
> To remove options altogether, use
> [`beforeInstantSearchSwatchOptionResolver`](#beforeinstantsearchswatchoptionresolver).
>
> ```js JavaScript icon=code theme={"system"}
> document.addEventListener("algolia.hooks.initialize", () => {
> 	algoliaShopify.hooks.registerHook("beforeInstantSearchOptions", (options) => {
> 		// A product with 10 options shows 6 chips and a "+4" button
> 		options.swatchRowLimit = 6;
>
> 		return 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

> [accordion] Preserve a custom URL parameter
>
> Add `ref` to the allowlist so InstantSearch preserves it in the URL.
>
> ```js JavaScript icon=code theme={"system"}
> 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](https://www.algolia.com/doc/api-reference/api-parameters/filters.md) of the search results page.

### Parameters

**defaultFilter** `string`

Default filter (A filter is a condition that limits which records Algolia returns. Filters often use one or more facet-value pairs, such as brand:Apple AND color:red. You can also filter by numeric values, dates, tags, booleans, or geographic constraints.) (may be empty).

### Returns

**filters** `string`

Filters to apply.

### Examples

> [accordion] Add a filter condition
>
> Append a price filter to the existing filter string, if present.
>
> ```js JavaScript icon=code theme={"system"}
> // 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";
> 			}
> 		},
> 	);
> });
> ```

## `beforeInstantSearchRuleContexts`

Modifies the [`ruleContexts`](https://www.algolia.com/doc/api-reference/api-parameters/ruleContexts) sent with InstantSearch queries.
Use this hook to trigger [Rules](https://www.algolia.com/doc/guides/managing-results/rules/rules-overview) based on page context, such as UTM parameters, customer segments, or custom page metadata.

On collection pages, the default contexts include the collection handle and `shopify_default_collection`.

### Parameters

**ruleContexts** `string[]`

Default rule contexts.
On collection pages, this includes the collection handle and `shopify_default_collection`.
On other pages, this is an empty array.

### Returns

**ruleContexts** `string[]`

Modified rule contexts.
Duplicates are removed and the list is limited to 10 items.

### Examples

> [accordion] Add rule contexts based on UTM parameters
>
> This example adds a rule context based on the `utm_source` URL parameter.
>
> ```js JavaScript icon=code highlight={7} theme={"system"}
> document.addEventListener("algolia.hooks.initialize", () => {
> 	algoliaShopify.hooks.registerHook(
> 		"beforeInstantSearchRuleContexts", (...rules) => {
> 			var params = new URLSearchParams(window.location.search);
> 			var utmSource = params.get("utm_source");
> 			if (utmSource) {
> 				rules.push("campaign-" + utmSource);
> 			}
> 			return rules;
> 		},
> 	);
> });
> ```

## `beforeInstantSearchMainTemplate`

Template for the main template container.

If you're using the [facet display](https://www.algolia.com/doc/integration/shopify/building-search-ui/instant-search.md#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

> [accordion] Customize the main template
>
> Return a custom page layout that includes facet, stats, and results containers.
>
> ```js JavaScript icon=code theme={"system"}
> 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 `trackSearchAttribution(hit)` to properly handle events.

### Parameters

**\_defaultTemplate**

Default template.

**hit** `object`

Product hit.
On a product-level record, `hit._productLevel` is `true` and the variants are nested under
`hit.variants`.
The chips to render are on `hit._swatchOptions`, each one shaped like the options
[the swatch resolver returns](#beforeinstantsearchswatchoptionresolver), with `_matched` on the chip
the app preselected.
See [Product cards](https://www.algolia.com/doc/integration/shopify/sending-and-managing-data/product-level-indexing.md#product-cards).

**html**

Tagged template function for rendering HTML.

**components** `object`

InstantSearch components (like `Highlight`).

**trackSearchAttribution**

Function to track search attribution.
Equivalent to `algoliaShopify.helpers.handleItemClick`.

### Returns

**template**

Template to render.

### Examples

> [accordion] Customize product hits
>
> Return a custom product-hit template and call `trackSearchAttribution(hit)` to track events.
>
> ```js JavaScript icon=code theme={"system"}
> document.addEventListener("algolia.hooks.initialize", () => {
> 	algoliaShopify.hooks.registerHook(
> 		"beforeInstantSearchProductTemplate",
> 		(_defaultTemplate, hit, html, components, trackSearchAttribution) => 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="${() => trackSearchAttribution(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>
>     `,
> 	);
> });
> ```

> [accordion] Customize product-level hits
>
> Product-level hits carry `variants[]`, so the card shows a swatch row and a price range instead of a
> single variant's price and an add-to-cart button.
> Check `hit._productLevel` and keep your variant-level template for the other branch.
>
> Keep the class names and `data-` attributes from this example.
> The app delegates chip clicks from the results container and reads them to retarget the card image,
> the title link, and the overflow panel.
>
> ```js JavaScript icon=code theme={"system"}
> document.addEventListener("algolia.hooks.initialize", () => {
> 	algoliaShopify.hooks.registerHook(
> 		"beforeInstantSearchProductTemplate",
> 		(_defaultTemplate, hit, html, components, trackSearchAttribution) => {
> 			if (!hit._productLevel) {
> 				return _defaultTemplate;
> 			}
>
> 			const swatchOptions = hit._swatchOptions || [];
> 			const matchedSwatch = swatchOptions.find((option) => option._matched);
> 			const rowLimit =
> 				algoliaShopify.instantsearch.swatchRowLimit || swatchOptions.length;
> 			const rowSwatches = swatchOptions.slice(0, rowLimit);
> 			const panelSwatches = swatchOptions.slice(rowLimit);
>
> 			const productHref = algoliaShopify.helpers.instantsearchLink(hit);
> 			const titleHref = matchedSwatch?.variantID
> 				? `${productHref}?variant=${matchedSwatch.variantID}`
> 				: productHref;
>
> 			const swatchChip = (option) => html`
>         <button
>           type="button"
>           class="ais-hit--swatch ${option._matched
> 						? "ais-hit--swatch__selected"
> 						: ""} ${option.available ? "" : "ais-hit--swatch__oos"}"
>           title="${option.name}"
>           aria-label="${option.name}"
>           aria-pressed="${option._matched ? "true" : "false"}"
>           data-swatch-name="${option.name}"
>           data-product-image="${option.productImage || ""}"
>           data-variant-id="${option.variantID || ""}"
>           style="${option.swatchImage
> 						? `background-image:url(${option.swatchImage})`
> 						: `background-color:${option.color}`}"
>         ></button>
>       `;
>
> 			return html`
>         <div
>           class="ais-hit ais-product ais-hit--product-level"
>           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="${matchedSwatch?.variantID || ""}"
>           onClick="${() => trackSearchAttribution(hit)}"
>         >
>           <img
>             class="ais-hit--picture"
>             src="${algoliaShopify.helpers.renderImage(hit, 250).src}"
>             alt="${hit.title}"
>           />
>
>           <div class="ais-hit--details">
>             ${rowSwatches.length > 0 &&
> 						html`
>               <div class="ais-hit--swatches-bar">
>                 <div class="ais-hit--swatches">
>                   ${rowSwatches.map(swatchChip)}
>                 </div>
>                 ${panelSwatches.length > 0 &&
> 								html`
>                   <button
>                     type="button"
>                     class="ais-hit--swatches-more"
>                     aria-expanded="false"
>                   >
>                     +${panelSwatches.length}
>                   </button>
>                 `}
>               </div>
>               ${panelSwatches.length > 0 &&
> 							html`
>                 <div class="ais-hit--swatches-panel">
>                   ${panelSwatches.map(swatchChip)}
>                 </div>
>               `}
>             `}
>             <p class="ais-hit--title">
>               <a href="${titleHref}">
>                 ${components.Highlight({ attribute: "title", hit })}
>               </a>
>             </p>
>             <p class="ais-hit--price">
>               <b
>                 >${algoliaShopify.helpers.displayPrice(
> 									hit,
> 									hit._distinct,
> 									hit._productLevel,
> 								)}</b
>               >
>             </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

> [accordion] Customize the no results template
>
> Replace the default empty state with a custom template.
>
> ```js JavaScript icon=code theme={"system"}
> 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`](https://www.algolia.com/doc/api-reference/widgets/stats/js)

> [!NOTE]
>
> If the active sort order uses a [virtual replica](https://www.algolia.com/doc/guides/managing-results/refine-results/sorting/in-depth/relevant-sort.md), the response includes `nbSortedHits`:
> the number of results Algolia considered were relevant enough to sort.
> Use `nbSortedHits` to show a message such as "42 relevant results sorted out of 1,247"
> instead of only the total hit count.

### Parameters

**\_defaultTemplate**

Default template.

**data** `object`

Contains search statistics, for example `nbHits`, `nbSortedHits`, `page`, and `hitsPerPage`.

**html**

Tagged template function for rendering HTML.

### Returns

**template**

Template to render.

### Examples

> [accordion] Customize the stats template
>
> Customize the stats template for one or many results.
>
> ```js JavaScript icon=code theme={"system"}
> 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](https://www.algolia.com/doc/guides/building-search-ui/upgrade-guides/js.md#transformdata-is-replaced-by-transformitems) before they're rendered.

### Parameters

**transformedItems** `array`

Search result items.

**items** `array`

Original items.

### Returns

**items** `array`

Modified items.

### Examples

> [accordion] Mark out-of-stock items
>
> Set `can_order` to `false` for items with `inventory_quantity` equal to `0`.
>
> ```js JavaScript icon=code theme={"system"}
> 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;
> 			});
> 		},
> 	);
> });
> ```

## `beforeInstantSearchSwatchOptionResolver`

Reorder or filter the swatch chips on a product-level card before the template renders them.

Only fires for product-level hits whose records carry swatch data.

> [!NOTE]
>
> An option you drop here is gone from the card, including the overflow panel.
> To keep every option but show fewer chips in the row, set `swatchRowLimit` with
> [`beforeInstantSearchOptions`](#beforeinstantsearchoptions) instead.

Each resolved option arrives as its own argument, followed by the hit, so read the arguments object
rather than named parameters.

This hook runs before the app picks the preselected chip.
An option you remove here can no longer be preselected.
To reorder chips without changing which one is preselected, use
[`beforeInstantSearchTransformItems`](#beforeinstantsearchtransformitems) and edit `_matched` on
`hit._swatchOptions`.

### Parameters

**...swatchOptions** `object`

Each resolved swatch option, spread as a separate argument.
An option has `name`, `color`, `swatchImage`, `productImage`, `variantID`, and `available`.

**hit** `object`

Product hit the chips belong to.
Arrives as the last argument, after the options.

### Returns

**swatchOptions** `array`

Swatch options to render.

### Examples

> [accordion] Show the first five in-stock swatches
>
> Drop sold-out options, then cap the row at five chips.
>
> ```js JavaScript icon=code theme={"system"}
> document.addEventListener('algolia.hooks.initialize', function() {
>   algoliaShopify.hooks.registerHook('beforeInstantSearchSwatchOptionResolver', (...hookArgs) => {
>     const swatchOptions = hookArgs.slice(0, -1); // Drop the trailing internal argument
>
>     // Drop sold-out options, then cap the row
>     return swatchOptions
>       .filter(function(option) {
>         return option.available;
>       })
>       .slice(0, 2);
>   });
> });
> ```

## `afterInstantSearchSwatchClick`

Runs after a shopper clicks a swatch chip.

The app has already marked the chip, swapped the card image, and re-pointed the card at the
selected variant before this hook runs.
This hook doesn't use a return value.

The app doesn't fire this hook for a chip it preselected on first render.

### Parameters

**swatchClick** `object`

Details of the click, with the following properties:

* `swatchButton`: element of the chip the shopper clicked.
* `hitEl`: card element that holds the chip.
* `optionValue`: name of the clicked option value.

### Examples

> [accordion] Track swatch clicks
>
> Send the clicked option value and the card's product to your analytics tool.
>
> ```js JavaScript icon=code theme={"system"}
> document.addEventListener("algolia.hooks.initialize", () => {
> 	algoliaShopify.hooks.registerHook(
> 		"afterInstantSearchSwatchClick",
> 		({ swatchButton, hitEl, optionValue }) => {
> 			window.dataLayer.push({
> 				event: "swatch_selected",
> 				option_value: optionValue,
> 				product_id: hitEl.dataset.algoliaObjectid,
> 				variant_id: swatchButton.dataset.variantId,
> 			});
> 		},
> 	);
> });
> ```

## `beforeInstantSearchStartAddWidgets`

Add InstantSearch widgets to the search results page.
You can add the following widgets:

* [`clearRefinements`](https://www.algolia.com/doc/api-reference/widgets/clear-refinements/js)
* [`configure`](https://www.algolia.com/doc/api-reference/widgets/configure/js)
* [`dynamicWidgets`](https://www.algolia.com/doc/api-reference/widgets/dynamic-widgets/js)
* [`hierarchicalMenu`](https://www.algolia.com/doc/api-reference/widgets/hierarchical-menu/js)
* [`hits`](https://www.algolia.com/doc/api-reference/widgets/hits/js)
* [`menu`](https://www.algolia.com/doc/api-reference/widgets/menu/js)
* [`pagination`](https://www.algolia.com/doc/api-reference/widgets/pagination/js)
* [`panel`](https://www.algolia.com/doc/api-reference/widgets/panel/js)
* [`rangeSlider`](https://www.algolia.com/doc/api-reference/widgets/range-slider/js)
* [`refinementList`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js)
* [`searchBox`](https://www.algolia.com/doc/api-reference/widgets/search-box/js)
* [`sortBy`](https://www.algolia.com/doc/api-reference/widgets/sort-by/js)
* [`stats`](https://www.algolia.com/doc/api-reference/widgets/stats/js)

### Returns

**widgets** `array`

InstantSearch widgets.

### Examples

> [accordion] Add a custom widget
>
> Add a `searchBox` widget before InstantSearch adds default widgets.
>
> ```js JavaScript icon=code theme={"system"}
> 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

> [accordion] Remove a default widget
>
> Remove the default pagination widget.
>
> ```js JavaScript icon=code theme={"system"}
> 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`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-searchable-placeholder) for facet search.

> [!NOTE]
>
> Use [`beforeInstantSearchFacetParamsOptions`](#beforeinstantsearchfacetparamsoptions) instead.

### Parameters

**placeholder** `string`

Default placeholder text.

### Returns

**placeholder** `string`

Modified placeholder text.

### Examples

> [accordion] Change the facet search placeholder
>
> Override the facet search placeholder text.
>
> ```js JavaScript icon=code theme={"system"}
> 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):

* `title`
* `name`
* `type` (refinement parameters)
  * `slider`: [`rangeSlider`](https://www.algolia.com/doc/api-reference/widgets/range-slider/js)
  * `menu`: [`menu`](https://www.algolia.com/doc/api-reference/widgets/menu/js)
  * `conjunctive`: [`refinementList`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js)
  * `disjunctive`: [`refinementList`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js)

### Returns

**params** `object`

Modified widget parameters.

### Examples

> [accordion] Customize facet widget parameters
>
> Adjust facet widget parameters based on `facet.title` or `facet.type`.
>
> ```js JavaScript icon=code theme={"system"}
> 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`](https://www.algolia.com/doc/api-reference/widgets/panel/js).

**facet** `object`

Facet metadata (read-only):

* `title`
* `name`

### Returns

**params** `object`

Modified panel parameters.

### Examples

> [accordion] Customize panel parameters
>
> Customize panel templates like `header`, `footer`, and `searchableNoResults`.
>
> ```js JavaScript icon=code theme={"system"}
> 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`](https://www.algolia.com/doc/api-reference/widgets/sort-by/js#param-transform-items) before they're rendered.

### Parameters

**...sortOrders** `object[]`

Sort orders, spread as individual arguments.
The last argument is reserved for internal use: use rest syntax and `slice(0, -1)` to collect the sort order objects.
Each has:

* `label` (string): display name for the sort order
* `value` (string): index (An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.) name for the sort order

### Returns

**sortOrders** `array`

Modified sort orders.

### Examples

> [accordion] Add a custom sort order
>
> Add a custom sort option to the sort-by widget.
>
> ```js JavaScript icon=code theme={"system"}
> document.addEventListener("algolia.hooks.initialize", () => {
> 	algoliaShopify.hooks.registerHook(
> 		"beforeInstantSearchInitSearchSortOrders", 
> 		(...hookArgs) => {
> 			const indexPrefix = algoliaShopify.config.index_prefix;
> 			const sortOrders = hookArgs.slice(0, -1); // Drop the trailing internal argument
>
> 			const replicaName = `price_asc_virtual`; 
> 			const primaryIndex = `${indexPrefix}products`;
> 			const sortOrderIndex = `${primaryIndex}_${replicaName}`;
>
> 			sortOrders.push({
> 				label: 'Lowest Price',
> 				value: sortOrderIndex, // shopify_products_price_asc_virtual
> 			});
> 			return sortOrders;
> 		}
> 	);
> });
> ```

## `beforeInstantSearchInitCollectionSortOrders`

Transform the sort order for collections.

### Parameters

**...sortOrders** `object[]`

Sort orders, spread as individual arguments.
The last argument is reserved for internal use: use rest syntax and `slice(0, -1)` to collect the sort order objects.
Each has:

* `label` (string): display name for the sort order
* `value` (string): index (An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.) name for the sort order

### Returns

**sortOrders** `array`

Modified sort orders.

### Examples

> [accordion] Add a custom collection sort order
>
> Add a custom sort option for collections.
>
> ```js JavaScript icon=code theme={"system"}
> document.addEventListener("algolia.hooks.initialize", () => {
> 	algoliaShopify.hooks.registerHook(
> 		"beforeInstantSearchInitCollectionSortOrders", 
> 		(...hookArgs) => {
> 			const indexPrefix = algoliaShopify.config.index_prefix;
> 			const sortOrders = hookArgs.slice(0, -1); // Drop the trailing internal argument
>
> 			const replicaName = `price_asc_virtual`; 
> 			const primaryIndex = `${indexPrefix}products`;
> 			const sortOrderIndex = `${primaryIndex}_${replicaName}`;
>
> 			sortOrders.push({
> 				label: 'Lowest Price',
> 				value: sortOrderIndex, // shopify_products_price_asc_virtual
> 			});
> 			return sortOrders;
> 		}
> 	);
> });
> ```

## `afterInstantSearchHitClickAction` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchProductTemplate`](#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)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchFacetParamsOptions`](#beforeinstantsearchfacetparamsoptions) instead.
> The [`refinementList`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js) 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)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchFacetParamsOptions`](#beforeinstantsearchfacetparamsoptions) instead.
> The [`refinementList`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js) widget can be added as a parameter within the template object.

Template for the [`showMoreText`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-show-more-text) button.

### Parameters

**\_defaultTemplate**

Default template.

**data** `object`

Contains the `isShowingMore` property.

**html**

Tagged template function for rendering HTML.

## `beforeInstantSearchFacetLimitNumber` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchFacetParamsOptions`](#beforeinstantsearchfacetparamsoptions) instead.
> The [`refinementList`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js) widget can be added as a parameter.

Changes the [`limit`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-limit) (default: 10).

### Parameters

**limit** `number` (default: 10)

Default limit.

### Returns

**limit** `number`

New limit.

## `beforeISFacetSearchablePlaceholderString` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchFacetSearchablePlaceholder`](#beforeinstantsearchfacetsearchableplaceholder) or
> [`beforeInstantSearchFacetParamsOptions`](#beforeinstantsearchfacetparamsoptions) instead.
> The [`searchablePlaceholder`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-searchable-placeholder) option can be added as a parameter in the template object.

Changes the [`searchablePlaceholder`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-searchable-placeholder).

### Parameters

**placeholder** `string`

Default placeholder text.

### Returns

**placeholder** `string`

Modified placeholder text.

## `beforeISFacetSearchableNoResultsString` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchFacetParamsOptions`](#beforeinstantsearchfacetparamsoptions) instead.
> The [`searchableNoResults`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-searchable-no-results) option can be added as a parameter in the template object.

Changes the [`searchableNoResults`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-searchable-no-results).

### Parameters

**noResultsText** `string`

Default "no results" text.

### Returns

**noResultsText** `string`

Modified "no results" text (string or template literal).

## `beforeInstantSearchFacetHeaderString` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchFacetPanelOptions`](#beforeinstantsearchfacetpaneloptions) instead.
> The [`header`](https://www.algolia.com/doc/api-reference/widgets/panel/js#param-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)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchFacetParamsOptions`](#beforeinstantsearchfacetparamsoptions) instead.
> Use `transformItems` as a parameter to transform the data.

Transforms [`items`](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js#param-items) before they're rendered.

### Parameters

**options** `object`

Transform items options.

### Returns

**options** `object`

Modified options.

## `beforeISTransformItems` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchTransformItems`](#beforeinstantsearchtransformitems) instead.

Change [items](https://www.algolia.com/doc/guides/building-search-ui/upgrade-guides/js.md#transformdata-is-replaced-by-transformitems) before they're rendered.

### Parameters

**transformedItems** `array`

Transformed items.

**items** `array`

Original items.

### Returns

**items** `array`

Modified items.

## `afterISStartRemoveDefaultWidget` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`afterInstantSearchStartRemoveDefaultWidgets`](#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)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchInitSearchSortOrders`](#beforeinstantsearchinitsearchsortorders) instead.

Transform [`sort order`](https://www.algolia.com/doc/api-reference/widgets/sort-by/js#param-transform-items) before they're rendered.

### Parameters

**sortOrders** `array`

Sort orders.

### Returns

**sortOrders** `array`

Modified sort orders.

## `beforeISStartAddWidgetArray` (deprecated)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchStartAddWidgets`](#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)

> [!NOTE]
>
> This hook is deprecated.
> Use [`beforeInstantSearchInitCollectionSortOrders`](#beforeinstantsearchinitcollectionsortorders) instead.

Transform the sort order for collections.

### Parameters

**sortOrders** `array`

Sort orders.

### Returns

**sortOrders** `array`

Modified sort orders.

## See also

* [Add custom hooks](https://www.algolia.com/doc/integration/shopify/building-search-ui/frontend-custom-events)
* [Autocomplete hooks](https://www.algolia.com/doc/integration/shopify/building-search-ui/autocomplete-hooks.md)
* [Insights and Recommend hooks](https://www.algolia.com/doc/integration/shopify/building-search-ui/insights-recommend-hooks.md)
