Kelp analytics
How Kelp's batched analytics pipeline works - queryId attribution, createAnalytics, auto-filled fields, and the events endpoint.
Kelp analytics is a buffered, batched pipeline that tracks the full ecommerce funnel. Events are auto-filled with session, user, and timestamp information, then sent in batches to your analytics endpoint - so your UI code just calls a tracker method and moves on.
Install
npm install @kelpclick/client@latestcreateAnalytics
Import createAnalytics from @kelpclick/client/analytics (or the root @kelpclick/client). It requires a KelpClient instance and a KelpIdentity instance so it can auto-fill ambient fields on every event.
import { createKelpClient, createIdentity, createAnalytics } from '@kelpclick/client';
const kelp = createKelpClient({
searchUrl: 'https://{TENANT_ID}-search.kelp.click',
analyticsUrl: 'https://{TENANT_ID}-events.kelp.click',
apiKey: process.env.KELP_API_KEY!,
tenantCode: 'acme', // optional; stamped on every batch envelope
});
const identity = createIdentity();
const analytics = createAnalytics({
client: kelp,
identity,
flushAt: 10, // flush after this many events are buffered (default 10)
flushIntervalMs: 5000, // also flush on an interval in ms (default 5000)
maxBufferedEvents: 1000, // drop oldest events past this limit if the ingester is down
});Options
| Option | Default | Notes |
|---|---|---|
client | - | Required. A KelpClient created by createKelpClient. |
identity | - | Required. A KelpIdentity created by createIdentity. |
flushAt | 10 | Flush once this many events are buffered. |
flushIntervalMs | 5000 | Flush on a recurring interval. Pass 0 to disable. |
maxBufferedEvents | 1000 | Drop the oldest events if the buffer grows past this limit. |
serializeFilterBy | built-in | Override the filter serialization used by trackSearch. |
sanitizeEvent | - | Synchronous hook to redact PII before an event is buffered. |
Tracking events
Call the typed tracker methods after each user action. Each method composes the event with its fixed kind and auto-fills occurredAt, sessionId, and userId.
// After a search response
const res = await kelp.search('products', { q: 'shoes' });
analytics.trackSearch({
collection: 'products',
q: 'shoes',
found: res.found,
page: res.page,
queryId: res.queryId,
filters: [{ field: 'status', op: '=', values: ['ACTIVE'] }],
});
// Ecommerce funnel
analytics.trackProductClicked({
collection: 'products',
objectId: '9149995942110',
queryId: res.queryId, // attributes the click to the originating search
});
analytics.trackProductViewed({ collection: 'products', objectId: '9149995942110' });
analytics.trackProductAddedToCart({
collection: 'products',
objectId: '9149995942110',
queryId: res.queryId,
});
analytics.trackPurchase({
collection: 'products',
orderId: 'order-1001',
value: 129.99,
currency: 'USD',
items: [{ objectId: '9149995942110', quantity: 1, price: 129.99 }],
});
// Force a flush at any time (e.g. before navigation)
await analytics.flush();See Events for the full event taxonomy and field reference.
Auto-filled fields
createAnalytics fills three fields on every event automatically - you never supply them manually:
| Field | Value |
|---|---|
occurredAt | ISO 8601 timestamp of now |
sessionId | identity.getSessionId() - a rolling session id |
userId | The identified user from identity.getUserId(), or a stable anon_-prefixed anonymous id |
userId precedence: value on the event (if you pass one) > identified user (identity.identify(...)) > anon_<stable-id> for unidentified visitors.
The batch envelope
Events are not posted individually. The SDK buffers them and sends a batch when flushAt is reached, flushIntervalMs fires, or flush() is called. The wire format is:
{
"id": "019f7571-998f-7bb5-abdd-0945c5be7a4a",
"tenantCode": "acme",
"events": [
{
"kind": "search",
"occurredAt": "2026-08-03T12:00:00Z",
"collection": "products",
"sessionId": "sess_abc",
"userId": "anon_1a3b",
"q": "shoes",
"found": 42,
"page": 1,
"queryId": "019f7571-998f-7bb5-abdd-0945c5be7a4a"
}
]
}idis a UUID v4 generated per batch. The sameidis reused on every retry attempt so the server can deduplicate the batch.tenantCodeis omitted when not set on the client.- The endpoint is
<analyticsUrl>/analytics/events. Search and analytics are separate hosts -analyticsUrlis never inferred fromsearchUrl.
In Hydrogen or other SSR setups you can pass analyticsUrl: '' to proxy analytics same-origin through your own /analytics/events route. The real API key stays server-side and never reaches the browser.
Flush on page unload
The SDK listens for the pagehide event in the browser and calls flush() as a best-effort POST when the user navigates away or closes the tab. In-flight requests at that point may not complete - this is expected for analytics.
PII sanitization
Use sanitizeEvent to redact sensitive content before events leave the browser. The hook runs synchronously after ambient fields are filled and before the event is buffered:
const analytics = createAnalytics({
client: kelp,
identity,
sanitizeEvent(event) {
if (event.kind === 'search' && event.q) {
// Redact email-shaped search queries
return { ...event, q: /[^\s@]+@[^\s@]+\.[^\s@]+/.test(event.q) ? '[redacted]' : event.q };
}
return event;
},
});Related
- Events - event taxonomy and field reference
- Attribution - threading
queryIdfrom search through click and conversion events - Identity & Sessions - how session and user ids are generated and stored
- Configuration -
analyticsUrl,tenantCode, retries, and observability hooks