1 import { Table, Prerequisites, Note, CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `InstantSearch Adapter`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how to install and configure the InstantSearch adapter to build a search experience in your storefront.
10
11 <Note>
12
13 If you installed your Medusa application after v2.21.1, its storefront already has the search functionalities explained in this guide, and the Medusa application already defines the `product` index at `src/search/product.ts` and allows it on the `/store/search` API route in `src/api/middlewares.ts`. You can still follow this guide to understand how the search works and customize it.
14
15 </Note>
16
17 <Prerequisites
18 items={[
19 {
20 text: "Search Module configured with a provider",
21 link: "/infrastructure-modules/search"
22 },
23 {
24 text: "`product` search index defined and allowed on the `/store/search` API route",
25 link: "/infrastructure-modules/search#search-products"
26 },
27 {
28 text: "Medusa v2.21.1+",
29 link: "https://github.com/medusajs/medusa/releases/tag/v2.21.1"
30 }
31 ]}
32 />
33
34 ## Integrate with an AI Agent
35
36 If you use an AI agent, such as Claude Code or Codex, ask it to fetch this page:
37
38 ```bash
39 Fetch https://docs.medusajs.com/resources/instantsearch and follow the instructions.
40 ```
41
42 It will receive the following prompt with instructions on how to integrate the InstantSearch adapter into the storefront:
43
44 ```md collapsed noLineNumbers
45 <role>
46 You are a front-end engineer integrating search into an existing Medusa storefront. You work within the storefront's current framework, conventions, and styling rather than introducing new ones.
47 </role>
48
49 <task>
50 Add a product search experience to this storefront using the `@medusajs/instantsearch-adapter` package.
51 </task>
52
53 <context>
54 - Medusa's Search Module indexes data in a search engine and serves queries with filters, facets, sorting, and pagination.
55 - Medusa exposes a `/store/search` API route that searches any index of the Medusa application, so you don't create a route for product search. An index is only reachable through it once the Medusa application allows it with the `configureStoreSearch` middleware. The route narrows a product index to published products in the publishable API key's sales channels on its own, and any further scoping is that middleware's `filters` in the Medusa application, never the storefront.
56 - `@medusajs/instantsearch-adapter` provides a search client, not UI components. It converts InstantSearch requests into Medusa search queries, sends them to `/store/search`, and converts the results back.
57 - InstantSearch is a family of UI widget libraries: `react-instantsearch`, `vue-instantsearch`, `angular-instantsearch`, and `instantsearch.js` for storefronts without a framework.
58 - Everything that reads or changes the search must sit inside one `InstantSearch` provider. Where that provider lives decides the shape of the experience.
59 - A field only works with a widget if the search index definition marks it as `searchable`, `filterable`, `facetable`, or `sortable`.
60 - A range or stats widget needs the field listed in the search client's `numericAttributes` option, on top of being `facetable({ types: ["stats"] })` in the index definition. Without it, the adapter asks for value facets instead of stats, so the widget never receives `facets_stats` and renders no bounds.
61 - Consult the Medusa documentation at https://docs.medusajs.com, or the Docs MCP server if it's available, for anything this prompt doesn't cover.
62 </context>
63
64 <input>
65 You have access to the storefront's codebase. Before writing code, determine from it:
66 - The framework and package manager in use.
67 - Whether a Medusa JS SDK instance already exists, and where.
68 - The environment variables holding the Medusa backend URL and publishable API key.
69 - The components the search will live in or next to, and the UI primitives the storefront already depends on.
70 - The fields the `product` search index holds, from the Medusa application's index definition if it's available.
71 </input>
72
73 <steps>
74 1. Ask the user where the search should live and how it should behave. Offer the common shapes and let them pick or describe their own:
75 - A control in the navbar that opens a panel, such as a drawer or a modal.
76 - A field in the navbar that shows results in a dropdown beneath it.
77 - A dedicated search page with the results as the page body.
78 Ask in the same message which parts of the search they want beyond the field and the results, such as filters, sorting, or pagination. Don't start writing code until they answer.
79 2. Install `@medusajs/instantsearch-adapter` and the InstantSearch library matching the storefront's framework, using the storefront's package manager. Install `@medusajs/js-sdk` only if the storefront doesn't already have it.
80 3. Create the search client in a shared module, such as `src/lib/search-client.ts`. Pass the existing JS SDK instance if there is one; otherwise create one from the storefront's backend URL and publishable API key environment variables. Set `path` to `/store/search`, and export the index name as a constant so the UI never repeats the string.
81 4. Export the client from a shared module, so every search surface in the storefront uses the same one.
82 5. Build the search UI in the shape the user chose, with one `InstantSearch` provider wrapping the field, the results, and any other search widgets.
83 6. Render each result with the storefront's existing product card or link pattern, using only fields the index holds.
84 7. Make the search feel responsive: debounce the query so a burst of typing sends one request rather than one per keystroke, and keep the results already on screen while the next search runs.
85 8. Keep the previous results on screen, with one exception: results fetched for the empty query, once the customer has typed. The empty query matches every document, so those "previous results" are the entire index, and rendering them flashes the whole catalogue the moment the first real query goes out. Gate on that case alone, from the query the visible results were fetched for and whether there's input, such as `hasInput && !resultsQuery`. Don't treat every mismatch between the results' query and the query last sent as stale: after a debounce the two differ on nearly every keystroke, so an equality check blanks the list as the customer types, which is the flicker step 7 forbids. Leave a comment on the gate saying which case it covers, so nobody widens it later.
86 9. Give every state its own treatment: no query yet, results, no results, and a failed search. An empty list must never stand in for any of the others. Add an in-flight treatment, such as a spinner or skeleton, only for the case where there's nothing valid to show: the first search of a session, or the empty-query results that step 8 gates out. While a search runs over results that are still valid, leave those results on screen; a loading state that replaces them is the flicker step 7 avoids, and it barely appears in practice.
87 10. Place the finished component where the user asked for it.
88 11. Report what you changed and how to test it.
89 </steps>
90
91 <constraints>
92 - Never decide the search's placement or interaction yourself. That's the user's call in step 1.
93 - Never render the empty query's hits once the customer has typed.
94 - Never blank the results because the query moved on. Only the empty query's results are stale.
95 - Never place a filter in the storefront that exists to protect data. Customers can change anything the client sends.
96 - Never hardcode the publishable API key, the backend URL, or the index name. Read the first two from environment variables and the third from the exported constant.
97 - Never invent index field names. Use only fields you confirmed in an index definition or in a search response.
98 - Never add these widgets, as the adapter doesn't support them: `geoSearch`, Insights and Analytics widgets, Query Rules, related-items widgets, autocomplete, vector-search widgets, and Algolia `filters` strings.
99 - Never add a CSS framework, component library, state-management library, or UI primitive that the storefront doesn't already use. Style the search with the storefront's existing approach.
100 - Never create more than one search client or more than one `InstantSearch` provider for the same search.
101 - Never modify the Medusa application's `/store/search` route.
102 - Never create a custom API route for an index that `/store/search` already serves. Report to the user instead when an index isn't allowed on it, so they add it to the `configureStoreSearch` middleware.
103 </constraints>
104
105 <error_handling>
106 - If the user doesn't answer step 1, ask again rather than picking a placement. It's the decision the rest of the work depends on.
107 - If you can't determine the storefront's framework, ask the user instead of guessing.
108 - If the chosen shape needs a UI primitive the storefront doesn't have, ask the user before installing a library.
109 - If no index definition is available, ask the user which fields the index holds. Don't infer field names from the storefront's product types.
110 - If a search request answers with "No search index named \"product\"", the index isn't allowed on the route. Ask the user to add it to the `configureStoreSearch` middleware in their Medusa application rather than working around it.
111 - If the search request fails at runtime, surface the error in the UI and report the status code and response body. Don't fall back to an empty state that hides it.
112 - If the storefront already has a search implementation, ask whether to replace it or add alongside it before changing any file.
113 - If a range or stats widget renders no bounds, add the field to the search client's `numericAttributes` and report that the index definition needs `facetable({ types: ["stats"] })`. Don't remove the widget silently.
114 - If the work needs migrations in the Medusa application, ask the user to run `npx medusa db:migrate` themselves. The command can end in an interactive prompt to sync module links, so it hangs when you run it unattended.
115 </error_handling>
116
117 <output_format>
118 Report in this structure:
119
120 ## Approach
121 The placement and behavior the user chose, in one or two sentences.
122
123 ## Changes
124 A list of the files you created or modified, each with a one-line description.
125
126 ## Setup
127 Any environment variables the user must set, and any command they must run.
128
129 ## How to Test
130 Numbered steps that end in an observable result, including one that types a query from an empty search and confirms the full catalogue never flashes before the matches, and one that keeps typing and confirms the list never blanks between keystrokes.
131
132 ## Skipped
133 Any widget or feature you left out, each with the reason. Write "None" if there are none.
134 </output_format>
135
136 <success_criteria>
137 - The search is placed and behaves the way the user described in step 1.
138 - Typing shows matching products, and the previous results stay on screen until the new ones arrive.
139 - Typing the first query from an empty search never flashes results from the empty query.
140 - Typing further characters never blanks the list. The previous matches stay until the new ones arrive.
141 - A burst of typing sends one search request, not one per character.
142 - Each of the four states in step 9 shows something distinct from the others, and the in-flight treatment only appears when no valid results are on screen.
143 - A failed search shows an error message rather than an empty list.
144 - Every field referenced in the code exists in a search index definition.
145 - The storefront builds and type-checks with no new errors.
146 </success_criteria>
147 ```
148
149 ---
150
151 ## What is the InstantSearch Adapter?
152
153 [InstantSearch](https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/) is a family of open source UI libraries that render search interfaces from small widgets, such as a search box, a hit list, facet filters, and pagination. It's available for plain JavaScript, React, Vue, and Angular.
154
155 The `@medusajs/instantsearch-adapter` package provides a search client for Medusa. It translates each InstantSearch request into a Medusa-compatible search query, sends it to Medusa's `/store/search` API route, then maps the result back into the shape the widgets expect.
156
157 So, you install the adapter and add InstantSearch widgets instead of writing the data fetching, filter serialization, and pagination logic yourself.
158
159 <Note>
160
161 The adapter doesn't provide UI components. You install an InstantSearch library alongside it and use its widgets.
162
163 </Note>
164
165 ---
166
167 ## Step 1: Install the Adapter
168
169 In your storefront project, install the adapter and the InstantSearch library that matches your storefront's framework.
170
171 For example, if you're using a Next.js project, install the React library in the storefront:
172
173 ```bash npm2yarn title="apps/storefront"
174 npm install @medusajs/instantsearch-adapter react-instantsearch instantsearch.js
175 ```
176
177 You install `instantsearch.js` alongside `react-instantsearch` for the types it exports, such as `Hit` and `SearchClient`. The same adapter also works with `vue-instantsearch` and `angular-instantsearch`.
178
179 ---
180
181 ## Step 2: Create the Search Client
182
183 Next, create the search client that the InstantSearch widgets use.
184
185 The adapter needs a way to send requests to your Medusa application. Pass an instance of the [Medusa JS SDK](../js-sdk/page.mdx), as it sends the publishable API key and other headers for you.
186
187 For example, if you're using the default starter, it already exports an SDK instance from `apps/storefront/src/lib/config.ts`. So, create the file `apps/storefront/src/lib/search-client.ts` with the following content:
188
189 export const clientHighlights = [
190 ["6", "PRODUCT_INDEX_NAME", "The name of the index to search."],
191 ["9", "sdk", "The storefront's existing SDK instance."],
192 ["10", "path", "Medusa's storefront search route."],
193 ]
194
195 <CodeTabs group="client">
196 <CodeTab label="Default Starter" value="starter">
197
198 ```ts title="apps/storefront/src/lib/search-client.ts" highlights={clientHighlights}
199 import {
200 createInstantSearchAdapter,
201 } from "@medusajs/instantsearch-adapter"
202 import { sdk } from "@lib/config"
203
204 export const PRODUCT_INDEX_NAME = "product"
205
206 export const { searchClient } = createInstantSearchAdapter({
207 sdk: sdk,
208 path: "/store/search",
209 })
210 ```
211
212 </CodeTab>
213 <CodeTab label="Other Storefronts" value="other">
214
215 ```ts title="src/lib/search-client.ts"
216 import {
217 createInstantSearchAdapter,
218 } from "@medusajs/instantsearch-adapter"
219 import { sdk } from "./sdk"
220
221 export const PRODUCT_INDEX_NAME = "product"
222
223 export const { searchClient } = createInstantSearchAdapter({
224 sdk,
225 path: "/store/search",
226 })
227 ```
228
229 </CodeTab>
230 </CodeTabs>
231
232 The `createInstantSearchAdapter` function accepts the adapter's options and returns an object with a `searchClient` property, which you pass to InstantSearch. Export the client once and import it wherever you need it. Every search surface in your storefront uses the same one.
233
234 <Note>
235
236 If your storefront doesn't use the JS SDK, pass `baseUrl` and `publishableApiKey` instead, and the adapter uses the native `fetch` function. You can also pass a `requester` function to control the transport yourself. Refer to the [Adapter Configuration Options](#adapter-configuration-options) section for details.
237
238 </Note>
239
240 ---
241
242 ## Step 3: Add the Search Interface
243
244 Finally, add the search interface. This example puts a search button in the navbar that opens a drawer holding the search field and its results.
245
246 ### Render a Hit
247
248 Start with the component that renders a single result. Each hit's fields come from the index, so only reference the fields your index definition holds.
249
250 For example, if you're using the default starter, create the file `apps/storefront/src/modules/layout/components/search/hit.tsx` with the following content:
251
252 export const hitHighlights = [
253 ["6", "ProductHit", "The fields the `product` index holds."],
254 ["21", "handle", "Link the hit to its product page."],
255 ]
256
257 <CodeTabs group="hit">
258 <CodeTab label="Default Starter" value="starter">
259
260 ```tsx title="apps/storefront/src/modules/layout/components/search/hit.tsx" highlights={hitHighlights}
261 "use client"
262
263 import type { Hit as HitType } from "instantsearch.js"
264 import LocalizedClientLink from "@modules/common/components/localized-client-link"
265
266 export type ProductHit = HitType<{
267 title: string | null
268 handle: string | null
269 thumbnail: string | null
270 }>
271
272 type SearchHitProps = {
273 hit: ProductHit
274 onNavigate?: () => void
275 }
276
277 const SearchHit = ({ hit, onNavigate }: SearchHitProps) => {
278 return (
279 <li>
280 <LocalizedClientLink
281 href={`/products/${hit.handle}`}
282 onClick={onNavigate}
283 >
284 {hit.title}
285 </LocalizedClientLink>
286 </li>
287 )
288 }
289
290 export default SearchHit
291 ```
292
293 </CodeTab>
294 <CodeTab label="Other Storefronts" value="other">
295
296 ```tsx title="src/components/search/hit.tsx"
297 import type { Hit as HitType } from "instantsearch.js"
298
299 export type ProductHit = HitType<{
300 title: string | null
301 handle: string | null
302 thumbnail: string | null
303 }>
304
305 const SearchHit = ({ hit }: { hit: ProductHit }) => (
306 <li>
307 <a href={`/products/${hit.handle}`}>{hit.title}</a>
308 </li>
309 )
310
311 export default SearchHit
312 ```
313
314 </CodeTab>
315 </CodeTabs>
316
317 InstantSearch's `Hit` type adds `objectID` to the fields you pass it, so use `hit.objectID` as the key when you render a list of hits.
318
319 ### Create the Drawer
320
321 Next, add the drawer that the search opens in.
322
323 The default starter depends on [Headless UI](https://headlessui.com/react/dialog), whose `Dialog` component brings the focus trap, the Escape key, and the backdrop click. So, the drawer only describes its own layout.
324
325 <Note>
326
327 The search doesn't depend on Headless UI. Use whichever dialog primitive your storefront has, as long as it traps focus while open.
328
329 </Note>
330
331 Create the file `apps/storefront/src/modules/layout/components/search/drawer.tsx` with the following content:
332
333 <CodeTabs group="drawer">
334 <CodeTab label="Default Starter" value="starter">
335
336 ```tsx title="apps/storefront/src/modules/layout/components/search/drawer.tsx"
337 "use client"
338
339 import { Dialog, Transition } from "@headlessui/react"
340 import { XMark } from "@medusajs/icons"
341 import React, { Fragment } from "react"
342
343 type SearchDrawerProps = {
344 isOpen: boolean
345 close: () => void
346 children: React.ReactNode
347 }
348
349 const SearchDrawer = ({
350 isOpen,
351 close,
352 children,
353 }: SearchDrawerProps) => {
354 return (
355 <Transition appear show={isOpen} as={Fragment}>
356 <Dialog
357 as="div"
358 className="relative z-[75]"
359 onClose={close}
360 >
361 <div className="fixed inset-0 bg-ui-bg-overlay" />
362
363 <div className="fixed inset-0 overflow-hidden">
364 <div className="fixed inset-y-0 right-0 flex pl-10">
365 <Transition.Child
366 as={Fragment}
367 enterFrom="translate-x-full"
368 enterTo="translate-x-0"
369 leaveFrom="translate-x-0"
370 leaveTo="translate-x-full"
371 >
372 <Dialog.Panel className="w-screen max-w-md">
373 <div className="flex h-full flex-col">
374 <div className="flex justify-between">
375 <Dialog.Title>Search</Dialog.Title>
376 <button
377 type="button"
378 onClick={close}
379 aria-label="Close search"
380 >
381 <XMark />
382 </button>
383 </div>
384 {children}
385 </div>
386 </Dialog.Panel>
387 </Transition.Child>
388 </div>
389 </div>
390 </Dialog>
391 </Transition>
392 )
393 }
394
395 export default SearchDrawer
396 ```
397
398 </CodeTab>
399 <CodeTab label="Other Storefronts" value="other">
400
401 ```tsx title="src/components/search/drawer.tsx"
402 // Any dialog primitive works. It only has to trap focus
403 // while open and close on Escape or a backdrop click.
404 const SearchDrawer = ({ isOpen, close, children }) => (
405 <Dialog open={isOpen} onClose={close}>
406 {/* ... */}
407 <DialogPanel className="drawer">
408 {children}
409 </DialogPanel>
410 </Dialog>
411 )
412
413 export default SearchDrawer
414 ```
415
416 </CodeTab>
417 </CodeTabs>
418
419 ### Render the Search Panel
420
421 Next, add the panel that holds the search field and its results, then the button that opens the drawer.
422
423 This example uses the `useSearchBox` and `useHits` hooks rather than the `SearchBox` and `Hits` widgets, which gives you the same behavior with your own markup.
424
425 Create the file `apps/storefront/src/modules/layout/components/search/index.tsx` with the following content:
426
427 export const searchHighlights = [
428 ["30", "useSearchSettled", "Whether the results match the current query."],
429 ["49", "queryHook", "Wait for a pause in typing before searching."],
430 ["63", "useSearchBox", "The current query and a function to change it."],
431 ["68", "inputValue", "The field's value, ahead of the debounced query."],
432 ["75", "hasInput", "Tell the panel's states apart."],
433 ["76", "isPending", "The field has changed, the query hasn't caught up."],
434 ]
435
436 <CodeTabs group="panel">
437 <CodeTab label="Default Starter" value="starter">
438
439 ```tsx title="apps/storefront/src/modules/layout/components/search/index.tsx" highlights={searchHighlights}
440 "use client"
441
442 import { MagnifyingGlass } from "@medusajs/icons"
443 import {
444 useCallback,
445 useEffect,
446 useRef,
447 useState,
448 } from "react"
449 import type { SearchClient } from "instantsearch.js"
450 import {
451 Configure,
452 InstantSearch,
453 useHits,
454 useInstantSearch,
455 useSearchBox,
456 } from "react-instantsearch"
457
458 import useToggleState from "@lib/hooks/use-toggle-state"
459 import {
460 PRODUCT_INDEX_NAME,
461 searchClient,
462 } from "@lib/search-client"
463 import SearchDrawer from "./drawer"
464 import SearchHit, { ProductHit } from "./hit"
465
466 const HITS_PER_PAGE = 12
467 const DEBOUNCE_MS = 250
468
469 const useSearchSettled = () => {
470 const { status, results } = useInstantSearch()
471
472 const isSearching =
473 status !== "idle" && status !== "error"
474 const hasNoResultsYet = Boolean(
475 (results as unknown as {
476 __isArtificial?: boolean
477 })?.__isArtificial
478 )
479
480 return !isSearching && !hasNoResultsYet
481 }
482
483 const SearchPanel = ({ onNavigate }: {
484 onNavigate: () => void
485 }) => {
486 const timer = useRef<number | undefined>(undefined)
487
488 const queryHook = useCallback(
489 (
490 nextQuery: string,
491 search: (value: string) => void
492 ) => {
493 window.clearTimeout(timer.current)
494 timer.current = window.setTimeout(
495 () => search(nextQuery),
496 DEBOUNCE_MS
497 )
498 },
499 []
500 )
501
502 const { query, refine } = useSearchBox({ queryHook })
503 const { items } = useHits<ProductHit>()
504 const { status, error } = useInstantSearch()
505 const isSettled = useSearchSettled()
506
507 const [inputValue, setInputValue] = useState(query)
508
509 useEffect(
510 () => () => window.clearTimeout(timer.current),
511 []
512 )
513
514 const hasInput = Boolean(inputValue.trim())
515 const isPending = inputValue.trim() !== query.trim()
516 const hasResults = Boolean(query.trim()) && items.length > 0
517
518 return (
519 <>
520 <div className="flex items-center gap-x-3 px-4">
521 <MagnifyingGlass className="shrink-0" />
522 <input
523 type="search"
524 value={inputValue}
525 onChange={(event) => {
526 setInputValue(event.target.value)
527 refine(event.target.value)
528 }}
529 placeholder="Search products"
530 aria-label="Search products"
531 autoFocus
532 className="w-full bg-transparent py-4 outline-none"
533 />
534 </div>
535
536 <div className="flex-1 overflow-y-auto">
537 {!hasInput ? (
538 <span>Start typing to search for products.</span>
539 ) : status === "error" ? (
540 <span>
541 Couldn&apos;t search products
542 {error?.message ? `: ${error.message}` : "."}
543 </span>
544 ) : !isSettled ? (
545 <span>Searching&hellip;</span>
546 ) : hasResults ? (
547 <ul className="py-2">
548 {items.map((hit) => (
549 <SearchHit
550 key={hit.objectID}
551 hit={hit}
552 onNavigate={onNavigate}
553 />
554 ))}
555 </ul>
556 ) : isPending || !query.trim() ? (
557 <span>Searching&hellip;</span>
558 ) : (
559 <span>No products found</span>
560 )}
561 </div>
562 </>
563 )
564 }
565
566 const Search = () => {
567 const { state: isOpen, open, close } = useToggleState()
568
569 return (
570 <>
571 <button
572 type="button"
573 onClick={open}
574 aria-label="Search products"
575 >
576 <MagnifyingGlass />
577 </button>
578
579 <SearchDrawer isOpen={isOpen} close={close}>
580 <InstantSearch
581 indexName={PRODUCT_INDEX_NAME}
582 searchClient={searchClient as unknown as SearchClient}
583 future={{ preserveSharedStateOnUnmount: true }}
584 >
585 <Configure hitsPerPage={HITS_PER_PAGE} />
586 <SearchPanel onNavigate={close} />
587 </InstantSearch>
588 </SearchDrawer>
589 </>
590 )
591 }
592
593 export default Search
594 ```
595
596 </CodeTab>
597 <CodeTab label="Other Storefronts" value="other">
598
599 ```tsx title="src/components/search/index.tsx"
600 import {
601 Configure,
602 InstantSearch,
603 useHits,
604 useSearchBox,
605 } from "react-instantsearch"
606
607 import {
608 PRODUCT_INDEX_NAME,
609 searchClient,
610 } from "../../lib/search-client"
611
612 const SearchPanel = () => {
613 const { query, refine } = useSearchBox()
614 const { items } = useHits()
615
616 return (
617 <>
618 <input
619 type="search"
620 value={query}
621 onChange={(e) => refine(e.target.value)}
622 />
623 {/* render the states: empty, loading, results */}
624 </>
625 )
626 }
627
628 const Search = () => (
629 <InstantSearch
630 indexName={PRODUCT_INDEX_NAME}
631 searchClient={searchClient}
632 >
633 <Configure hitsPerPage={12} />
634 <SearchPanel />
635 </InstantSearch>
636 )
637
638 export default Search
639 ```
640
641 </CodeTab>
642 </CodeTabs>
643
644 The `indexName` prop is the `name` property of your [search index definition](../infrastructure-modules/search/index-definitions/page.mdx), which the adapter sends as the query's `entity`. For the products index that Medusa provides, use `product`.
645
646 Each widget and hook then contributes to the query the adapter builds. `useSearchBox`'s `refine` function sets the free-text `q` filter, and `Configure` sets the query's `take` through its `hitsPerPage` prop.
647
648 The field stays at the top of the drawer while the results scroll below it.
649
650 <Note title="Important">
651
652 A field must be `searchable`, `filterable`, or `facetable` in your index definition before a widget can use it. Learn more in the [Index Field Modifiers guide](../infrastructure-modules/search/index-definitions/modifiers/page.mdx).
653
654 </Note>
655
656 ### Add the Search to the Navbar
657
658 Finally, render the search component in your storefront's navbar.
659
660 For example, if you're using the default starter, add it to `apps/storefront/src/modules/layout/templates/nav/index.tsx`:
661
662 <CodeTabs group="navbar">
663 <CodeTab label="Default Starter" value="starter">
664
665 ```tsx title="apps/storefront/src/modules/layout/templates/nav/index.tsx"
666 import Search from "@modules/layout/components/search"
667
668 export default async function Nav() {
669 // ...
670 return (
671 <div>
672 <header>
673 <nav>
674 <Search />
675 {/* other navbar items */}
676 </nav>
677 </header>
678 </div>
679 )
680 }
681 ```
682
683 </CodeTab>
684 <CodeTab label="Other Storefronts" value="other">
685
686 ```tsx title="src/components/navbar.tsx"
687 import Search from "./search"
688
689 const Navbar = () => (
690 <nav>
691 {/* ... */}
692 <Search />
693 </nav>
694 )
695 ```
696
697 </CodeTab>
698 </CodeTabs>
699
700 To show the full results on a dedicated search page, use the same `InstantSearch` provider with the `Pagination`, `RefinementList`, and `SortBy` widgets. Learn more in the [Supported Widgets](#supported-widgets) section.
701
702 ---
703
704 ## Step 4: Test the Search
705
706 To test the search integration:
707
708 1. Start the Medusa backend and the storefront.
709 2. Open the storefront in a browser and click the search button in the navbar.
710 3. Type a product's title or other searchable field into the search box. The panel should show matching products as you type.
711
712 ---
713
714 ## Adapter Configuration Options
715
716 `createInstantSearchAdapter` accepts the following options:
717
718 <Table>
719 <Table.Header>
720 <Table.Row>
721 <Table.HeaderCell>
722 Option
723 </Table.HeaderCell>
724 <Table.HeaderCell>
725 Description
726 </Table.HeaderCell>
727 <Table.HeaderCell>
728 Default
729 </Table.HeaderCell>
730 </Table.Row>
731 </Table.Header>
732 <Table.Body>
733 <Table.Row>
734 <Table.Cell>
735 `sdk`
736 </Table.Cell>
737 <Table.Cell>
738 A Medusa JS SDK instance. The adapter sends requests through it, so the publishable API key and other headers are included.
739 </Table.Cell>
740 <Table.Cell>
741 \-
742 </Table.Cell>
743 </Table.Row>
744 <Table.Row>
745 <Table.Cell>
746 `path`
747 </Table.Cell>
748 <Table.Cell>
749 The path of the search route, or an absolute URL. Use `/store/search` unless you added a custom route. Required unless you pass `requester`.
750 </Table.Cell>
751 <Table.Cell>
752 \-
753 </Table.Cell>
754 </Table.Row>
755 <Table.Row>
756 <Table.Cell>
757 `baseUrl`
758 </Table.Cell>
759 <Table.Cell>
760 The Medusa backend's URL. Use it with `publishableApiKey` when you don't pass `sdk`.
761 </Table.Cell>
762 <Table.Cell>
763 \-
764 </Table.Cell>
765 </Table.Row>
766 <Table.Row>
767 <Table.Cell>
768 `publishableApiKey`
769 </Table.Cell>
770 <Table.Cell>
771 The publishable API key sent in the `x-publishable-api-key` header. Only used with `baseUrl`.
772 </Table.Cell>
773 <Table.Cell>
774 \-
775 </Table.Cell>
776 </Table.Row>
777 <Table.Row>
778 <Table.Cell>
779 `requester`
780 </Table.Cell>
781 <Table.Cell>
782 A custom transport function that receives the adapted queries and returns one result per query, in the same order.
783 </Table.Cell>
784 <Table.Cell>
785 \-
786 </Table.Cell>
787 </Table.Row>
788 <Table.Row>
789 <Table.Cell>
790 `headers`
791 </Table.Cell>
792 <Table.Cell>
793 Extra headers to send with every request.
794 </Table.Cell>
795 <Table.Cell>
796 \-
797 </Table.Cell>
798 </Table.Row>
799 <Table.Row>
800 <Table.Cell>
801 `batch`
802 </Table.Cell>
803 <Table.Cell>
804 Whether to send all queries in one request as `{ queries }`. When disabled, the adapter sends each query as its own request body.
805 </Table.Cell>
806 <Table.Cell>
807 `true`
808 </Table.Cell>
809 </Table.Row>
810 <Table.Row>
811 <Table.Cell>
812 `placeholderSearch`
813 </Table.Cell>
814 <Table.Cell>
815 Whether to search when the query is empty. When disabled, the adapter returns empty results without calling the backend.
816 </Table.Cell>
817 <Table.Cell>
818 `true`
819 </Table.Cell>
820 </Table.Row>
821 <Table.Row>
822 <Table.Cell>
823 `numericAttributes`
824 </Table.Cell>
825 <Table.Cell>
826 The fields that range widgets use. The adapter requests them as `stats` facets. The index must also mark them as `facetable({ types: ["stats"] })`. If the index holds a price field per currency, list every currency's fields, as explained in [Price Fields per Currency](./examples/filtering-sorting-pagination/page.mdx#price-fields-per-currency).
827 </Table.Cell>
828 <Table.Cell>
829 \-
830 </Table.Cell>
831 </Table.Row>
832 <Table.Row>
833 <Table.Cell>
834 `distinctAttribute`
835 </Table.Cell>
836 <Table.Cell>
837 The index field to deduplicate on when a widget sends `distinct`.
838 </Table.Cell>
839 <Table.Cell>
840 \-
841 </Table.Cell>
842 </Table.Row>
843 <Table.Row>
844 <Table.Cell>
845 `primaryKey`
846 </Table.Cell>
847 <Table.Cell>
848 The document field that the adapter falls back to for InstantSearch's `objectID`. The adapter uses the hit's `id` first, so this option only applies when a hit has no `id`, such as when you pass a custom `requester`.
849 </Table.Cell>
850 <Table.Cell>
851 `"id"`
852 </Table.Cell>
853 </Table.Row>
854 <Table.Row>
855 <Table.Cell>
856 `cacheSearchResultsForSeconds`
857 </Table.Cell>
858 <Table.Cell>
859 How long the adapter caches results in the browser. `0` disables caching.
860 </Table.Cell>
861 <Table.Cell>
862 `0`
863 </Table.Cell>
864 </Table.Row>
865 <Table.Row>
866 <Table.Cell>
867 `additionalSearchParameters`
868 </Table.Cell>
869 <Table.Cell>
870 Defaults merged into every query. The adapter combines its filters with the widgets' filters using `$and`, and the widgets' pagination and sorting take precedence.
871 </Table.Cell>
872 <Table.Cell>
873 \-
874 </Table.Cell>
875 </Table.Row>
876 <Table.Row>
877 <Table.Cell>
878 `indexSpecificSearchParameters`
879 </Table.Cell>
880 <Table.Cell>
881 The same as `additionalSearchParameters`, but applied per index. The object's keys are index names.
882 </Table.Cell>
883 <Table.Cell>
884 \-
885 </Table.Cell>
886 </Table.Row>
887 <Table.Row>
888 <Table.Cell>
889 `transformQuery`
890 </Table.Cell>
891 <Table.Cell>
892 A function that receives the adapted query and the original InstantSearch request, and returns the query to send.
893 </Table.Cell>
894 <Table.Cell>
895 \-
896 </Table.Cell>
897 </Table.Row>
898 <Table.Row>
899 <Table.Cell>
900 `transformResponse`
901 </Table.Cell>
902 <Table.Cell>
903 A function that receives the adapted response, the raw search result, and the original request, and returns the response to hand to the widgets.
904 </Table.Cell>
905 <Table.Cell>
906 \-
907 </Table.Cell>
908 </Table.Row>
909 </Table.Body>
910 </Table>
911
912 ### Set Default Query Parameters
913
914 Use `additionalSearchParameters` to add filters or search options that every query must include, and `indexSpecificSearchParameters` to scope them to one index.
915
916 For example:
917
918 ```ts title="apps/storefront/src/lib/search-client.ts"
919 export const { searchClient } = createInstantSearchAdapter({
920 sdk,
921 path: "/store/search",
922 additionalSearchParameters: {
923 search_options: {
924 match_strategy: "last",
925 typo_tolerance: true,
926 },
927 },
928 indexSpecificSearchParameters: {
929 product: {
930 fields: ["id", "title", "handle", "thumbnail"],
931 },
932 },
933 })
934 ```
935
936 Every query then uses the `last` match strategy and typo tolerance, and the product index only returns the fields listed.
937
938 The `/store/search` route only returns fields the index holds and can retrieve, so every field in `fields` must be a retrievable field of the index definition. If you list a field that the index can't return, the route rejects the query with an error.
939
940 <Note title="Warning" type="warning">
941
942 Filters you set in the storefront's client are visible to customers, who can change them, so use these options for presentation, such as choosing the fields to retrieve, and not to protect data. Scoping a search to what a customer may see is the `/store/search` route's own responsibility in your Medusa application, which narrows a product index to published products in the publishable API key's sales channels.
943
944 </Note>
945
946 ---
947
948 ## Search Another Index
949
950 The `/store/search` route searches any index that a middleware allowed in your Medusa application, so an index you defined yourself needs no route of its own. Add its name to the `configureStoreSearch` middleware:
951
952 ```ts title="src/api/middlewares.ts"
953 import {
954 configureStoreSearch,
955 defineMiddlewares,
956 } from "@medusajs/framework/http"
957
958 export default defineMiddlewares({
959 routes: [
960 {
961 matcher: "/store/search",
962 middlewares: [
963 configureStoreSearch({
964 allowed_indexes: {
965 product: true,
966 article: true,
967 },
968 }),
969 ],
970 },
971 ],
972 })
973 ```
974
975 Then, pass the index's name as the `indexName` of an `InstantSearch` provider in your storefront, and the same search client serves it:
976
977 ```tsx
978 <InstantSearch
979 indexName="article"
980 searchClient={searchClient}
981 >
982 {/* widgets... */}
983 </InstantSearch>
984 ```
985
986 Refer to the [Search Module](../infrastructure-modules/search/page.mdx) documentation to learn how to define an index.
987
988 If you'd rather serve an index from a route of your own, such as one that reshapes the result, point the adapter's `path` option to it instead:
989
990 ```ts title="apps/storefront/src/lib/search-client.ts"
991 export const { searchClient } = createInstantSearchAdapter({
992 sdk,
993 path: "/store/article-search",
994 })
995 ```
996
997 ---
998
999 ## Supported InstantSearch Widgets
1000
1001 The adapter supports the following widgets:
1002
1003 - [searchBox](https://www.algolia.com/doc/api-reference/widgets/search-box/js/)
1004 - [hits](https://www.algolia.com/doc/api-reference/widgets/hits/js/) and [infiniteHits](https://www.algolia.com/doc/api-reference/widgets/infinite-hits/js/)
1005 - [pagination](https://www.algolia.com/doc/api-reference/widgets/pagination/js/) and [hitsPerPage](https://www.algolia.com/doc/api-reference/widgets/hits-per-page/js/)
1006 - [stats](https://www.algolia.com/doc/api-reference/widgets/stats/js/)
1007 - [configure](https://www.algolia.com/doc/api-reference/widgets/configure/js/)
1008 - [index](https://www.algolia.com/doc/api-reference/widgets/index-widget/js/)
1009 - [refinementList](https://www.algolia.com/doc/api-reference/widgets/refinement-list/js/), including its searchable variant
1010 - [menu](https://www.algolia.com/doc/api-reference/widgets/menu/js/) and [menuSelect](https://www.algolia.com/doc/api-reference/widgets/menu-select/js/)
1011 - [toggleRefinement](https://www.algolia.com/doc/api-reference/widgets/toggle-refinement/js/)
1012 - [currentRefinements](https://www.algolia.com/doc/api-reference/widgets/current-refinements/js/) and [clearRefinements](https://www.algolia.com/doc/api-reference/widgets/clear-refinements/js/)
1013 - [sortBy](https://www.algolia.com/doc/api-reference/widgets/sort-by/js/)
1014 - [highlight](https://www.algolia.com/doc/api-reference/widgets/highlight/js/) and [snippet](https://www.algolia.com/doc/api-reference/widgets/snippet/js/), if the provider supports highlighting
1015 - [routing](https://www.algolia.com/doc/guides/building-search-ui/going-further/routing-urls/js/)
1016
1017 ### Widgets with Requirements
1018
1019 The following widgets work, but they need extra setup:
1020
1021 <Table>
1022 <Table.Header>
1023 <Table.Row>
1024 <Table.HeaderCell>
1025 Widget
1026 </Table.HeaderCell>
1027 <Table.HeaderCell>
1028 Requirement
1029 </Table.HeaderCell>
1030 </Table.Row>
1031 </Table.Header>
1032 <Table.Body>
1033 <Table.Row>
1034 <Table.Cell>
1035 [rangeSlider](https://www.algolia.com/doc/api-reference/widgets/range-slider/js/), [rangeInput](https://www.algolia.com/doc/api-reference/widgets/range-input/js/), [numericMenu](https://www.algolia.com/doc/api-reference/widgets/numeric-menu/js/), and [ratingMenu](https://www.algolia.com/doc/api-reference/widgets/rating-menu/js/)
1036 </Table.Cell>
1037 <Table.Cell>
1038 List the field in the adapter's `numericAttributes` option, and mark it as `facetable({ types: ["stats"] })` in the index definition. Stats facets are opt-in, and both the PostgreSQL and Medusa Search providers support them.
1039 </Table.Cell>
1040 </Table.Row>
1041 <Table.Row>
1042 <Table.Cell>
1043 [hierarchicalMenu](https://www.algolia.com/doc/api-reference/widgets/hierarchical-menu/js/) and [breadcrumb](https://www.algolia.com/doc/api-reference/widgets/breadcrumb/js/)
1044 </Table.Cell>
1045 <Table.Cell>
1046 The index must hold the level fields the widgets expect, such as `categories.lvl0` and `categories.lvl1`. Build them in the index definition's `consume` and `seed` functions.
1047 </Table.Cell>
1048 </Table.Row>
1049 <Table.Row>
1050 <Table.Cell>
1051 `highlight` and `snippet`
1052 </Table.Cell>
1053 <Table.Cell>
1054 The provider must support highlighting. [Medusa Search](!cloud!/search) supports it, while the PostgreSQL provider doesn't.
1055 </Table.Cell>
1056 </Table.Row>
1057 </Table.Body>
1058 </Table>
1059
1060 ---
1061
1062 ## Filtering, Sorting, and Pagination
1063
1064 With this adapter, you can add widgets to a product listing page that allow customers to filter, sort, and paginate through products. The adapter translates the widgets' state into Medusa-compatible search queries, so you don't have to write the logic yourself.
1065
1066 Learn more in the [Filtering, Sorting, and Pagination guide](./examples/filtering-sorting-pagination/page.mdx).