SDK API reference

Types

All exported TypeScript types and interfaces from @kelpclick/client with field tables.

KelpClientConfig

Configuration object passed to createKelpClient and createKelpSearch.

FieldTypeRequiredDefaultNotes
searchUrlstringyes-Base URL for search + browse.
analyticsUrlstringyes-Base URL for analytics batches. Not inferred from searchUrl.
apiKeystringyes-Sent as X-Api-Key. Throws if missing.
tenantCodestringno-Tenant slug stamped on every analytics batch envelope.
timeoutMsnumberno10000Per-request timeout in ms.
fetchtypeof fetchnoglobalThis.fetchInject a custom fetch (SSR / testing).
serializeFilters(filters: KelpFilters) => Record<string, unknown>no{ filters }Override the filter wire shape.
maxRetriesnumberno0Retry attempts after the initial try.
retryBaseMsnumberno250Base delay for exponential backoff (ms).
retryMaxMsnumberno5000Cap on per-attempt delay (ms).
debugbooleannofalseEmit debug log for every attempt.
logger{ debug, info, warn, error }noconsoleCustom log sink. Only active when debug: true.
onRequest(info: { url, method, attempt }) => voidno-Called before each attempt.
onResponse(info: { url, method, status, attempt }) => voidno-Called after response received.
onError(err: unknown) => voidno-Called after all retries exhausted.

KelpDocumentBase

Minimal shape that every indexed document carries. Extend it with your own document type.

interface KelpDocumentBase {
  id: string;
  objectId: string;
  [field: string]: unknown;
}
interface Product extends KelpDocumentBase {
  title: string;
  handle: string;
  vendor: string;
}

const res = await kelp.search<Product>('products', { q: 'shirt' });
res.hits[0].document.title; // typed as string

KelpSearchResponse<TDoc>

Returned by both search and browse.

FieldTypeNotes
hitsKelpHit<TDoc>[]Matched documents with highlights.
facetCountsKelpFacetCount[]Facet field counts.
foundnumberTotal number of matching documents.
pagenumberCurrent page number.
processingTimeMsnumberServer-side processing time in ms.
queryIdstring | undefinedServer-assigned id for this response. Pass to click/conversion events for attribution.

KelpHit<TDoc>

One item in KelpSearchResponse.hits.

FieldTypeNotes
documentTDocThe indexed document.
highlightsKelpHighlight[]Array of matched field snippets.

KelpHighlight

A highlight snippet for a matched field.

FieldTypeNotes
fieldstringThe document field name.
snippetstringExcerpt that may contain <mark> tags around matched terms.

KelpFacetCount

Counts for one facet field.

FieldTypeNotes
fieldstringFacet field name.
countsKelpFacetValue[]Array of { value, count } pairs, sorted by count descending.

KelpFacetValue

One value bucket within a KelpFacetCount.

FieldTypeNotes
valuestringThe facet value.
countnumberNumber of documents matching this value.

KelpFilter

One filter clause. Multiple clauses are ANDed together.

FieldTypeNotes
fieldstringDocument field to filter on. Must be a configured facet attribute.
opKelpFilterOpComparison operator. Defaults to = on the backend when omitted.
valuesstring[]=/!= accept one or more (IN-list); comparisons take one; range takes [min, max].

KelpFilterOp

type KelpFilterOp = '=' | '!=' | '>' | '>=' | '<' | '<=' | 'range';
OpMeaningValues
=Equals / IN-list (default)One or more
!=Not equalsOne or more
> >= < <=Numeric comparisonOne (values[0])
rangeInclusive rangeTwo ([min, max])

KelpFilters

type KelpFilters = KelpFilter[];

An array of KelpFilter clauses. The default wire format is { "filters": [ ... ] }. Override with serializeFilters on KelpClientConfig.


SortItem

One sort key. Pass an array to sort for multi-key sorting applied in order.

FieldTypeNotes
fieldstringDocument field to sort on.
directionSortDirection'asc' or 'desc'. Defaults to 'asc' on the backend when omitted.

SortDirection

type SortDirection = 'asc' | 'desc';

BrowseParams

Parameters accepted by browse (and inherited by SearchParams for search).

