1 # `@medusajs/instantsearch-adapter`
2
3 An [InstantSearch](https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/) search client for Medusa Search. It translates InstantSearch requests into Medusa `SearchQuery` payloads and maps `SearchResult` responses back into the shape InstantSearch widgets expect.
4
5 The adapter does not ship UI widgets. Install InstantSearch (or React / Vue / Angular InstantSearch) in your storefront alongside this package.
6
7 ## Installation
8
9 ```bash
10 yarn add @medusajs/instantsearch-adapter instantsearch.js
11 ```
12
13 Use a Medusa JS SDK instance so store requests include the publishable API key:
14
15 ```ts
16 import { createInstantSearchAdapter } from "@medusajs/instantsearch-adapter"
17 import instantsearch from "instantsearch.js"
18 import {
19 searchBox,
20 hits,
21 pagination,
22 refinementList,
23 } from "instantsearch.js/es/widgets"
24 import { sdk } from "./sdk"
25
26 const { searchClient } = createInstantSearchAdapter({
27 sdk,
28 path: "/store/search",
29 })
30
31 const search = instantsearch({
32 indexName: "product",
33 searchClient,
34 })
35
36 search.addWidgets([
37 searchBox({ container: "#searchbox" }),
38 hits({ container: "#hits" }),
39 refinementList({ container: "#brand", attribute: "brand" }),
40 pagination({ container: "#pagination" }),
41 ])
42
43 search.start()
44 ```
45
46 The same `searchClient` works with `react-instantsearch`, `vue-instantsearch`, and `angular-instantsearch`.
47
48 ### React InstantSearch
49
50 ```tsx
51 import {
52 InstantSearch,
53 SearchBox,
54 Hits,
55 RefinementList,
56 Pagination,
57 } from "react-instantsearch"
58 import { createInstantSearchAdapter } from "@medusajs/instantsearch-adapter"
59 import { sdk } from "./sdk"
60
61 const { searchClient } = createInstantSearchAdapter({
62 sdk,
63 path: "/store/search",
64 })
65
66 export function ProductSearch() {
67 return (
68 <InstantSearch indexName="product" searchClient={searchClient}>
69 <SearchBox />
70 <RefinementList attribute="brand" />
71 <Hits />
72 <Pagination />
73 </InstantSearch>
74 )
75 }
76 ```
77
78 ## Configuration
79
80 ```ts
81 createInstantSearchAdapter({
82 sdk, // preferred
83 // requester, // custom (queries) => results
84 // baseUrl, publishableApiKey, // native fetch fallback
85 path: "/store/search",
86 batch: true, // POST `{ queries }` in one request
87 placeholderSearch: true, // empty query still searches
88 numericAttributes: ["min_price"], // range widgets: request stats facets
89 distinctAttribute: "handle",
90 primaryKey: "id",
91 cacheSearchResultsForSeconds: 0,
92 additionalSearchParameters: {
93 filters: { status: { $eq: "published" } },
94 search_options: { match_strategy: "last" },
95 },
96 indexSpecificSearchParameters: {
97 product: { fields: ["title", "handle", "thumbnail"] },
98 },
99 transformQuery: (query, request) => query,
100 transformResponse: (response, result, request) => response,
101 })
102 ```
103
104 `path` is required when using `sdk` or `baseUrl`. If InstantSearch does not send `hitsPerPage`, the adapter omits `pagination.take` so the backend default applies.
105
106 `indexName` is the Search index `name` (the `entity` sent to Medusa). For `sortBy`, encode the sort in the index name:
107
108 ```ts
109 sortBy({
110 items: [
111 { label: "Relevance", value: "product" },
112 { label: "Price (asc)", value: "product/sort/min_price:asc" },
113 { label: "Price (desc)", value: "product/sort/min_price:desc" },
114 ],
115 })
116 ```
117
118 ## HTTP contract
119
120 The adapter POSTs Medusa `SearchQuery` objects, not Algolia-format params.
121
122 **Batched (default)**
123
124 ```http
125 POST /store/search
126 Content-Type: application/json
127 x-publishable-api-key: pk_...
128
129 {
130 "queries": [
131 {
132 "entity": "product",
133 "filters": { "q": "shoes", "brand": { "$in": ["nike"] } },
134 "search_options": {
135 "facets": [{ "field": "brand", "type": "value", "limit": 10 }]
136 }
137 }
138 ]
139 }
140 ```
141
142 ```json
143 {
144 "results": [
145 {
146 "hits": [{ "id": "prod_123", "document": { "title": "Trail shoe" } }],
147 "facets": {
148 "brand": {
149 "type": "value",
150 "values": [{ "value": "nike", "count": 4 }]
151 }
152 },
153 "metadata": { "skip": 0, "take": 20, "count": 4, "query": "shoes" }
154 }
155 ]
156 }
157 ```
158
159 InstantSearch sends one request per disjunctive facet in addition to the hits query. The route should run `searchMany` / `query.search` per item and return results in the same order.
160
161 When `batch: false`, each `SearchQuery` is POSTed as the body. The response may be a single `SearchResult`, or a `{ results }` wrapping exactly one — both are unwrapped.
162
163 The route is responsible for storefront constraints (sales channel, region, which indexes are public). Pass extra filters through `additionalSearchParameters` if the client should send them itself.
164
165 ### The built-in route
166
167 `POST /store/search` implements this contract over every registered index, so `indexName` is the index a query runs against. It hydrates the fields an index doesn't hold onto each hit's `document`, and otherwise runs the queries as posted.
168
169 It exposes nothing by default, and narrows a product index to published products in the publishable key's sales channels by. A `configureStoreSearch` middleware applied on the route can specify which indexes are searchable and it can apply
170 default filtesr to each index.
171
172 ```ts
173 configureStoreSearch({
174 allowed_indexes: {
175 product_category: { filters: (req) => ({ is_active: true }) },
176 },
177 })
178 ```
179
180 ## Widget support
181
182 Supported: `searchBox`, `hits`, `infiniteHits`, `pagination`, `hitsPerPage`, `stats`, `configure`, `index`, `refinementList` (including searchable), `menu`, `menuSelect`, `toggleRefinement`, `currentRefinements`, `clearRefinements`, `sortBy`, `highlight` / `snippet` (if the search provider supports highlighting), `routing`.
183
184 Supported with caveats:
185
186 - **Range widgets** (`rangeSlider`, `rangeInput`, `numericMenu`, `ratingMenu`) need stats facets. List those fields in `numericAttributes`, and mark them `facetable({ types: ["stats"] })` (or include `"stats"` alongside `"range"`) on the index — stats are opt-in. Both the Postgres and `search-medusa` providers support stats.
187 - **Hierarchical menu / breadcrumb** work if the index stores Algolia-style `categories.lvl0`, `categories.lvl1`, … fields.
188 - **Highlighting** is provider-dependent (available on `search-medusa`, not on Postgres).
189
190 Not supported: `geoSearch`, Algolia `filters` strings, Insights / Analytics, Query Rules, related-items, autocomplete, vector-search widgets.
191
192 Facetable, filterable, and sortable fields come from your `defineSearchIndex` definition, not from this package. The InstantSearch `stats` widget (hit count / timing) is independent of stats facets and works without `numericAttributes`.