Shopify Liquid

Call Kelp from an Online Store theme - a Liquid section, theme JS, API search, facets, and queryId analytics.

This guide is storefront search UI on a Shopify Online Store (Liquid) theme. The section renders a mount root; theme JavaScript POSTs the Kelp API. You do not need npm. Hydrogen is a different stack - see Shopify Hydrogen / React storefronts.

Catalog sync is separate. Connecting the shop, product webhooks, and order popularity lives on Catalog sync (Shopify). This page assumes the collection already has documents.

Liquid cannot call Kelp by itself (no X-Api-Key from the server without an app proxy). The theme outputs HTML and settings; a small JS island performs fetch. That is the supported Online Store path.

What you build

  1. A section (or snippet) with a search form and a results root.
  2. Theme settings for the search host, optional proxy path, collection name, and a search-scoped key if you call Kelp directly.
  3. JS that searches, renders hits and facetCounts, and keeps queryId for analytics.

Direct API vs app proxy

ApproachKey locationNotes
Direct from theme JSSearch-scoped key in section settings (public)Simplest. Same as any public storefront key.
Authenticated app proxyKey on your app serverSame-origin /apps/... path; your app forwards to Kelp. You write or host that app - this page does not name a Kelp Shopify app.

Theme settings are visible in the storefront HTML. Use a key scoped to search and events only. See Security.

Section markup

{% comment %} sections/kelp-search.liquid {% endcomment %}
<div
  id="kelp-search"
  data-search-url="{{ section.settings.search_url | escape }}"
  data-api-key="{{ section.settings.api_key | escape }}"
  data-collection="{{ section.settings.collection | escape | default: 'products' }}"
>
  <form data-kelp-form>
    <input type="search" name="q" placeholder="{{ section.settings.placeholder | escape }}" />
    <button type="submit">Search</button>
  </form>
  <div data-kelp-facets></div>
  <ul data-kelp-hits></ul>
  <p data-kelp-status></p>
</div>

<script type="module" src="{{ 'kelp-search.js' | asset_url }}"></script>

{% schema %}
{
  "name": "Kelp search",
  "settings": [
    { "type": "text", "id": "search_url", "label": "Kelp search URL", "info": "https://YOUR-search.kelp.click" },
    { "type": "text", "id": "api_key", "label": "Search-scoped API key" },
    { "type": "text", "id": "collection", "label": "Collection name", "default": "products" },
    { "type": "text", "id": "placeholder", "label": "Placeholder", "default": "Search" }
  ],
  "presets": [{ "name": "Kelp search" }]
}
{% endschema %}

Add the section to a search template or a custom page in the theme editor. Point product links at {{ routes.root_url }} plus the document handle (or your own PDP URL scheme).

Theme JS - search, facets, semanticWeight

assets/kelp-search.js can be a native module. fetch the Kelp API; the JS SDK is optional (CDN ESM if you want it).

const root = document.getElementById('kelp-search');
if (!root) throw new Error('kelp-search root missing');

const searchUrl = root.dataset.searchUrl.replace(/\/$/, '');
const collection = root.dataset.collection || 'products';
const endpoint = `${searchUrl}/api/v1/collections/${encodeURIComponent(collection)}/search`;

async function search({ q, filters = [], semanticWeight } = {}) {
  const body = {
    q,
    page: 1,
    perPage: 20,
    facets: ['vendor', 'productType'],
    filters,
    fields: ['id', 'objectId', 'title', 'handle', 'minPrice'],
  };
  // Omit semanticWeight for keyword-only. Search only - never on browse.
  if (semanticWeight) body.semanticWeight = semanticWeight;

  const res = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': root.dataset.apiKey,
    },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`Kelp search ${res.status}`);
  return res.json();
}

function render(data) {
  root.dataset.queryId = data.queryId || '';
  root.querySelector('[data-kelp-status]').textContent = `${data.found} results`;
  root.querySelector('[data-kelp-hits]').innerHTML = (data.hits || [])
    .map((hit) => {
      const doc = hit.document || {};
      const href = `/products/${doc.handle || ''}`;
      const id = doc.objectId || doc.id;
      return `<li><a href="${href}" data-object-id="${id}">${doc.title || id}</a></li>`;
    })
    .join('');
}

root.querySelector('[data-kelp-form]').addEventListener('submit', async (e) => {
  e.preventDefault();
  const q = String(new FormData(e.target).get('q') || '');
  render(await search({ q }));
});

Facet chips: read data.facetCounts and, on click, call search again with filters: [{ field: 'vendor', values: ['acme'] }]. Operators and AND/OR rules are in Filtering.

semanticWeight named values: strict | heavy | default | balanced | light | keyword | off. Semantic ranking only when the collection has enableSemanticSearch and you send a weight. Omit = keyword-only. See Semantic search.

queryId analytics

When a shopper clicks a hit, POST product_clicked with the queryId from the last search. Events go to https://{TENANT_ID}-events.kelp.click/analytics/events (or an app proxy you host).

function sessionId() {
  const key = 'kelp_session';
  let id = localStorage.getItem(key);
  if (!id) {
    id = crypto.randomUUID();
    localStorage.setItem(key, id);
  }
  return id;
}

root.addEventListener('click', (e) => {
  const a = e.target.closest('[data-object-id]');
  if (!a) return;
  const sid = sessionId();
  fetch('https://{TENANT_ID}-events.kelp.click/analytics/events', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': root.dataset.apiKey,
    },
    body: JSON.stringify({
      id: crypto.randomUUID(),
      events: [
        {
          kind: 'product_clicked',
          sessionId: sid,
          userId: 'anon_' + sid,
          occurredAt: new Date().toISOString(),
          queryId: root.dataset.queryId,
          objectId: a.dataset.objectId,
          collection: root.dataset.collection,
        },
      ],
    }),
    keepalive: true,
  });
});

Direct API callers must send sessionId, userId, and occurredAt. Shopify customer id, if you have it, can replace the anon_ user. Checkout purchase events usually need a pixel or thank-you hook - the Hydrogen guide covers a custom pixel; Liquid themes can use the same events API from a customer event / pixel you configure. See Events.

Optional: Shopify app proxy

To keep the key off the theme, host an app that exposes an authenticated app proxy path (for example /apps/kelp/search). Theme JS posts to that same-origin path; your app adds X-Api-Key and forwards to https://{TENANT_ID}-search.kelp.click. This repo does not ship that app.

On this page