React Router and Vite
Use Kelp with a plain Vite + React SPA via the React hooks, or with React Router 7 in framework mode for server-side loaders.
Kelp works in two modes with React Router and Vite:
- Client-side (Vite SPA) - use the
@kelpclick/client/reacthooks directly. Everything runs in the browser. Both the Kelp search host and the analytics events host must send CORS headers for your origin. - Server-side (React Router 7 framework mode) - run search in loaders, proxy analytics through a resource route. The same pattern as the Shopify Hydrogen guide, without the Oxygen-specific parts.
Vite SPA setup
Install and create the client
npm install @kelpclick/clientCreate the client once at module scope - never inline in a component, or it will recreate identity on every render.
// src/kelp.ts
import { createKelpClient, type KelpDocumentBase } from '@kelpclick/client';
export interface Product extends KelpDocumentBase {
title: string;
handle: string;
vendor: string;
featuredImage?: string;
minPrice?: number;
maxPrice?: number;
}
export const kelp = createKelpClient({
searchUrl: import.meta.env.VITE_KELP_SEARCH_URL,
analyticsUrl: import.meta.env.VITE_KELP_ANALYTICS_URL,
apiKey: import.meta.env.VITE_KELP_API_KEY,
// tenantCode: import.meta.env.VITE_KELP_TENANT_CODE, // optional
maxRetries: 1,
});# .env.local
VITE_KELP_SEARCH_URL=https://{TENANT_ID}-search.kelp.click
VITE_KELP_ANALYTICS_URL=https://{TENANT_ID}-events.kelp.click
VITE_KELP_API_KEY=kelp_...Keys prefixed VITE_ are embedded in the browser bundle. Only ever use search-scoped, read-only keys client-side. See Security.
Wrap the app in KelpProvider
KelpProvider builds an identity and analytics tracker automatically. Pass your own analytics instance if you want to configure sanitizeEvent or flushAt.
// src/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { KelpProvider } from '@kelpclick/client/react';
import { kelp } from './kelp';
import App from './App';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<KelpProvider client={kelp}>
<App />
</KelpProvider>
</StrictMode>,
);Search page with useSearch
useSearch manages query state, debouncing, pagination, facets, and cancellation. It auto-emits a search analytics event on each result and returns trackProductClicked for click attribution.
// src/pages/SearchPage.tsx
import { useSearch } from '@kelpclick/client/react';
import type { Product } from '../kelp';
export function SearchPage() {
const {
query,
setQuery,
hits,
facetCounts,
found,
page,
setPage,
totalPages,
toggleFilter,
isFilterActive,
clearFilters,
isLoading,
error,
trackProductClicked,
} = useSearch<Product>({
collection: 'products',
facets: ['vendor', 'productType', 'gender'], // omit to receive all configured facets
perPage: 24,
debounceMs: 200,
fields: ['id', 'title', 'handle', 'vendor', 'featuredImage', 'minPrice'],
});
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search products..."
/>
{isLoading && <p>Searching...</p>}
{error && <p>Something went wrong.</p>}
{/* Facet sidebar */}
<aside>
{facetCounts.map((facet) => (
<div key={facet.field}>
<h3>{facet.field}</h3>
{facet.counts.map(({ value, count }) => (
<label key={value}>
<input
type="checkbox"
checked={isFilterActive(facet.field, value)}
onChange={() => toggleFilter(facet.field, value)}
/>
{value} ({count})
</label>
))}
</div>
))}
</aside>
{/* Results grid */}
<section>
<p>{found} results</p>
{hits.map((h) => (
<a
key={h.document.id}
href={`/products/${h.document.handle}`}
onClick={() => trackProductClicked(h.document.id)}
>
{h.document.title}
</a>
))}
</section>
{/* Pagination */}
<nav>
<button disabled={page <= 1} onClick={() => setPage(page - 1)}>Prev</button>
<span>{page} / {totalPages}</span>
<button disabled={page >= totalPages} onClick={() => setPage(page + 1)}>Next</button>
</nav>
</div>
);
}Blank query searches "*" (match-all), so an empty search box browses the full collection.
Collection page with useBrowse
useBrowse is useSearch without the query - use it for category/collection pages driven by filters and sort.
// src/pages/CollectionPage.tsx
import { useEffect } from 'react';
import { useBrowse, useKelpAnalytics } from '@kelpclick/client/react';
import type { Product } from '../kelp';
export function CollectionPage({ handle }: { handle: string }) {
const analytics = useKelpAnalytics();
const { hits, facetCounts, setFilters, toggleFilter, isFilterActive, page, setPage, totalPages, result, trackProductClicked } =
useBrowse<Product>({
collection: 'products',
sort: [{ field: 'variantsInStockPercentage', direction: 'desc' }],
perPage: 24,
});
// Scope to the collection by seeding a filter on mount / handle change.
useEffect(() => {
setFilters([{ field: 'collections', op: '=', values: [handle] }]);
}, [handle]);
// Fire collection_viewed on each page load (in addition to the auto search event).
useEffect(() => {
if (result?.queryId) {
analytics.trackCollectionViewed({ collection: 'products', objectId: handle, queryId: result.queryId });
}
}, [result?.queryId]);
return (
<div>
{hits.map((h) => (
<a key={h.document.id} href={`/products/${h.document.handle}`} onClick={() => trackProductClicked(h.document.id)}>
{h.document.title}
</a>
))}
</div>
);
}Product and conversion events
Pull the tracker from context for events that happen off the search results page.
// src/pages/ProductPage.tsx
import { useEffect, useRef } from 'react';
import { useKelpAnalytics } from '@kelpclick/client/react';
export function ProductPage({ product, queryId }: { product: Product; queryId?: string }) {
const analytics = useKelpAnalytics();
const tracked = useRef(false);
useEffect(() => {
if (tracked.current) return; // guard against StrictMode double-fire
tracked.current = true;
analytics.trackProductViewed({ collection: 'products', objectId: product.id });
}, [product.id]);
return (
<>
<button onClick={() => analytics.trackProductWishlisted({ collection: 'products', objectId: product.id })}>
Save
</button>
<button
onClick={() =>
analytics.trackProductAddedToCart({ collection: 'products', objectId: product.id, queryId })
}
>
Add to cart
</button>
</>
);
}CORS for local development
In a Vite SPA everything runs in the browser, so both the Kelp search and analytics hosts must send CORS headers for your origin in production. For local development, proxy through Vite to avoid CORS:
// vite.config.ts
export default {
server: {
proxy: {
'/kelp-search': {
target: 'https://{TENANT_ID}-search.kelp.click',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/kelp-search/, ''),
},
'/kelp-analytics': {
target: 'https://{TENANT_ID}-events.kelp.click',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/kelp-analytics/, ''),
},
},
},
};Set VITE_KELP_SEARCH_URL=/kelp-search and VITE_KELP_ANALYTICS_URL=/kelp-analytics in .env.local for local development.
Autosuggest
In both modes, autosuggest is a small search with field projection and a short debounce. In a Vite SPA, use a second useSearch instance with debounceMs: 120 and fields limiting the returned payload. In React Router 7, call a resource route (same pattern as the Hydrogen guide).
// Vite SPA autosuggest
import { useSearch } from '@kelpclick/client/react';
function Autosuggest() {
const { query, setQuery, hits, trackProductClicked } = useSearch<Product>({
collection: 'products',
perPage: 6,
debounceMs: 120,
fields: ['id', 'title', 'handle', 'featuredImage'],
});
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search..." />
{query && hits.map((h) => (
<a key={h.document.id} href={`/products/${h.document.handle}`} onClick={() => trackProductClicked(h.document.id)}>
{h.document.title}
</a>
))}
</div>
);
}Related
- Shopify Hydrogen - production SSR reference with caching, tenantCode injection, and the full analytics funnel
- SSR and custom fetch - injecting fetch, same-origin proxies, and identity in SSR
- React - full
useSearch,useBrowse, andKelpProviderreference - Analytics - event taxonomy and
createAnalyticsoptions
SSR and custom fetch
Run the Kelp SDK in Node, Cloudflare Workers, or any SSR environment - inject a fetch implementation, pass request signals, and proxy same-origin.
Catalog fields reference
All Shopify product fields available in a Kelp products collection - searchable, filterable, sortable, and rankable.