JavaScript client
@shoof/js-client wraps the REST API with typed methods. It runs in
browsers, Node.js 18+, Deno, Bun and edge runtimes: anywhere with fetch.
npm install @shoof/js-clientIt has two entry points:
@shoof/js-client:ShoofClient, for searching. Use a search key or a secured key; it’s safe in browsers.@shoof/js-client/admin:ShoofAdminClient, for indexing and configuration. Use an admin key, on your server only.
Search client
Section titled “Search client”import { ShoofClient } from "@shoof/js-client";
const client = new ShoofClient({ appId: "my-store", apiKey: "shf_pub_…",});
const res = await client.search({ q: "running shoes", lang: "en", filters: { brand: ["Nike", "Asics"], price: { lte: 150 } }, facets: ["brand", "categories", "price"], hitsPerPage: 24,});
for (const hit of res.hits) console.log(hit.title, hit.price);Options
Section titled “Options”| Option | Default | Does |
|---|---|---|
appId |
required | Your application ID. |
apiKey |
required | A search key (shf_pub_…) or secured key (shf_sec_…). The client warns if it’s given an admin key in a browser. |
host |
https://api.shoofai.co |
The API host. |
userToken |
a random anon-… ID |
The visitor’s ID, sent with searches and events. See user tokens. |
timeoutMs |
10000 |
Request timeout. Streaming answers have none. |
fetch |
globalThis.fetch |
Your own fetch, for tests, proxies or polyfills. |
headers |
Extra headers on every request. |
Methods
Section titled “Methods”| Method | Returns | API |
|---|---|---|
search(request, { signal? }) |
SearchResponse |
Search |
multiSearch(requests[]) |
SearchResponse[] |
Multi-search |
autocomplete(q, { lang?, hits?, filters?, analytics?, signal? }) |
AutocompleteResponse |
Autocomplete |
searchFacetValues(field, request?) |
FacetSearchResponse |
Search facet values |
answer(request, { onSources?, onDelta?, signal? }) |
{ text, sources, mode, queryId?, query? } |
Answer |
answerStream(request, { signal? }) |
async iterator of answer events | Answer |
related(id, { lang?, limit? }) |
Hit[] |
Related items |
trending({ limit?, lang?, type?, filters? }) |
TrendingHit[] |
Trending items |
trendingQueries({ limit?, lang? }) |
TrendingQuery[] |
Trending queries |
boughtTogether(id, { limit?, lang? }) |
TogetherHit[] |
Bought together |
config() |
the app’s public config, cached | Config |
sendEvents(events[]) |
Events | |
beacon(events[]) |
Events that survive navigation, sent with navigator.sendBeacon. |
|
clicked(queryId, objectId, position) |
A click, as a beacon. | |
viewed(objectId) |
A view of an item’s page, as a beacon. | |
converted(queryId, objectId, value?, currency?, orderId?) |
A purchase, as a beacon. | |
reportError({ where, message, stack?, version? }) |
An error your code caught, as a beacon. The widget uses it. | |
setApiKey(key) |
Swap the key, such as a refreshed secured key, without a new client. |
Every method that makes a request takes an AbortSignal, so you can cancel a
search when the visitor types another letter:
let ctrl: AbortController | undefined;
input.addEventListener("input", async () => { ctrl?.abort(); ctrl = new AbortController(); try { const res = await client.autocomplete(input.value, { lang: "en", signal: ctrl.signal }); render(res); } catch (e) { if ((e as Error).name !== "AbortError") throw e; }});Streaming answers
Section titled “Streaming answers”answer() resolves with the whole answer, and calls you back as it streams:
const result = await client.answer( { q: "what is your return policy?", lang: "en" }, { onSources: (sources) => showSources(sources), onDelta: (_text, full) => (answerEl.textContent = full), },);// result.mode is "llm", "extractive" or "none"For a follow-up question, send the conversation so far:
const followUp = await client.answer({ q: "does that include sale items?", messages: [ { role: "user", content: "what is your return policy?" }, { role: "assistant", content: result.text }, ],});See AI answers for how answers are made.
Reporting events
Section titled “Reporting events”const res = await client.search({ q: "trail shoes" });
// The visitor clicked the second result:client.clicked(res.queryId, res.hits[1].id, 2);
// They bought it, on the order confirmation page:client.converted(res.queryId, res.hits[1].id, 140, "AED", "order-10521");See Events for what to send and when.
Admin client
Section titled “Admin client”import { ShoofAdminClient } from "@shoof/js-client/admin";
const admin = new ShoofAdminClient({ appId: "my-store", apiKey: process.env.SHOOF_ADMIN_KEY!,});
const result = await admin.upsertAll(records, { onProgress: (done, total) => console.log(`${done}/${total}`),});console.log(result.indexed, result.updated, result.errors);The admin client’s default timeout is 120 seconds, since big batches take a while to embed.
Methods
Section titled “Methods”| Method | Does |
|---|---|
batch({ upserts?, deletes?, reindexId? }, { refresh? }) |
Upserts up to 500 and deletes up to 1,000 records. Records |
upsertAll(records, { reindexId?, batchSize?, onProgress? }) |
Splits any number of records into batches (200 by default, at most 500) and sends them in turn. |
getRecord(id) |
The record as stored. |
deleteRecord(id) |
Deletes one record. |
clear() |
Deletes every record. |
startReindex({ copy?, restart? }) |
Starts a full resync. |
reindexStatus() |
The resync’s progress. |
commitReindex(reindexId) |
Swaps in the new index and removes records that weren’t sent. |
cancelReindex() |
Drops the new index. |
status() |
Record counts by type and language, embeddings, and any resync. |
getSettings() / setSettings(s) / patchSettings(s) |
Read, replace or update settings. |
applyPreset("store" | "blog", { ifUnchanged? }) |
Sets the facets for a kind of site. |
getSynonyms() / setSynonyms(list) |
Read or replace synonyms. |
getRules() / setRules(list) |
Read or replace rules. |
A full resync
Section titled “A full resync”const { reindexId } = await admin.startReindex();await admin.upsertAll(allRecords, { reindexId });await admin.commitReindex(reindexId); // removes the records that weren't re-sentSee Full resync for the details.
Errors
Section titled “Errors”Failed requests throw a ShoofApiError with the HTTP status, the API’s
error code and message, and any details:
import { ShoofApiError } from "@shoof/js-client";
try { await client.search({ q: "shoes", hitsPerPage: 500 });} catch (e) { if (e instanceof ShoofApiError && e.code === "bad_request") { console.error(e.message, e.details); }}See Errors for every code.
Every request and response type is exported, so your editor completes them:
import type { SearchRequest, SearchResponse, Hit, Filters, RecordInput } from "@shoof/js-client";