Analytics & attribution

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@latest

createAnalytics

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

OptionDefaultNotes
client-Required. A KelpClient created by createKelpClient.
identity-Required. A KelpIdentity created by createIdentity.
flushAt10Flush once this many events are buffered.
flushIntervalMs5000Flush on a recurring interval. Pass 0 to disable.
maxBufferedEvents1000Drop the oldest events if the buffer grows past this limit.
serializeFilterBybuilt-inOverride 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:

FieldValue
occurredAtISO 8601 timestamp of now
sessionIdidentity.getSessionId() - a rolling session id
userIdThe 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"
    }
  ]
}
  • id is a UUID v4 generated per batch. The same id is reused on every retry attempt so the server can deduplicate the batch.
  • tenantCode is omitted when not set on the client.
  • The endpoint is <analyticsUrl>/analytics/events. Search and analytics are separate hosts - analyticsUrl is never inferred from searchUrl.

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;
  },
});
  • Events - event taxonomy and field reference
  • Attribution - threading queryId from search through click and conversion events
  • Identity & Sessions - how session and user ids are generated and stored
  • Configuration - analyticsUrl, tenantCode, retries, and observability hooks

On this page