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.

The Kelp core client (createKelpClient, createKelpSearch) is framework-agnostic and runs in any JavaScript runtime that provides fetch - browsers, Node 18+, and Cloudflare Workers (Oxygen). If your runtime has no global fetch, inject one.

Injecting a custom fetch

Pass a fetch implementation via the fetch option on createKelpClient or createKelpSearch:

import { createKelpClient } from '@kelpclick/client';
import nodeFetch from 'node-fetch'; // Node < 18, or a custom agent

const kelp = createKelpClient({
  searchUrl: process.env.KELP_SEARCH_URL!,
  analyticsUrl: process.env.KELP_ANALYTICS_URL!,
  apiKey: process.env.KELP_API_KEY!,
  fetch: nodeFetch as unknown as typeof fetch,
});

When fetch is omitted the SDK uses globalThis.fetch. Cloudflare Workers (including Oxygen) and Node 18+ both provide it, so you typically do not need to inject one.

Using a request signal in loaders

Pass the incoming request's AbortSignal so Kelp cancels in-flight requests when the client navigates away or the request is aborted:

export async function loader({ request }: { request: Request }) {
  const res = await kelp.search('products', { q: 'shirt' }, { signal: request.signal });
  return res;
}

This works in React Router loaders, Next.js route handlers, and any framework that surfaces a Request object.

Same-origin proxy

When your app is server-rendered, both the search and analytics hosts can be proxied through the same origin as your app. This has two benefits:

  • No CORS - the browser only talks to your own origin.
  • Key stays server-side - the real API key is attached by the proxy, not shipped to the browser.

Pass an empty string ('') for searchUrl or analyticsUrl. The SDK treats '' as same-origin and constructs paths relative to the current host:

  • searchUrl: '' - search calls become POST /api/v1/collections/{collection}/search on your origin.
  • analyticsUrl: '' - analytics batches become POST /analytics/events on your origin.

searchUrl and analyticsUrl are independent. You can proxy just analytics (the common pattern in Hydrogen) and leave search pointing at the Kelp host directly.

Analytics proxy example

The most common pattern is to proxy only analytics, keeping search on the Kelp search host. The browser client sets analyticsUrl: '' and a server route forwards the batch:

// Browser analytics client (e.g. app/lib/analytics.client.ts)
import { createKelpClient, createIdentity, createAnalytics } from '@kelpclick/client';

export const identity = createIdentity();

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
  }),
  identity,
});
// Server proxy route (framework-agnostic handler)
export async function handleAnalyticsPost(request: Request, env: Env) {
  if (request.method !== 'POST') {
    return new Response('Method Not Allowed', { status: 405 });
  }

  const body = await request.text();

  const upstream = await fetch(`${env.KELP_ANALYTICS_URL}/analytics/events`, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'X-Api-Key': env.KELP_API_KEY,
    },
    body,
  });

  return new Response(null, { status: upstream.status });
}

See the Shopify Hydrogen guide for a full production-ready proxy route with tenantCode injection.

Identity in SSR

createIdentity uses localStorage by default. On the server, it falls back to an in-memory store automatically - getAnonymousId and getSessionId return stable values for the duration of the process, but they are not persisted across requests.

The recommended pattern is:

  1. Run search server-side with a userId read from a cookie or gate token (no need for createIdentity on the server).
  2. Initialize createIdentity client-side once, and hydrate a known user id with identity.identify({ userId }) after the customer logs in.
// Server loader - read userId from the session/cookie directly
export async function loader({ request }: { request: Request }) {
  const userId = getSessionUserId(request); // your own helper
  const res = await kelp.search('products', {
    q: 'shirt',
    userId,
    personalize: Boolean(userId),
  }, { signal: request.signal });
  return { result: res, userId };
}
// Client - hydrate identity after load
import { identity } from '~/lib/analytics.client';

// When the customer is logged in, identify them so subsequent events
// carry the real user id instead of the anonymous one.
if (userId) {
  identity.identify({ userId });
}

Environment variables

Never hardcode API keys. Load them from environment variables and keep them server-side where possible:

# Oxygen / Cloudflare / Node
KELP_SEARCH_URL=https://{TENANT_ID}-search.kelp.click
KELP_ANALYTICS_URL=https://{TENANT_ID}-events.kelp.click
KELP_API_KEY=kelp_...

See Security for key scoping guidance, and Configuration for all client options including maxRetries, timeoutMs, and observability hooks.

On this page