FieldTypeNotes
facetsstring[]Facet fields to count. Omit to return counts for all configured facet attributes.
pagenumberPage number. Default 1.
perPagenumberResults per page. Default 20.
filtersKelpFiltersFilter clauses.
sortSortItem[]Multi-key sort, applied in order.
fieldsstring[]Restrict returned document fields, e.g. ['id', 'title', 'handle'].
distinctBystringOptional. One hit per distinct value of that field (for example, styleId returns one hit per keyedTags.styleId).
userIdstringPer-visitor stable id for personalization. Caller-supplied.
sessionIdstringCurrent session id for behavioral signals.
personalizebooleanExplicit opt in/out of behavioral re-ranking for this request.
extraParamsRecord<string, unknown>Escape hatch merged directly into the request body.

SemanticWeight

Named semantic blend sent on search. Not a raw engine float.

type SemanticWeight =
  | 'strict'
  | 'heavy'
  | 'default'
  | 'balanced'
  | 'light'
  | 'keyword'
  | 'off';

See Semantic search for what each value does. Omit the field for keyword-only.


SearchParams

Extends BrowseParams with search-only fields q and semanticWeight. distinctBy is on BrowseParams (and therefore on search as well).

FieldTypeNotes
qstringRequired. The search query. Pass '*' for match-all. Must not exceed 512 characters or 50 words (backend-enforced).
semanticWeightSemanticWeightOptional. Search only. Semantic blend when the collection has enableSemanticSearch and this field is sent. Omit or unset = keyword-only. Not on BrowseParams.

RequestOptions

Options accepted by search, browse, suggest, and trackEvents as the last argument.

FieldTypeNotes
signalAbortSignalCancel the request in flight. Throws DOMException(AbortError) - not wrapped in KelpApiError.

KelpError

Base class for all SDK errors. Extends Error.

class KelpError extends Error {}

KelpApiError

Thrown on non-2xx responses, network failures, and timeouts. Extends KelpError.

FieldTypeNotes
statusnumberHTTP status code. 0 for network and timeout errors.
bodyunknownParsed response body, if any.
codeKelpErrorCodeDiscriminated error code for programmatic handling.
requestIdstring | undefinedFrom x-request-id or x-trace-id response header. Include in support requests.

KelpErrorCode

type KelpErrorCode = 'auth' | 'rate_limit' | 'client' | 'server' | 'network' | 'timeout';

See Error handling for the full code-to-scenario table.


KelpAnalyticsEvent

One analytics event. Mirrors the backend AnalyticsEventDto. Sent batched as { id, events: [...] }.

FieldTypeRequiredNotes
kindKelpEventKindyesEvent type. Closed set of 12 kinds.
occurredAtstringyesISO 8601 timestamp on the event root only. Auto-filled by createAnalytics.
sessionIdstringyesSession id. Auto-filled by createAnalytics.
collectionstringnoCollection scoping. Required for search/product/collection events; omitted for email events.
qstringnoSearch query string.
filterBystringnoSerialized filter expression, e.g. brand:=[globex] && price:>0.
foundnumbernoResult count (search events).
pagenumbernoPage number.
objectIdstringnoSubject document id (product id, or collection handle for collection_viewed).
queryIdstringnoTies the event to the search response that produced it (queryId chaining). Separate from the UTM Attribution object.
userIdstringnoKelp visitor id or anon_-prefixed anonymous id. Auto-filled by createAnalytics.
valuenumbernoOrder/basket total (mainly purchase). First-class persisted.
currencystringnoISO 4217 currency code (mainly purchase). First-class persisted.
orderIdstringnoOrder id (mainly purchase). First-class persisted.
itemsArray<{ objectId, quantity?, price? }>noPurchased line items (mainly purchase). First-class persisted.
emailEmailnoNested Email DTO (optional on every kind). See Email below.
attributionAttributionnoNested Attribution DTO (optional on every kind). See Attribution below.
metadataobjectnoOptional event-level JSON (KEL-52). Stored as jsonb. Separate from email.meta / attribution.meta. An empty object is stored as null. Only objects are valid.

Purchase scalars and typed email / attribution are first-class persisted (KEL-57). See Events.


Email

Nested email DTO. Optional on every event kind. When present, email (address) is required. source is optional (source?: string) for the capture point, e.g. 'footer-form'. Separate from Attribution source, which is required when Attribution is present. Flat string helpers map to { email } only.

