Attribution
How to thread queryId from a search response through click and conversion events to attribute purchases back to the originating query.
Every Kelp search response includes a queryId - a stable identifier for that specific query. Pass it forward into click, add-to-cart, and purchase events to build a complete attribution chain from query to conversion.
How it works
- Run a search. The response carries
queryId. - When the visitor interacts with a result, pass
queryIdto the corresponding analytics call. - Kelp ties the downstream event back to the originating search on the server.
// 1. Search
const res = await kelp.search('products', { q: 'running shoes' });
// res.queryId === '019f7571-998f-7bb5-abdd-0945c5be7a4a'
// 2. Track the search itself
analytics.trackSearch({
collection: 'products',
q: 'running shoes',
found: res.found,
page: res.page,
queryId: res.queryId,
});
// 3. Visitor clicks a result
analytics.trackProductClicked({
collection: 'products',
objectId: '9149995942110',
queryId: res.queryId, // attributes the click to this search
});
// 4. Visitor adds to cart
analytics.trackProductAddedToCart({
collection: 'products',
objectId: '9149995942110',
queryId: res.queryId, // attributes the cart add to this search
});
// 5. Order completes - queryId is typically OMITTED on purchase.
// See the note below on purchase attribution.
analytics.trackPurchase({
collection: 'products',
orderId: 'order-1001',
value: 129.99,
currency: 'USD',
items: [{ objectId: '9149995942110', quantity: 1, price: 129.99 }],
// queryId intentionally absent - attribution works via sessionId/userId
});Purchase attribution uses session/user id, not queryId. A real cart typically contains items from multiple searches, browsed pages, and recommendations. Attaching a single queryId to the order would misattribute the conversion for any cart built from more than one search. Kelp attributes purchases to searches via the shared sessionId and userId that are stamped on every event throughout the session.
Pass queryId on purchase only in simple single-page scenarios where you can guarantee the cart contains items from one search only.
Storing queryId across navigations
On a multi-page storefront, the search, click, and purchase events happen on different pages. Store queryId in session storage so it survives the navigation. Each new search or collection page load overwrites the stored value so attribution always points to the most recent search that led to the current PDP.
// Search page - save queryId after the search
const res = await kelp.search('products', { q: 'running shoes' });
if (res.queryId) {
sessionStorage.setItem('kelp_query_id', res.queryId);
}
analytics.trackSearch({
collection: 'products',
q: 'running shoes',
found: res.found,
page: res.page,
queryId: res.queryId,
});
// Product detail page - read it back for click attribution
const savedQueryId = sessionStorage.getItem('kelp_query_id') ?? undefined;
analytics.trackProductViewed({
collection: 'products',
objectId: productId,
// queryId not passed to product_viewed; it is used on the add-to-cart below
});
// Cart add - still within the same search session
analytics.trackProductAddedToCart({
collection: 'products',
objectId: productId,
queryId: savedQueryId,
});queryId is optional on every event. If it is absent, the event is still recorded - it just cannot be attributed to a specific search query.
Purchase attribution in Shopify Hydrogen
In Hydrogen, the storefront JavaScript does not run during the Shopify checkout. Conversion attribution must take a different path:
- sessionStorage holds
queryIdafter each search or collection page view. - The
ProductFormreadssessionIdanduserIdclient-side on mount and populates two controlled hidden inputs. - The hidden inputs are submitted with the
LinesAddcart action (both Add to Cart and Buy Now). - The server-side
LinesAddhandler reads those fields fromformDataand stamps_kelp_session_idand_kelp_user_idonto the cart's attributes before any checkout redirect fires. This is race-free - attributes are written in the same server request.queryIdis not stamped on the cart; it is used on mid-funnel events (product_added_to_cart) only. - Shopify carries those cart attributes through to
checkout.attributes. - A Shopify custom pixel subscribes to
checkout_completed, reads_kelp_session_idand_kelp_user_idfromcheckout.attributes, and POSTs thepurchaseevent to the Kelp events host.
The _kelp_user_id value is the resolved event userId: the identified user id when known, or anon_<anonymousId> for guests. This matches exactly what the SDK stamps on earlier funnel events, so a guest's purchase stitches to their search and click events by the identical userId.
See the Shopify Hydrogen guide for the full implementation including the pixel code.
Using a capability seam (Hydrogen and SSR storefronts)
On server-rendered storefronts like Shopify Hydrogen, search runs in a server loader and analytics fires client-side. The queryId must cross the server/client boundary through the loader response.
In Hydrogen, analytics.client.ts carries the .client.ts suffix so Vite excludes it from the SSR bundle. Import it lazily inside useEffect calls so route modules stay SSR-safe. All calls resolve to the same module-scope singleton - identity is shared across every event in the session.
// Server loader (e.g. app/routes/search.tsx)
export async function loader({ request, context }: Route.LoaderArgs) {
const result = await getSearchProvider(context.env).search(context.env, { q: query });
return {
hits: result.hits,
found: result.found,
queryId: result.queryId, // passed to the client in loader data
};
}
// Client component - lazy import keeps the route module SSR-safe
export default function SearchPage() {
const { hits, found, queryId } = useLoaderData<typeof loader>();
useEffect(() => {
void import('~/lib/kelp-search/analytics.client').then(
({ analytics, setStoredQueryId }) => {
setStoredQueryId(queryId); // persist for PDP attribution
analytics.trackSearch({ collection: 'products', q, found, queryId });
},
);
}, [queryId]);
return (
<ul>
{hits.map((hit) => (
<li key={hit.id}>
<a
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,
});
},
);
}}
>
{hit.title}
</a>
</li>
))}
</ul>
);
}The proxy pattern (analyticsUrl: '') keeps the real API key server-side. The browser posts analytics to /analytics/events on the same origin, and the server forwards the batch to the Kelp events host. See the Shopify Hydrogen guide for the full implementation including the proxy route.
With the React hooks
useSearch and useBrowse expose trackProductClicked directly. It closes over the current queryId so you do not have to manage it yourself:
const { hits, trackProductClicked } = useSearch<Product>({
collection: 'products',
facets: ['vendor'],
});
// In the render - trackProductClicked emits product_clicked with the current queryId
hits.map((hit) => (
<a
key={hit.document.id}
href={`/products/${hit.document.handle}`}
onClick={() => trackProductClicked(hit.document.id)}
>
{hit.document.title}
</a>
));Related
- Events - full event taxonomy and field reference
- Analytics overview - batching, flush, and
createAnalyticsoptions - Catalogue personalisation -
userIdandsessionIdalongsidequeryId(beta)