Shopify Hydrogen / React storefronts
Server-side search in route loaders behind a capability seam, same-origin analytics proxy, full client funnel wiring, and conversion tracking via a Shopify custom pixel - for Hydrogen on Oxygen.
Kelp fits Hydrogen's server-first model naturally: search runs server-side in loaders (SSR gives you SEO and no CORS), and analytics runs client-side with event batches forwarded through a same-origin resource route so the API key never reaches the browser.
Key patterns in this guide:
- A provider-agnostic
SearchProviderseam - swap Kelp for anything by changing one line. createKelpSearchin loaders with field projection,AbortSignal.timeout, andmaxRetries.- A same-origin
/analytics/eventsproxy with server-sidetenantCodeinjection. - A shared
analytics.client.tsmodule (module singleton) - routes and components lazy-import it inside effects so the SSR bundle stays clean. queryIdthreaded from the loader response through click and add-to-cart events via sessionStorage.- Cart attributes stamped server-side during
LinesAddsosessionIdanduserIdsurvive the checkout redirect. - A Shopify custom pixel reading those attributes to send the
purchaseevent at order completion.
Install and configure
npm install @kelpclick/clientAdd these to your Oxygen environment (and to the Env type in env.d.ts):
PUBLIC_KELP_SEARCH_URL=https://{TENANT_ID}-search.kelp.click
PUBLIC_KELP_ANALYTICS_URL=https://{TENANT_ID}-events.kelp.click
PUBLIC_KELP_API_KEY=kelp_...
PUBLIC_KELP_TENANT_CODE={TENANT_ID}
PUBLIC_KELP_PRODUCTS_COLLECTION=products # optional override, defaults to 'products'All vars are server-side only. Loaders read them from context.env; the proxy route attaches the key before forwarding. None are injected into window.ENV, so no CORS configuration is needed on the analytics host and the API key never leaves the server.
Define the search seam
Depend on a capability interface, not on Kelp directly. This lets you swap the search engine by changing one line in index.ts.
// app/lib/search/types.ts
import type { KelpFilter, KelpFacetCount, SortItem } from '@kelpclick/client';
export interface SearchQuery {
q?: string;
collectionHandle?: string;
filters?: KelpFilter[];
sort?: SortItem[];
facets?: string[];
page?: number;
perPage?: number;
userId?: string;
personalize?: boolean;
}
export interface SearchResult {
hits: Array<{ id: string; title: string; handle: string; [k: string]: unknown }>;
facetCounts: KelpFacetCount[];
found: number;
page: number;
queryId?: string;
}
export interface SearchProvider {
readonly name: string;
search(env: Env, query: SearchQuery): Promise<SearchResult>;
suggest(env: Env, term: string, limit?: number): Promise<SearchResult>;
}// app/lib/search/index.ts
import { kelpProvider } from './providers/kelp';
import type { SearchProvider } from './types';
export type { SearchQuery, SearchResult, SearchProvider };
// Swap this one line to change search engines without touching any route.
export function getSearchProvider(_env: Env): SearchProvider {
return kelpProvider;
}Create the Kelp adapter
The adapter is the only file that imports the SDK. It uses createKelpSearch (search-only; no analytics wired here) and wraps calls in a 4-second timeout with 2 retry attempts on transient failures.
// app/lib/search/providers/kelp/client.ts
import { createKelpSearch, type KelpSearch } from '@kelpclick/client';
export function createSearchClient(env: Env): KelpSearch {
return createKelpSearch({
searchUrl: env.PUBLIC_KELP_SEARCH_URL,
analyticsUrl: env.PUBLIC_KELP_ANALYTICS_URL, // required by config; search client never posts events
apiKey: env.PUBLIC_KELP_API_KEY,
tenantCode: env.PUBLIC_KELP_TENANT_CODE,
maxRetries: 2,
});
}// app/lib/search/providers/kelp/index.ts
import type { SearchProvider, SearchQuery, SearchResult } from '../../types';
import { createSearchClient } from './client';
const COLLECTION = 'products';
// Field projection - return only what the UI renders. Trimming the payload
// reduces transfer size; keep this list in sync with your normalizer.
const FIELDS = [
'id',
'objectId',
'handle',
'title',
'vendor',
'featuredImage',
'minPrice',
'maxPrice',
'collections',
'status',
'productType',
];
export const kelpProvider: SearchProvider = {
name: 'kelp',
async search(env, query) {
const client = createSearchClient(env);
const filters = [
...(query.filters ?? []),
// Scope to a Shopify collection via a configured facet field.
...(query.collectionHandle
? [{ field: 'collections', op: '=' as const, values: [query.collectionHandle] }]
: []),
];
// Empty query on a collection page -> browse endpoint (uses the configured
// ranking/sort config). A real search term -> search endpoint (text relevance).
// Sending q:'*' to search runs the relevance pipeline and bypasses browse
// ranking, so the two endpoints would order results differently.
const term = query.q?.trim() ?? '';
const isBrowse = term.length === 0;
const params = {
filters,
facets: query.facets, // omit to receive all configured facet attributes
sort: query.sort,
page: query.page ?? 1,
perPage: query.perPage ?? 24,
fields: FIELDS,
userId: query.userId,
personalize: query.personalize,
};
const signal = AbortSignal.timeout(4000);
const res = isBrowse
? await client.browse(COLLECTION, params, { signal })
: await client.search(COLLECTION, { ...params, q: term }, { signal });
return {
hits: res.hits.map((h) => h.document as SearchResult['hits'][number]),
facetCounts: res.facetCounts,
found: res.found,
page: res.page,
queryId: res.queryId,
};
},
async suggest(env, term, limit = 6) {
const client = createSearchClient(env);
const res = await client.search(
COLLECTION,
{ q: term, perPage: limit, fields: ['id', 'title', 'handle', 'featuredImage'] },
{ signal: AbortSignal.timeout(4000) },
);
return {
hits: res.hits.map((h) => h.document as SearchResult['hits'][number]),
facetCounts: [],
found: res.found,
page: 1,
queryId: res.queryId,
};
},
};facets is optional. Omitting it returns counts for every configured facet attribute on the collection - useful if you want to let the index control which facets are available. Pass an explicit list to limit the fields returned.
Add caching (anonymous dedup + personalized preservation)
For production deployments, a caching layer between the loader and Kelp collapses anonymous/bot traffic onto a shared response and still serves personalized results for known users.
The strategy is:
- Anonymous requests (no
userId) share a single cache entry keyed by query/filters/sort/page. This deduplicates the high-volume, non-differentiated traffic. - Personalized requests (with
userId) bypass or get a separate short-TTL cache entry so each user gets their own re-ranked results.
// app/lib/search/cache.ts
// Minimal example - adapt to your platform (Workers KV, Cache API, Redis, etc.)
export type CacheScope = 'neutral' | 'personalized';
export interface CacheOptions {
cacheScope: CacheScope;
userToken?: string;
personalizedCacheTtlMs?: number;
query?: string;
hasHits?: (result: unknown) => boolean;
}
// Build a stable string key from any serialisable input.
export function makeCacheKey(input: unknown): string {
return JSON.stringify(input);
}
// Wrap a Kelp call with a cache. Personalized requests use a shorter TTL
// (or skip caching entirely by setting personalizedCacheTtlMs: 0).
export async function cachedFetch<T>(
keyInput: unknown,
fetch: () => Promise<T>,
options: CacheOptions,
): Promise<T> {
const { cacheScope, personalizedCacheTtlMs = 0 } = options;
// Skip caching for personalized requests if TTL is 0.
if (cacheScope === 'personalized' && personalizedCacheTtlMs === 0) {
return fetch();
}
// Platform-specific cache lookup/store omitted - plug in Workers KV, the
// Cache API, or any key-value store here. The key excludes userId for
// 'neutral' scope so anonymous traffic collapses onto one entry.
return fetch();
}In the adapter, pass the request's cache scope and user token when calling cachedFetch:
// Determine cache scope from your session/gate logic.
const cacheScope = query.userId ? 'personalized' : 'neutral';
const result = await cachedFetch(
{ collection: COLLECTION, mode: isBrowse ? 'browse' : 'search', term, filters, sort: params.sort, page: params.page, perPage: params.perPage },
() => (isBrowse ? client.browse(...) : client.search(...)),
{ cacheScope, userToken: query.userId, personalizedCacheTtlMs: 30_000 },
);Use the provider in loaders
Both the search page and collection pages follow the same pattern: parse URL params, call the provider, return the result. The loader runs server-side on every request (including crawlers), so the first paint is fully rendered HTML with results and facets.
// app/routes/search.tsx
import { useLoaderData, useSearchParams } from 'react-router';
import { getSearchProvider } from '~/lib/search';
export async function loader({ request, context }: Route.LoaderArgs) {
const url = new URL(request.url);
const q = url.searchParams.get('q') ?? '';
const page = Number(url.searchParams.get('page') ?? '1');
// Parse facet selections from URL params (convention: f.<field>=<value>).
const filters = [...url.searchParams.entries()]
.filter(([k]) => k.startsWith('f.'))
.map(([k, v]) => ({ field: k.slice(2), op: '=' as const, values: v.split(',') }));
// Read userId from session/cookie for personalization.
const userId = await getUserIdFromSession(request); // your own helper
const result = await getSearchProvider(context.env).search(context.env, {
q,
filters,
page,
perPage: 24,
facets: ['vendor', 'productType', 'gender'], // or omit for all configured facets
...(userId ? { userId, personalize: true } : {}),
});
return { result, q };
}
export default function SearchPage() {
const { result, q } = useLoaderData<typeof loader>();
const [params, setParams] = useSearchParams();
// Facet toggles rewrite f.<field> URL params; the loader re-runs (SSR).
// result.queryId is passed down to analytics effects - see Step 7.
return (
<div>
{/* render result.hits, result.facetCounts, result.found, pagination via ?page= */}
</div>
);
}// app/routes/collections.$handle.tsx
export async function loader({ params, request, context }: Route.LoaderArgs) {
const url = new URL(request.url);
const filters = [...url.searchParams.entries()]
.filter(([k]) => k.startsWith('f.'))
.map(([k, v]) => ({ field: k.slice(2), op: '=' as const, values: v.split(',') }));
const result = await getSearchProvider(context.env).search(context.env, {
collectionHandle: params.handle, // adapter adds the `collections =` filter
filters,
sort: [{ field: 'variantsInStockPercentage', direction: 'desc' }],
page: Number(url.searchParams.get('page') ?? '1'),
perPage: 24,
});
return { result, handle: params.handle };
}Proxy analytics same-origin
Create a resource route at app/routes/analytics.events.tsx. The browser client posts to /analytics/events (same-origin), and this route forwards the batch to the Kelp events host with the real API key attached server-side. tenantCode is injected here too so the browser bundle never needs it.
// app/routes/analytics.events.tsx
import type { Route } from './+types/analytics.events';
export async function action({ request, context }: Route.ActionArgs) {
if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}
const rawBody = await request.text();
// Inject tenantCode server-side so it never appears in browser traffic.
let body = rawBody;
const tenantCode = context.env.PUBLIC_KELP_TENANT_CODE;
if (tenantCode) {
try {
const envelope = JSON.parse(rawBody) as Record<string, unknown>;
if (!envelope.tenantCode) {
envelope.tenantCode = tenantCode;
body = JSON.stringify(envelope);
}
} catch {
// Body was not valid JSON - forward unchanged.
}
}
const upstream = await fetch(`${context.env.PUBLIC_KELP_ANALYTICS_URL}/analytics/events`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'X-Api-Key': context.env.PUBLIC_KELP_API_KEY,
// Forward the SDK client tag for server observability.
...(request.headers.get('x-kelp-client')
? { 'X-Kelp-Client': request.headers.get('x-kelp-client') as string }
: {}),
},
body,
});
return new Response(null, { status: upstream.status });
}Initialize the client-side analytics module
Create a .client.ts file (Hydrogen excludes .client.ts from the SSR bundle). Use analyticsUrl: '' so the SDK posts to the same-origin proxy. The placeholder apiKey: 'browser' is replaced by the proxy route.
The identity export is a module-scope singleton. Share this one instance everywhere (analytics events, cart attribute stamping, the pixel stitch). Anonymous-to-known stitching only works when all events share one identity.
// app/lib/kelp-search/analytics.client.ts
import {
createKelpClient,
createIdentity,
createAnalytics,
type KelpAnalyticsEvent,
} from '@kelpclick/client';
const EMAIL_RE = /[^\s@]+@[^\s@]+\.[^\s@]+/;
// Module-scope shared identity singleton. The keyPrefix namespaces the
// sessionStorage/localStorage keys so they do not collide with other libraries.
// Never change this prefix once live sessions exist - it would reset all stored
// ids, breaking session continuity.
export const identity = createIdentity({ keyPrefix: 'kelp' });
export const analytics = createAnalytics({
client: createKelpClient({
searchUrl: '', // unused client-side
analyticsUrl: '', // same-origin: SDK posts to /analytics/events
apiKey: 'browser', // placeholder - proxy attaches the real key
// PUBLIC_KELP_TENANT_CODE is not exposed to the browser; the proxy stamps it.
}),
identity,
// Redact email-shaped queries before they leave the browser.
sanitizeEvent: (event: KelpAnalyticsEvent) =>
event.q && EMAIL_RE.test(event.q) ? { ...event, q: '[redacted]' } : event,
});
// ---------------------------------------------------------------------------
// sessionStorage attribution threading
//
// After a search or collection browse the loader returns a queryId. Persist it
// in sessionStorage so the PDP and add-to-cart can read it even after navigating
// away from the results page. This is more robust than router location.state,
// which is lost on refresh.
const QUERY_ID_KEY = 'kelp_query_id';
/** Persist the queryId from a search or browse result. SSR-safe (no-ops on server). */
export function setStoredQueryId(token: string | undefined): void {
if (typeof window === 'undefined') return;
if (!token) return;
window.sessionStorage.setItem(QUERY_ID_KEY, token);
}
/** Read the persisted queryId for PDP and add-to-cart attribution. SSR-safe. */
export function getStoredQueryId(): string | undefined {
if (typeof window === 'undefined') return undefined;
return window.sessionStorage.getItem(QUERY_ID_KEY) ?? undefined;
}
/**
* Return the resolved userId to stamp on cart attributes.
* Matches what the SDK stamps on funnel events exactly:
* known user id > 'anon_<anonymousId>' for guests.
* A guest's purchase event stitches to their search events via this value.
*/
export function getResolvedUserId(): string {
return identity.getUserId() ?? `anon_${identity.getAnonymousId()}`;
}Wire the full client funnel
analytics.client.ts is excluded from the SSR bundle by its .client.ts suffix. Import it lazily inside useEffect calls so route modules stay SSR-safe. All calls resolve to the same module-scope singleton - identity is shared, so session/user ids are stable across the page lifetime.
objectId convention
objectId must be the Shopify product numeric id - the GID tail, not the handle:
// gid://shopify/Product/9149995942110 -> '9149995942110'
const objectId = String(gid).split('/').pop();This applies at every event call site: product_clicked, product_viewed, product_added_to_cart, and purchase line items.
Search page
// app/routes/search.tsx
import { useEffect } from 'react';
import { useLoaderData } from 'react-router';
export default function SearchPage() {
const { result, q } = useLoaderData<typeof loader>();
// Search analytics, once per result set (keyed on queryId).
// Lazy import keeps this route module SSR-safe.
useEffect(() => {
void import('~/lib/kelp-search/analytics.client').then(
({ analytics, setStoredQueryId }) => {
// Persist queryId in sessionStorage so the PDP and add-to-cart can
// pick it up for attribution even after navigating away from this page.
setStoredQueryId(result.queryId);
analytics.trackSearch({
collection: 'products',
// Empty box is browse-all; report '*' (the ingester rejects an empty q).
q: q || '*',
found: result.found,
page: result.page,
queryId: result.queryId,
});
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [result.queryId]);
return (
<div>
{result.hits.map((hit) => (
<a
key={hit.id}
href={`/products/${hit.handle}`}
onClick={() => {
void import('~/lib/kelp-search/analytics.client').then(
({ analytics }) => {
analytics.trackProductClicked({
collection: 'products',
objectId: String(hit.id).split('/').pop()!,
queryId: result.queryId,
});
},
);
}}
>
{hit.title}
</a>
))}
</div>
);
}Key the useEffect on result.queryId so it fires once per result set. The setStoredQueryId call persists the token for downstream PDP and add-to-cart attribution even after the user navigates away from the search page.
Collection page
// app/routes/collections.$handle.tsx
import { useEffect } from 'react';
import { useLoaderData } from 'react-router';
export default function CollectionPage() {
const { result, handle } = useLoaderData<typeof loader>();
// collection_viewed event. objectId = the collection handle (not a product id).
// Also persists queryId for downstream PDP / add-to-cart attribution.
useEffect(() => {
void import('~/lib/kelp-search/analytics.client').then(
({ analytics, setStoredQueryId }) => {
setStoredQueryId(result.queryId);
analytics.trackCollectionViewed({
collection: 'products',
objectId: handle, // e.g. 'mens-shoes', 'all'
queryId: result.queryId,
});
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [result.queryId]);
// ...render hits, facets, pagination
}Product detail page (PDP)
// app/routes/products.$handle.tsx
import { useEffect } from 'react';
import { useLoaderData } from 'react-router';
export default function ProductPage() {
const { product } = useLoaderData<typeof loader>();
// product_viewed once per product load.
// objectId = numeric id (GID suffix). queryId comes from sessionStorage
// (set by the search or collection route the visitor came from).
useEffect(() => {
let cancelled = false;
void import('~/lib/kelp-search/analytics.client').then(
({ analytics, getStoredQueryId }) => {
if (cancelled) return;
const objectId = String(product.id).split('/').pop()!;
analytics.trackProductViewed({
collection: 'products',
objectId,
queryId: getStoredQueryId(),
});
},
);
return () => { cancelled = true; };
}, [product.id]);
// ...render product, ProductForm
}ProductForm: hidden inputs and add-to-cart event
The ProductForm stamps the Kelp identity values as controlled hidden inputs so the server-side LinesAdd handler can write them as cart attributes. Analytics is lazy-imported inside useEffect (SSR-safe). The onSuccess callback fires after the cart mutation confirms - not on button click.
// app/components/ProductForm.tsx (simplified)
import { useEffect, useState } from 'react';
import { AddToCartButton } from './AddToCartButton';
// Neutral field names - must match what cart.tsx reads from formData.
const FIELD_SESSION_ID = 'kelpSessionId';
const FIELD_USER_ID = 'kelpUserId';
export function ProductForm({ productId, selectedVariant }) {
// Populated client-only via useEffect (SSR: stays empty, avoids hydration mismatch).
const [conversionFields, setConversionFields] = useState<Record<string, string>>({});
useEffect(() => {
void import('~/lib/kelp-search/analytics.client').then(
({ identity, getResolvedUserId }) => {
const sessionId = identity.getSessionId();
// getResolvedUserId() returns 'anon_<anonymousId>' for guests -
// the same value the SDK stamps on funnel events - so the purchase
// pixel can stitch to them even for anonymous visitors.
const userId = getResolvedUserId();
const fields: Record<string, string> = {};
if (sessionId) fields[FIELD_SESSION_ID] = sessionId;
if (userId) fields[FIELD_USER_ID] = userId;
setConversionFields(fields);
},
);
}, []);
const objectId = String(productId).split('/').pop()!;
return (
<AddToCartButton
hiddenFields={Object.keys(conversionFields).length > 0 ? conversionFields : undefined}
onSuccess={() => {
// Fires AFTER the cart mutation succeeds (not on click).
void import('~/lib/kelp-search/analytics.client').then(
({ analytics, getStoredQueryId }) => {
analytics.trackProductAddedToCart({
collection: 'products',
objectId,
queryId: getStoredQueryId(),
});
},
);
}}
lines={[{ merchandiseId: selectedVariant.id, quantity: 1, selectedVariant }]}
>
{selectedVariant?.availableForSale ? 'Add to cart' : 'Sold out'}
</AddToCartButton>
);
}conversionFields is intentionally empty on the server and populated in a useEffect. This avoids hydration mismatches. The two hidden inputs are controlled from this state - no imperative DOM reads.
Typeahead / autosuggest
Typeahead clicks also fire trackProductClicked. Pass position (1-based) when available:
// app/routes/api.suggest.tsx (resource route - returns JSON)
import { getSearchProvider } from '~/lib/kelp-search';
export async function loader({ request, context }: Route.LoaderArgs) {
const term = new URL(request.url).searchParams.get('q')?.trim();
if (!term) return Response.json({ hits: [], queryId: null });
const result = await getSearchProvider(context.env).suggest(context.env, term);
return Response.json({ hits: result.hits, queryId: result.queryId });
}// Client typeahead component
import { useState, useEffect } from 'react';
import { useFetcher } from 'react-router';
function PredictiveSearch() {
const [term, setTerm] = useState('');
const fetcher = useFetcher<{ hits: Array<{ id: string; title: string; handle: string }>; queryId?: string }>();
useEffect(() => {
if (term.trim()) {
fetcher.load(`/api/suggest?q=${encodeURIComponent(term)}`);
}
}, [term]);
const queryId = fetcher.data?.queryId;
return (
<div>
<input value={term} onChange={(e) => setTerm(e.target.value)} placeholder="Search..." />
{fetcher.data?.hits.map((hit, i) => (
<a
key={hit.id}
href={`/products/${hit.handle}`}
onClick={() => {
void import('~/lib/kelp-search/analytics.client').then(({ analytics }) => {
analytics.trackProductClicked({
collection: 'products',
objectId: String(hit.id).split('/').pop()!,
queryId,
position: i + 1, // 1-based position in the typeahead list
});
});
}}
>
{hit.title}
</a>
))}
</div>
);
}Stamp cart attributes server-side
When a visitor checks out, Kelp needs sessionId and userId to stitch the purchase event back to the originating search. These must survive the redirect to the Shopify checkout - the only reliable path is via cart attributes. Purchase events attribute via session and user ID; queryId is used on mid-funnel events (e.g. product_added_to_cart) only.
Stamping happens server-side during the LinesAdd cart action - this covers both Add to Cart and Buy Now in one place, and it is race-free because the attributes are written before the 303 redirect fires.
Do not stamp attributes client-side after the form submits. Buy Now fires a server-side redirect immediately - a subsequent client fetch would race and lose. The server-side LinesAdd path wins unconditionally.
Hidden inputs carry the values from client to server
The two hidden inputs in the ProductForm (kelpSessionId, kelpUserId) are populated from client state (see the previous step) and submitted as form fields with the LinesAdd action. The server reads them from formData.
Cart action
// app/routes/cart.tsx (LinesAdd case)
import { CartForm } from '@shopify/hydrogen';
// Neutral form-field names. Defined as constants so ProductForm and the cart
// action stay in sync without importing from each other.
const CONVERSION_FIELDS = {
sessionId: 'kelpSessionId',
userId: 'kelpUserId',
} as const;
// Build the _kelp_* cart attributes from identity values.
// The _ prefix hides them from the Shopify cart UI but they appear in checkout.attributes.
function buildKelpCartAttributes(params: {
sessionId?: string | null;
userId?: string | null;
}): Array<{ key: string; value: string }> {
const attrs: Array<{ key: string; value: string }> = [];
if (params.sessionId) attrs.push({ key: '_kelp_session_id', value: params.sessionId });
if (params.userId) attrs.push({ key: '_kelp_user_id', value: params.userId });
return attrs;
}
// Merge new attributes onto the existing cart attributes. Shopify's
// updateAttributes replaces the full list, so we read first and merge
// to avoid clobbering non-Kelp attributes (UTM params, gift messages, etc.).
async function mergeKelpCartAttributes(
cart: Route.ActionArgs['context']['cart'],
newAttrs: Array<{ key: string; value: string }>,
): Promise<void> {
if (newAttrs.length === 0) return;
const currentCart = await cart.get();
const existing: Array<{ key: string; value: string }> = (
currentCart?.attributes ?? []
).flatMap((a) =>
a.key && a.value != null ? [{ key: a.key, value: a.value }] : [],
);
// New values win for Kelp keys; all others are kept unchanged.
const merged = [...existing];
for (const attr of newAttrs) {
const idx = merged.findIndex((a) => a.key === attr.key);
if (idx >= 0) {
merged[idx] = attr;
} else {
merged.push(attr);
}
}
await cart.updateAttributes(merged);
}
export async function action({ request, context }: Route.ActionArgs) {
const { cart } = context;
const formData = await request.formData();
const { action, inputs } = CartForm.getFormInput(formData);
let result: CartQueryDataReturn;
switch (action) {
case CartForm.ACTIONS.LinesAdd: {
result = await cart.addLines(inputs.lines);
// Stamp Kelp conversion attributes AFTER the line add succeeds.
// Best-effort: if this fails the cart add has already succeeded,
// so log and continue rather than surfacing an error to the customer.
const sessionId = formData.get(CONVERSION_FIELDS.sessionId) as string | null;
const userId = formData.get(CONVERSION_FIELDS.userId) as string | null;
const kelpAttrs = buildKelpCartAttributes({ sessionId, userId });
if (kelpAttrs.length > 0) {
await mergeKelpCartAttributes(cart, kelpAttrs).catch((err: unknown) => {
console.error('Kelp cart attribute stamp failed', err);
});
}
break;
}
// ... other cases
}
}Attributes written
| Cart attribute | Value | Notes |
|---|---|---|
_kelp_session_id | identity.getSessionId() | Written on every add when non-empty. |
_kelp_user_id | identity.getUserId() or anon_<anonymousId> | Written on every add when non-empty. The anon_* form matches what the SDK stamps on funnel events, so guest purchases stitch correctly. |
The _ prefix keeps these out of the Shopify storefront cart UI. They do appear in checkout.attributes, which is where the custom pixel reads them.
Conversion tracking: Shopify custom pixel
The purchase event is sent from a Shopify custom pixel - not from the storefront JavaScript. The pixel runs in a sandboxed iframe inside the Shopify checkout and fires on the checkout_completed event, after the order is confirmed. It reads _kelp_* from checkout.attributes and POSTs the event to the Kelp events host directly.
Why a pixel instead of the analytics tracker
The storefront JavaScript does not run during or after the Shopify checkout. The Shopify Web Pixel API is the only reliable way to receive the checkout_completed event.
Why queryId is omitted on purchase
A single order-level queryId cannot represent a mixed-origin cart (items added after different searches, from recommendations, or browsed directly). Attaching the last-stored queryId would misattribute conversions for most real-world carts. Search-to-conversion attribution still works via sessionId and userId - those identifiers are stable across the full session, so Kelp can link any purchase to the searches and clicks that preceded it.
Full pixel code
Copy the code below into the Shopify admin pixel editor and fill the three PLACEHOLDER values before saving. Never commit real credentials to source control.
// pixels/kelp-purchase.js
// Register via: Shopify admin -> Settings -> Customer events -> Add custom pixel
// ---------------------------------------------------------------------------
// Config - replace PLACEHOLDER values before saving in Shopify admin
// ---------------------------------------------------------------------------
const KELP_EVENTS_URL = 'https://{TENANT_ID}-events.kelp.click'; // = PUBLIC_KELP_ANALYTICS_URL
const KELP_API_KEY = '<KELP_API_KEY>'; // paste real key in Shopify admin
const KELP_TENANT_CODE = '{TENANT_ID}'; // = PUBLIC_KELP_TENANT_CODE
const KELP_COLLECTION = 'products'; // = PUBLIC_KELP_PRODUCTS_COLLECTION
// ---------------------------------------------------------------------------
// Pixel
// ---------------------------------------------------------------------------
analytics.subscribe('checkout_completed', function (event) {
try {
var checkout = event.data.checkout;
if (!checkout) return;
// --- Attribution identifiers from cart attributes ---
// Cart attributes are an array of {key, value} objects.
// The _kelp_* keys are stamped by the storefront before checkout.
var attrs = Array.isArray(checkout.attributes) ? checkout.attributes : [];
function getAttr(key) {
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].key === key) {
var v = attrs[i].value;
return typeof v === 'string' && v.length > 0 ? v : null;
}
}
return null;
}
var sessionId = getAttr('_kelp_session_id');
var userId = getAttr('_kelp_user_id');
// Note: queryId is intentionally NOT sent on the purchase event. A single
// order-level queryId cannot represent a mixed-origin cart (items added
// after different searches), so it carries no meaningful attribution weight.
// Search-to-conversion is still linked via sessionId/userId.
// --- Order identifiers ---
// checkout.order.id is the GID (gid://shopify/Order/123...); use as-is.
// Fall back to checkout.token when the order object is not yet materialised.
var orderId = String(
(checkout.order && checkout.order.id) || checkout.token || '',
);
// --- Value & currency ---
var value = Number(
checkout.totalPrice && checkout.totalPrice.amount
? checkout.totalPrice.amount
: 0,
);
var currency = checkout.currencyCode || '';
// --- Line items ---
// objectId = Shopify product numeric id (GID suffix, or plain number).
// li.variant.product.id may be a full GID ("gid://shopify/Product/123...")
// or just the numeric string depending on the Shopify pixel SDK version;
// split('/').pop() is safe in both cases.
var lineItems = Array.isArray(checkout.lineItems) ? checkout.lineItems : [];
var items = [];
for (var j = 0; j < lineItems.length; j++) {
var li = lineItems[j];
var variant = li && li.variant;
var product = variant && variant.product;
if (!product || !product.id) continue;
items.push({
objectId: String(product.id).split('/').pop(),
quantity: li.quantity || 1,
price: Number(
variant.price && variant.price.amount ? variant.price.amount : 0,
),
});
}
// --- Build envelope ---
var purchaseEvent = {
kind: 'purchase',
occurredAt: new Date().toISOString(),
collection: KELP_COLLECTION,
orderId: orderId,
value: value,
currency: currency,
items: items,
};
// Attach attribution fields only when present.
// If both are absent the purchase is still sent (orderId/value/items are
// the core conversion data); we just omit the attribution fields.
if (sessionId) purchaseEvent.sessionId = sessionId;
if (userId) purchaseEvent.userId = userId;
var envelope = {
id: crypto.randomUUID(),
tenantCode: KELP_TENANT_CODE,
events: [purchaseEvent],
};
// --- POST to Kelp events host ---
fetch(KELP_EVENTS_URL + '/analytics/events', {
method: 'POST',
keepalive: true,
headers: {
'content-type': 'application/json',
'X-Api-Key': KELP_API_KEY,
},
body: JSON.stringify(envelope),
});
// No response body is expected; swallow silently.
} catch (err) {
console.error('[kelp-purchase] Failed to send purchase event:', err);
}
});Register the pixel in Shopify admin
- Go to Settings -> Customer events -> Add custom pixel.
- Give it a name (e.g.
Kelp Purchase Conversion). - Paste the full pixel code into the editor.
- Replace the three
PLACEHOLDERvalues:KELP_EVENTS_URL= yourPUBLIC_KELP_ANALYTICS_URLvalueKELP_API_KEY= your tenant API key (events-write scope)KELP_TENANT_CODE= yourPUBLIC_KELP_TENANT_CODEvalue
- Save and publish.
The API key is visible in the Shopify admin pixel editor. Use a key scoped to events-write only - never a search or admin key. The pixel sandbox is isolated from the storefront origin.
Verify the full chain
After deploying, confirm the full attribution chain works:
- Cart attributes: after adding a product to cart, check via Storefront API or Shopify admin order detail that
_kelp_session_idand_kelp_user_idare present on the cart. - Checkout attributes: complete a test order and inspect the order's attributes in Shopify admin. Both
_kelp_*keys should appear there. - Pixel fires: check the pixel's activity log in Shopify admin (Settings -> Customer events) or confirm the event appears in your Kelp dashboard.
Full data flow
search loader (server, returns queryId)
-> setStoredQueryId (client, sessionStorage)
-> product_clicked / product_added_to_cart events carry queryId
-> hidden form inputs carry sessionId + userId
-> LinesAdd cart action (server, stamps _kelp_session_id + _kelp_user_id on cart.attributes)
-> checkout.attributes
-> Shopify custom pixel (checkout_completed)
-> POST to Kelp events host (purchase event with sessionId + userId)Mid-funnel events (product_clicked, product_added_to_cart) carry queryId. The purchase event omits queryId by design and attributes via sessionId/userId instead.
Email capture
Use createKelpEmail with tracker: analytics so newsletter opt-in events travel through the same same-origin proxy as all other analytics. Create the instance lazily with useRef so it is only constructed once per mount.
// app/components/SubscribeForm.tsx
import { useState, useRef } from 'react';
import { createKelpEmail } from '@kelpclick/client/email';
import { analytics, identity } from '~/lib/kelp-search/analytics.client';
type KelpEmailInstance = ReturnType<typeof createKelpEmail>;
export function SubscribeForm({ source = 'footer' }: { source?: string }) {
const emailRef = useRef<KelpEmailInstance | null>(null);
const [email, setEmail] = useState('');
const [submitted, setSubmitted] = useState(false);
const getEmail = (): KelpEmailInstance => {
if (!emailRef.current) {
// Shares the same buffer and flush loop as the main analytics instance.
emailRef.current = createKelpEmail({ identity, tracker: analytics });
}
return emailRef.current;
};
if (submitted) return <p>Subscribed - thanks!</p>;
return (
<form
onSubmit={(e) => {
e.preventDefault();
const trimmed = email.trim();
if (!trimmed) return;
// subscribe() is synchronous - buffered and flushed with the next batch.
// Also calls identity.identify({ email }) for anonymous-to-known stitching.
getEmail().subscribe({ email: trimmed, source });
setSubmitted(true);
}}
>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
required
/>
<button type="submit">Subscribe</button>
</form>
);
}Related
- SSR and custom fetch - framework-agnostic SSR patterns
- Analytics - full analytics event taxonomy
- Attribution - queryId threading and purchase attribution
- Configuration -
maxRetries,timeoutMs, and observability hooks - Merchandising - pin, boost, bury, hide without theme changes
- Security - key scoping and PII guidance