FieldTypeRequiredNotes
emailstringyes (when present)Contact address.
sourcestringnoCapture point, e.g. 'footer-form'. Optional on object form.
listIdstringnoTarget list id.
campaignIdstringnoCampaign id.
detailsEmailDetailsnoPerson fields.
metaRecord<string, unknown>noEmail-scoped overflow. Not event metadata.

EmailDetails

FieldTypeRequiredNotes
namestringnoFull name.
firstNamestringnoGiven name.
lastNamestringnoFamily name.
phonestringnoPhone number.

Attribution

Nested UTM / traffic Attribution DTO. Optional on every event kind. When present, source is required; medium is optional. occurredAt is not on this object (event-root only).

FieldTypeRequiredNotes
sourcestringyes (when present)Traffic source, e.g. 'google'.
mediumstringnoe.g. 'organic', 'cpc'.
campaignstringnoCampaign name.
contentstringnoCreative / content.
termstringnoPaid keyword.
campaignRefstringnoExternal campaign reference.
clickIdstringnoClick id value.
clickIdParamstringnoParam name that held the click id.
referrerstringnoDocument referrer.
landingPagestringnoLanding path.
metaRecord<string, unknown>noAttribution-scoped overflow. Not event metadata.

Search-to-conversion queryId chaining is documented in Attribution and is separate from this object.


KelpEventKind

type KelpEventKind =
  | 'session_started'
  | 'search'
  | 'product_viewed'
  | 'product_clicked'
  | 'product_wishlisted'
  | 'product_added_to_cart'
  | 'collection_viewed'
  | 'purchase'
  | 'email_subscribed'
  | 'email_unsubscribed'
  | 'email_opened'      // reserved
  | 'email_clicked';    // reserved

Closed named set. email_opened and email_clicked are reserved and are not emitted by the client yet. The SDK does not accept custom kind strings.


CreateAnalyticsOptions

Options for createAnalytics.

FieldTypeRequiredDefaultNotes
clientKelpClientyes-The Kelp client used to send events.
identityKelpIdentityyes-Identity instance for auto-filling sessionId and userId.
flushAtnumberno10Flush when this many events are buffered.
flushIntervalMsnumberno5000Also flush on this interval. 0 disables the interval.
maxBufferedEventsnumberno1000Drop oldest events past this cap if the ingester is down.
serializeFilterBy(filters: KelpFilters) => stringnodefaultSerializeFilterByCustom filter serializer for trackSearch.
sanitizeEvent(event: KelpAnalyticsEvent) => KelpAnalyticsEventno-Redact or transform each event before buffering. Must be synchronous.

KelpIdentityOptions

Options for createIdentity.

FieldTypeDefaultNotes
storageKelpStorageresolveStorage()Custom storage backend.
sessionTtlMsnumber1800000 (30 min)Inactivity window before a new session id is minted.
keyPrefixstring'kelp'Prefix for storage keys. Set per-tenant when multiple tenants share a browser origin.

KelpStorage

Interface for pluggable identity storage.

interface KelpStorage {
  get(key: string): string | null;
  set(key: string, value: string): void;
  remove(key: string): void;
}

KelpIdentity

Returned by createIdentity.

MethodSignatureNotes
getAnonymousId() => stringStable per-browser id. Created and persisted on first read.
getSessionId() => stringRolling session id. A new id is minted after sessionTtlMs of inactivity; every call refreshes the activity timestamp.
getUserId() => string | nullThe identified user id, or null.
identify(traits: IdentifyTraits & { userId?: string }) => KelpUserTokenRecords the known user locally. Returns { anonymousId, userId? }.
reset() => voidClears the known user. Keeps the anonymous id.

KelpClient

The type of the object returned by createKelpClient. Composed from the search capability and events transport.

type KelpClient = ReturnType<typeof createKelpClient>;
// { search, browse, suggest, trackEvents, identify }

React types (@kelpclick/client/react)

TypeNotes
KelpProviderPropsProps for KelpProvider: client, optional identity, optional analytics, children.
UseSearchOptionsOptions for useSearch: collection, facets, sort, fields, perPage, debounceMs, initialQuery, trackSearch, and any BrowseParams fields.
UseBrowseOptionsOptions for useBrowse: same as UseSearchOptions minus query fields.
UseKelpQueryOptionsLower-level options for useKelpQuery.
KelpQueryRunnerArgsArguments passed to the query runner function in useKelpQuery.
QueryStatus'idle' | 'loading' | 'success' | 'error' - status field returned by useSearch and useBrowse.

On this page