Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 61 ยท Products, Collections and Variants

Search and Predictive Search

Build Shopify theme search: the search template and search.results, result types, the predictive search API with fetch, debouncing and no-results states.

When a store has more than a few dozen products, many shoppers skip the menu and type. Shopify gives themes two search tools. The search page (/search?q=mug) is a full, server-rendered results page. Predictive search returns a small set of matches while the shopper is still typing, so the dropdown under the search box can show products, collections, pages and suggested queries.

You build both, but you do not build the search engine: Shopify ranks results, handles typos and plurals to a degree, and indexes products, collections, pages and articles. Your job is the template, the request logic and the many small states around it (empty query, loading, no results, slow network). This lesson covers each of them, with runnable stand-ins for the JavaScript parts. It builds on Collection Pages for pagination and filters, which search results reuse.

Search objects and the /search endpoints exist only on a real Shopify store, so the theme code below is read-only and written for current Online Store 2.0 themes. The live examples use a fake in-memory search index and a fake fetch, which lets you test debouncing and rendering without a store. Predictive search supports a limited set of languages and has its own result limits, so check Shopify's current documentation for your target markets.

The search page

A request to /search?q=ceramic+mug renders templates/search.json (or search.liquid), which normally contains a section named something like main-search. In Liquid, the search object tells you what happened:

Property Meaning
search.performed true once a search ran (a query was given)
search.terms the text the shopper typed
search.results the matching items, one page worth inside paginate
search.results_count total number of matches
search.types which resource types are searched (product, article, page)
search.filters filter definitions, as on collection pages

A reasonable results section:

LIQUID
{% paginate search.results by 24 %}
  <form action="{{ routes.search_url }}" method="get" role="search">
    <label for="q">Search</label>
    <input id="q" type="search" name="q" value="{{ search.terms | escape }}">
    <button>Search</button>
  </form>

  {%- if search.performed -%}
    <h1>
      {{ 'search.results_count' | t: count: search.results_count, terms: search.terms }}
    </h1>

    {%- for item in search.results -%}
      {%- case item.object_type -%}
        {%- when 'product' -%}
          {% render 'product-card', product: item %}
        {%- when 'article' -%}
          <a href="{{ item.url }}">{{ item.title }}</a>
        {%- when 'page' -%}
          <a href="{{ item.url }}">{{ item.title }}</a>
      {%- endcase -%}
    {%- else -%}
      <p>No results for "{{ search.terms | escape }}". Try a shorter word or check the spelling.</p>
    {%- endfor -%}

    {{ paginate | default_pagination }}
  {%- endif -%}
{% endpaginate %}

Several details are easy to miss:

  • Always escape search.terms. It is text typed by anyone, including attackers, and you are printing it into HTML. The escape filter turns <script> into harmless text. More in Security in Themes.
  • Results are mixed. Each item has object_type, which is product, article or page. Branch on it, because each type has different properties.
  • The empty state lives in the for loop's else. Handle "searched but found nothing" separately from "no search yet" (search.performed is false).
  • Pagination works as on collections, with ?page=.

Limiting what is searched

By default a search covers several types. Add a type parameter to the form to restrict it, for example type=product, or type=product,article. A hidden input in the form is the usual way:

LIQUID
<input type="hidden" name="type" value="product">
<input type="hidden" name="options[prefix]" value="last">

The second input asks Shopify to match partial words for the last word typed, so "cer" finds "ceramic". Without it, only whole-word matches count. Other search options exist (for example options[unavailable_products] to control where sold-out products appear); look them up in the current reference before relying on one.

Predictive search has its own endpoint:

Text
GET /search/suggest.json?q=mug&resources[type]=product,collection,page,article,query&resources[limit]=4

The response is JSON. The matches are grouped under resources.results, with arrays such as products, collections, pages, articles and queries (suggested search phrases). A product entry includes fields like title, url, price, available and an image. The exact field list can grow over time, so read only what you use and treat everything else as optional.

Two request rules matter:

  1. Build the URL from routes.predictive_search_url rather than hard-coding /search/suggest, because stores with language or market sub-paths (/fr/search/suggest) need the locale prefix. Output it in Liquid and read it from JavaScript:
LIQUID
<predictive-search data-url="{{ routes.predictive_search_url }}">
  <input type="search" name="q" autocomplete="off" aria-autocomplete="list" aria-controls="suggestions">
  <div id="suggestions" role="listbox"></div>
  <div aria-live="polite" class="visually-hidden" data-status></div>
</predictive-search>
  1. Do not fire a request on every keystroke. Typing "ceramic mug" would send twelve requests, eleven of which are already out of date. Wait until the shopper pauses.

Debounce and stale responses

