SDKs
React
@findlane/browser/react: a search box that suggests searches and results as visitors type, a results page with filters, and the hooks behind them for your own markup.
Install
The React hooks and components come with the browser SDK, under @findlane/browser/react. They work with React 18.2 and 19.
npm install @findlane/browserPages that don't import @findlane/browser/react don't load it, and the browser SDK itself doesn't need React.
A search box
SearchBox shows results as visitors type, and with query suggestions on, searches to pick above them. The arrow keys, Enter, and Escape work as screen readers expect. It needs only the index's public ID:
import { SearchBox } from "@findlane/browser/react"
import "@findlane/browser/react/styles.css"
export function Header() {
return (
<SearchBox
publicId="pub_your_public_id"
placeholder="Search products"
fields={["title", "image", "url"]}
getHref={(hit) => hit.record.url}
action="/search"
/>
)
}Each result shows the record's image and title (or name), with the matched words marked. Pass renderHit to show something else.
| Prop | |
|---|---|
publicId | The index's public ID. Or set it once with FindlaneProvider. |
fields | The record fields to return. Fewer fields make responses smaller. |
getHref | A hit's page. Clicking a result, or Enter on one, goes there. |
hrefTemplate | A hit's page as a template, such as "/products/{handle}", for server components. |
onSelect | Called with the chosen hit instead of following its link, for client-side routers. |
action | A results page, such as /search. Enter without a chosen result, or a picked search, goes there with ?q=. |
onSubmit | Called with the query on Enter without a chosen result, and with a picked search, instead of action. |
renderHit | A result's content. |
limit | Results to show: 6 by default. |
querySuggestions | Searches to suggest above the results as visitors type, up to 10. Off unless set; see below. |
popularSearches | Popular searches to show when the box is empty, up to 10. Off unless set. |
recentSearches | true shows the visitor's last five searches when the box is empty, or a number up to 10. Off unless set. |
subindexes | The index's subindexes to show above the results, such as categories and pages, each with limit (3 by default), fields, hrefTemplate or getHref, and label. Searched in the same request, as one search (0.22.0). |
renderSubindexHit | A subindex result's content, given the subindex's name and the hit. |
facetMatches | The fields of the index's facet matches to show as rows above the results, in the order given, each with label and getHref(match). See below. |
onFacetMatch, renderFacetMatch | Called when a facet match is chosen, instead of following its link, for client-side routers; and a row's content. |
filters, sort | As in Search, for every result. |
minLength | Characters to type before searching: 1 by default. |
debounceMs | How long a keystroke that comes this soon after the last search waits for the next: 50 ms by default. After a longer pause, the search goes out at once (0.16.0). |
placeholder, label | The input's placeholder, and its accessible name ("Search" by default). |
empty, seeAll | The "No results" and "See all N results" text. |
labels | The sections' headings and buttons, for other languages: recent, popular, suggestions, results, clear, remove. |
In a server component, such as a Next.js page, props must be plain values, so use hrefTemplate instead of getHref. {handle} puts in the record's handle, URL-encoded, and {objectID} the hit's ID. A template that is a single field, such as "{url}", uses that field's URL as it is. Only http:, https:, and relative links are allowed.
Facet matches
With the index's facet matches setting, the box can offer the categories, brands and places a search names, above the results:
<SearchBox
publicId="pub_…"
facetMatches={{ categorySlugs: { label: "Categories" }, brandSlugs: { label: "Brands" } }}
/>They come in the same request. A row goes to the setting's link, or its field's getHref(match), and sends a facetMatch event, for Analytics. The rows never filter the results in the box, whatever the setting's apply says.
On a results page, give SearchProvider the facetMatches option; see below.
Query suggestions
With query suggestions, the box suggests whole searches as visitors type, and with nothing typed, shows popular searches and the visitor's recent ones:
<SearchBox
publicId="pub_your_public_id"
hrefTemplate="/products/{handle}"
action="/search"
querySuggestions={4}
popularSearches={6}
recentSearches
/>Each kind is a section of one list, under its own heading: recent searches, popular searches, suggested searches, then results. The arrow keys move through all of them. In a suggestion, what was typed is plain and the rest bold. Recent searches each have a remove button, and their heading a Clear button.
Picking a search goes to action with ?q=, or calls onSubmit. Without either, it fills the box and shows its results. Recent searches stay in the visitor's browser, and count a search when it's submitted, picked, or leads to a result being opened. Popular searches are asked for once per page.
The sections are [data-findlane-section] (recent, popular, suggestion, or hit), with [data-findlane-section-title] headings, and each search is a [data-findlane-query] option.
A search dialog
SearchDialog is a search button that opens a dialog with the same search box, as on docs sites. ⌘K (Ctrl+K elsewhere) and / open it too:
<SearchDialog publicId="pub_your_public_id" hrefTemplate="{url}" fields={["title", "url"]} />It takes the same props as SearchBox, plus trigger for the button's content, footer for a line at the bottom of the open dialog, such as keyboard hints, and shortcuts={false} to turn the keys off. It uses the browser's <dialog>, so focus stays inside it while it's open. Escape or a click outside closes it.
Styles
The components render plain elements with data-findlane-* attributes and no styles of their own. @findlane/browser/react/styles.css gives them a default look that follows the page's color-scheme. Its rules are inside :where(), so your own CSS wins without !important. To theme it, set these variables anywhere above the components:
.site-header {
--findlane-accent: #0f766e;
--findlane-radius: 6px;
--findlane-background: #fff;
--findlane-border: #d4d4d8;
--findlane-muted: #71717a;
}Your own markup
useAutocomplete keeps the search box's state and gives your elements their attributes and events, so the ARIA combobox pattern works with any design:
import { Highlight, useAutocomplete } from "@findlane/browser/react"
function Search() {
const box = useAutocomplete<Product>({
fields: ["title", "url"],
onSelect: (hit) => navigate(hit.record.url),
})
return (
<div className="search">
<input {...box.getInputProps({ placeholder: "Search", "aria-label": "Search" })} />
{box.isOpen && (
<ul {...box.getListboxProps()}>
{box.hits.map((hit, index) => (
<li key={hit.id} {...box.getOptionProps(index)}>
<Highlight hit={hit} field="title" />
</li>
))}
</ul>
)}
</div>
)
}It takes the same options as SearchBox and returns query, hits, total, error, isPending, isOpen, and activeIndex. Earlier searches still in flight keep going while the visitor types: their answers show until a newer one's arrive, and a slow response never replaces a newer one (0.16.0). Focusing the box opens the connection to the API, so the first keystroke doesn't wait for it.
With query suggestions, popular, or recent searches on, items lists every option in order: searches (kind is suggestion, popular, or recent, with q, and for a suggestion typed) and then results (kind: "hit", with hit). Give each its props with getOptionProps(item.index). removeRecent(q) and clearRecent() change the recent searches.
{box.items.map((item) =>
item.kind === "hit" ? (
<li key={item.hit.id} {...box.getOptionProps(item.index)}>
<Highlight hit={item.hit} field="title" />
</li>
) : (
<li key={item.q} {...box.getOptionProps(item.index)}>
{item.kind === "suggestion"
? suggestionParts(item).map((part, at) => (part.typed ? part.text : <b key={at}>{part.text}</b>))
: item.q}
</li>
)
)}suggestionParts comes from @findlane/browser.
A results page
Hits shows rules' banners at their places among the first page's hits, each as its image linked to its page, with its title; renderBanner draws your own, and DefaultBanner is the default (0.20.0). Following a link in a banner sends a banner click (0.21.0); a banner you draw without a link can send one with useHits().bannerClick(banner). SearchBox follows a rule's redirect when a shopper presses Enter, such as "returns" to your returns page.
SearchProvider holds a results page's search. The components and hooks inside it share its query, filters, and results, wherever they are in the page:
import {
CurrentRefinements,
Hits,
LoadMore,
RefinementList,
SearchInput,
SearchProvider,
SortSelect,
Stats,
} from "@findlane/browser/react"
export function SearchPage() {
return (
<SearchProvider
publicId="pub_your_public_id"
facets={["brand", "category"]}
pageSize={24}
routing
>
<SearchInput placeholder="Search products" />
<aside>
<RefinementList field="brand" label="Brand" />
<RefinementList field="category" label="Category" />
</aside>
<main>
<Stats />
<SortSelect
options={[
{ id: "relevance", label: "Most relevant" },
{ id: "price_asc", label: "Price: low to high" },
]}
/>
<CurrentRefinements />
<Hits<Product> render={(hit) => <ProductCard hit={hit} />} />
<LoadMore />
</main>
</SearchProvider>
)
}When a visitor picks a brand, the other brands stay listed with their counts, so more can be added. That's still one search per change: the provider asks for disjunctiveFacets.
With the index's related results on, a search that finds nothing shows the products closest in meaning: Hits puts them under "No exact matches. Related products" (change it with relatedTitle), and their clicks are sent with list: "related" (0.17.0).
| Prop | |
|---|---|
facets | Fields to count values for, which RefinementList and useRefinementList choose from. |
filterFields | Fields that useRange and useToggle filter, so the URL can keep them. |
facetStats | Number fields whose smallest and largest values useRange returns, such as a price slider's bounds. |
filters | Filters always applied, such as { published: true }. They aren't shown as choices. |
near | Where searches are near until the visitor picks another place, such as { visitor: true }; see Location. |
pageSize | Hits per page: 20 by default, up to 50. |
fields | The record fields to return. |
countMode, facetMode | "exact" by default, so totals and counts cover every match. "page" is faster on large indexes. |
routing | Keep the search in the page's URL, as ?q=shoe&brand=Acme&page=2, so it can be shared and Back works. |
state, onStateChange | Sync the search with your router instead of routing. |
initialResults | Results from the server; see Server rendering. |
facetMatches | The facet values the query names, in the same request: true for every field of the setting, or { fields }. See below. |
subindexes | The index's subindexes to search with each query, such as { categories: { limit: 4 } }, in the same request and counted as one search. useSubindex("categories") reads their results, for categories to suggest above the results (0.23.0). |
With routing, typing replaces the current history entry, and choosing a filter adds one, so Back undoes a filter rather than a keystroke. Other parameters in the URL are kept.
Hooks
Every component is built on a hook, for when you want your own markup:
| Hook | Returns |
|---|---|
useSearchBox() | query, setQuery, clear, isPending. |
useHits() | hits, total, related, response, request, ms, isLoaded, isPending, error, click(hit). |
useRefinementList(field) | items (value, count, selected), toggle(value), clear. |
useRange(field) | range ({ gte, lte }), min, max, setRange, clear, for numbers and dates. |
useToggle(field, value) | on, set, toggle, for a filter like inStock: true. |
useSortBy() | sort, setSort. |
useCurrentRefinements() | items (field, value, label, remove), clear. |
useFacetMatches() | matches, applied, searched, select(match), removeApplied, isPending; see below. |
useLoadMore() | hasMore, loadMore, isLoading, shown, total. |
usePagination() | page (from 0), pages, setPage, hasPrevious, hasNext. |
useDidYouMean() | didYouMean (q, applied, changes) and apply; see below. |
useGeoSearch() | near, within, center, setNear, nearVisitor, setWithin, clear; see below. |
useSearchState() | The whole state and setState. |
A price range with two inputs, for example:
function PriceRange() {
const { range, setRange } = useRange("price")
const bound = (value: string) => (value ? Number(value) : undefined)
return (
<fieldset>
<legend>Price</legend>
<input
type="number"
placeholder="Min"
value={range?.gte ?? ""}
onChange={(event) => setRange({ ...range, gte: bound(event.target.value) })}
/>
<input
type="number"
placeholder="Max"
value={range?.lte ?? ""}
onChange={(event) => setRange({ ...range, lte: bound(event.target.value) })}
/>
</fieldset>
)
}For a slider, list the field in the provider's facetStats too: min and max are its smallest and largest values across the matches, without the range itself, so the slider's ends stay put while it moves.
The playground is built this way.
Facet matches on a results page
With facetMatches on SearchProvider, <FacetMatches /> offers the values the query names as buttons. Pressing one filters by it, and takes its words out of the query.
<SearchProvider publicId="pub_…" facets={["brandSlugs"]} facetMatches routing>
<SearchInput />
<FacetMatches label="Filter by" />
<CurrentRefinements />
<RefinementList field="brandSlugs" />
<Hits />
</SearchProvider>When the setting's apply makes a search filter by a match:
- The query in the box stays what was typed, and
CurrentRefinementsshows the filter as a chip.useRefinementListcounts its value as selected. - Removing the chip keeps that query's matches from applying until the query changes. With
routing, the URL says so withunapplied=1. - Choosing another value beside it makes both choices of their own, and stops searching the applied words.
Clicks on results carry the applied filter, for sales by filter value.
Did you mean
With the index's didYouMean setting on, DidYouMean says "Showing results for protein" when typo tolerance corrected the query. When nothing matches, it waits until the visitor stops typing, asks for a suggestion, and shows "Did you mean protein?" as a button that searches for it:
<SearchInput />
<DidYouMean />
<Hits render={(hit) => <ProductCard hit={hit} />} />It shows nothing for indexes without the setting, and doesn't ask them. delay sets the pause (400 ms by default), and format renders your own line: format={(didYouMean, apply) => ...}.
Images
Image (0.27.1) shows a record's photo. With optimized images on, it's resized to width and to twice that for sharp screens, and sent as WebP; with the hit's placeholder, a blurred preview shows until it loads, then the photo sharpens in:
<Image src={hit.record.image} width={240} placeholder={hit.placeholder} alt={hit.record.title} />It loads lazily, and loads the original if the resized photo fails. It takes the other img props, such as className. Inside SearchProvider, SearchBox or Recommendations it uses their client; elsewhere, pass client. The components' own results and recommendations use it.
Recommendations
For indexes with the recommendations add-on, Recommendations shows one of a product's lists, and renders nothing while the product has none. Lists for the same product share one request:
<Recommendations objectID={product.id} list="together" fill="goesWith" />
<Recommendations objectID={product.id} list="similar" title="You might also like" />list is goesWith (the default), similar, or together (Bought together, from your orders). fill tops up a short list from another list in the same response, and each product's data-findlane-source says which list it came from. The heading says what most of the list is: with list="together" fill="goesWith", "Frequently bought together" when most products shown come from orders, else "Goes well with".
getHref or hrefTemplate (as in SearchBox) makes each product a link to its page:
<Recommendations objectID={product.id} hrefTemplate="/products/{handle}" />useRecommendations(objectID, options) returns { data, error, isPending } for your own markup.
Clicks
The components send a click event when a shopper picks a result, so Analytics can show each query's click-through and the place of clicked results, and the Recommendations page each list's clicks:
SearchBoxandSearchDialog: choosing a result, with its place and the query; and picking a suggested, popular, or recent search, as asuggestionevent, with its place in its section.Hits: following a link in a result, with its place among the loaded results and the query.Recommendations: following a link in a product, with its list, its place, and the product the list is for.
A result rendered without a link, such as one that opens a panel, can send its own with useHits().click(hit). Clicks follow the client's events option: events: false turns them off, and events: "afterConsent" holds them until client.events.consent(true). Pass a client to FindlaneProvider to set it once:
const client = new SearchBrowserClient({ publicId: "pub_…", events: "afterConsent" })
<FindlaneProvider client={client}>…</FindlaneProvider>Product views
useProductView(objectID) sends a view event when a product's page shows, and again when objectID changes. Nothing is sent while it's empty, such as before the product has loaded:
function ProductPage({ product }: { product: Product }) {
useProductView(product.id)
return <h1>{product.title}</h1>
}Where hooks can't go, such as a Next.js server component, ProductView does the same and renders nothing:
<ProductView publicId="pub_…" objectID={product.id} />A repeat within 5 seconds, such as React's double mount in development, isn't sent. Views follow the client's events option, like clicks. Both need browser SDK 0.11.0.
Location
With the index's location field, useGeoSearch searches by location. Pass near={{ visitor: true }} to the provider to start nearest the visitor:
<SearchProvider publicId="pub_…" near={{ visitor: true }} routing>
<StoreFinder />
</SearchProvider>
function StoreFinder() {
const { hits } = useHits<Store>()
const { center, setNear, setWithin } = useGeoSearch()
// center: where distances are from, such as the visitor's city, to center a map on.
return hits.map((hit) => (
<p key={hit.id}>
{hit.record.name}: {(hit.distance! / 1000).toFixed(1)} km
</p>
))
}setNear({ lat, lng, radius })searches near a point, andnearVisitor(radius)near the visitor.setWithin({ north, south, east, west })keeps what a map shows. Call it from the map's move events: map moves replace the history entry instead of adding one, so Back doesn't step through every drag.clear()removes both.- With
routing, the URL keeps them asnear=51.5074,-0.1278(ornear=visitor) andwithin=north,east,south,west.
There's no map component: use any map library. The map playground uses MapLibre.
Maps
useMapSearch keeps a map's clusters and pins current, from fixed map tiles. It needs no SearchProvider. The homes playground uses it with MapLibre.
import { useMapSearch } from "@findlane/browser/react"
function HomesMap({ map }) {
const [view, setView] = useState(null)
useEffect(() => {
const update = () => setView({ box: map.getBounds(), zoom: map.getZoom() })
update()
map.on("moveend", update)
return () => map.off("moveend", update)
}, [map])
const { clusters, hits, total, isPending, error } = useMapSearch(view, {
filters: { status: "active" },
clusters: { stats: ["price"] },
hits: { cells: 8, limit: 50 },
})
// Draw a bubble at each cluster's lat and lng, and a pin for each hit.
}viewis{ box, zoom }, ornullto not search.boxcan be a plain{ north, south, east, west }or a map's owngetBounds()(0.34.0). Moves within the same tiles ask for nothing.- Moving around asks only for new tiles. Going back answers from memory, and requests for tiles no longer in view stop.
- After a zoom or a change of filters, the earlier answer stays until every new tile has arrived, so the map doesn't flash.
isPendingsays one is on its way. clustersdefaults to 16 cells a side, which makes cells 64 pixels wide.falseasks for none. A stat can be{ field: "price", gt: 0 }, to leave out values at or belowgt(0.34.0).hitsdefaults to none. They count as records a visitor took, and clusters don't.- One marker an area: give
clustersandhitsthe samecells, andclusterFor(hit.record._geoloc, clusters)finds a hit's cluster (0.34.0), so you can show its photo with how many others are there, as the playground does from zoom 12. totalcovers whole tiles, which reach past the view. To say how many are in sight, add up the clusters within it.qsends new tiles when it changes, so pass the search once typing has paused rather than on each key.errorsays a tile of this view failed (0.34.0). What the other tiles found still shows, and the next move asks for the failed one again.retry()asks at once, for a "Try again" button.
Highlights
Highlight shows a field with the words the query matched in <mark>. Snippet cuts a long field, such as a description, to the words around its best match:
<Highlight hit={hit} field="title" />
<Snippet hit={hit} field="description" words={24} />Both render React elements, not HTML, so they work under a strict Content Security Policy. A field without a match shows its plain value. field can be a path such as brand.name, and a list field's values are joined with separator (", " by default). Pass mark="strong" or your own component to change the element.
Server rendering
Browser search answers only browsers on the index's allowed origins, so a server renders the first results with the server SDK and a key with the search scope. getServerResults runs the same search the provider would, from @findlane/browser/react/ssr, which server code can import. A Next.js page:
// app/search/page.tsx
import { SearchServerClient } from "@findlane/server"
import { getServerResults, stateFromUrl } from "@findlane/browser/react/ssr"
import { SearchPage } from "./search-page" // a "use client" component with the SearchProvider
const config = { facets: ["brand", "category"], pageSize: 24 }
const products = new SearchServerClient({
workspaceId: process.env.FINDLANE_WORKSPACE_ID!,
apiKey: process.env.FINDLANE_SEARCH_KEY!,
}).index("products")
export default async function Page({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[]>>
}) {
const state = stateFromUrl(await searchParams, config)
const initialResults = await getServerResults(config, state, (request) =>
products.search(request)
)
return <SearchPage config={config} initialResults={initialResults} />
}Give the client's SearchProvider the same config, initialResults, and routing. Its first render then matches the server's and doesn't search again. Searches from the server count toward your plan like browser searches.
Logged-in visitors
FindlaneProvider takes a signedKey for a logged-in person (0.25.0): a signed key from your server, or a function that fetches one. The hooks and components inside it search as that person, held to the key's restrictions instead of the index's public settings:
<FindlaneProvider publicId="pub_…" signedKey={() => fetch("/api/search-key").then((response) => response.text())}>
<SearchBox />
</FindlaneProvider>A new function each render keeps the same client and its cached results; a new key string makes a new client, for the person it's for. See Logged-in visitors.
One search
useSearch keeps a single search current, for anything the components don't cover. A change after a pause searches at once, and one within debounceMs (50 ms) of the last search waits that long for the next. Searches in flight keep going, their answers fill the cache, and a slow response never replaces a newer one; the previous results stay while the next ones load. Pass null to not search.
const { data, error, isPending } = useSearch<Product>(query ? { q: query, limit: 5 } : null, {
publicId: "pub_your_public_id",
})Recent responses are kept in memory for five minutes, so going back to a query shows its results at once and doesn't search again.
Errors
The hooks return a failed search's FindlaneError as error; see Errors. messageFor(error) turns it into a sentence for visitors. A 403 (an origin that isn't allowed) or 402 (a plan's searches used up) becomes "Search isn't available right now.", since visitors can't fix either.