A debounce delays the request until the user has stopped typing for a short time (150 to 300 ms is typical). Every new keystroke cancels the pending timer and starts a new one.

Debouncing does not fully solve ordering. Network responses can arrive out of order: the answer for "mu" might come back after the answer for "mug" and overwrite it. Cancel the earlier request with an AbortController before sending the next one, and ignore AbortError:

JavaScript
let controller;

async function suggest(query, url) {
  controller?.abort();
  controller = new AbortController();
  const endpoint = `${url}?q=${encodeURIComponent(query)}&resources[limit]=4`;
  try {
    const response = await fetch(endpoint, { signal: controller.signal });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (error) {
    if (error.name === 'AbortError') return null; // a newer request replaced this one
    throw error;
  }
}

Note encodeURIComponent: the query can contain &, # or spaces that would otherwise break the URL.

sequenceDiagram
  participant S as Shopper
  participant T as Theme script
  participant P as /search/suggest.json
  S->>T: types "m", "mu", "mug"
  Note over T: each keystroke restarts a 200 ms timer
  T->>T: timer fires (shopper paused)
  T->>P: GET q=mug
  P-->>T: JSON results
  T->>S: render products, aria-live count

Only the final query reaches the server. A new keystroke would abort an in-flight request first.

Rendering the results safely

When you turn JSON into HTML, treat every string as untrusted. Product titles are written by the merchant, but queries and some fields can contain user-controlled text. Two safe approaches:

  • build DOM nodes and set textContent, never innerHTML with unescaped values;
  • or ask the server to render the markup (the predictive search endpoint can return HTML for a section when you pass section_id, which keeps the Liquid in one place). See the Section Rendering API.

If you do build strings for innerHTML, escape & < > " ' first, as the stand-in below does.

States to design

State What to show
empty input close the dropdown, or show popular searches
loading a small indicator, aria-busy="true"
results grouped lists, with the first group highlighted for keyboard use
no results "No results for X" plus a link to the full search page
error a quiet message; the form still submits to /search as a fallback

Keep the plain <form action="/search"> working. If your script fails, pressing Enter must still take the shopper to the full results page.

Stand-in: debounce and cancel against a fake server

This stand-in simulates the typing and the network. The fake fetch waits 40 ms and respects an AbortSignal. The input handler is debounced. Output shows how many requests actually went out compared with how many keystrokes there were.

JS Stand-in: debounced predictive search

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The three fast keystrokes produce a single request for mug. The abort path (cancelled) only triggers when a new search starts while the previous one is still waiting; try raising the debounce wait to 0 and lowering the sleep times to see it.

Stand-in: rendering results and the no-results state

The second stand-in turns a response into markup. It escapes every value, groups products and query suggestions, and builds the three states: results, no results and an error. Because it only builds strings, you can reuse the same function in a real theme.

JS Stand-in: render grouped results safely

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second call shows why escaping matters: the hostile query comes out as inert text in the "no results" message. Never put the raw query into innerHTML.

Search quality and merchant control

A theme developer cannot tune ranking, but you can help merchants. Product titles, types, tags, vendors and descriptions feed the index, so tidy catalog data gives better results. The Shopify Search & Discovery app lets merchants add synonyms, boost products and review what shoppers searched for. Show a link to the search page in the header on every template, and keep a visible, labelled search field or a button with an accessible name ("Search").

For catalog-wide meaning of search and filters beyond Shopify, see Search and Filters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must you apply the escape filter to search.terms when printing it into the page?

    search.terms is user input. Escaping turns markup into harmless text and prevents cross-site scripting.
  2. 2. What does debouncing the predictive search input achieve?

    Each keystroke restarts a short timer, so only the last query within the pause window is sent.
  3. 3. Two predictive requests are in flight and the older one returns last. How do you stop it overwriting newer results?

    Aborting the older fetch (and ignoring its AbortError) guarantees only the latest query updates the dropdown.
  4. 4. Where should the predictive search URL come from in a theme?

    Stores with locale sub-paths need the prefixed URL. The routes object always provides the correct one.
  5. 5. What should happen if the predictive search script fails to load?

    A plain form with action=/search is the baseline. JavaScript only enhances it.

Summary

  • The search object powers the full results page: performed, terms, results, results_count; branch on object_type and always escape search.terms.
  • Restrict result types and enable partial-word matching with form inputs such as type and options[prefix].
  • Predictive search is a JSON endpoint under routes.predictive_search_url; read only the fields you need.
  • Debounce input and abort stale requests so the newest query wins.
  • Render safely, design loading, empty and error states, and keep the plain search form working without JavaScript.

Next, enrich products and pages with custom data in Metafields in Themes.