Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 61 ยท Apps, Integrations and Extensibility

Storefront API and Fetching Data from a Theme

Learn when a Shopify theme should call the Storefront API instead of Liquid or the Ajax APIs: tokens, GraphQL queries, rate limits, caching and safe error handling.

Most data on a Shopify storefront reaches the page through Liquid: the server renders product.title into HTML before the browser sees anything. Sometimes that is not enough. You may want a "Recently viewed" strip that shows products the shopper opened earlier, a live "Complete the look" list built from handles in a metafield, or a store locator filtered in the browser. For those cases your theme JavaScript needs to ask Shopify for data after the page has loaded.

Shopify gives themes several ways to do that, and the Storefront API is the most flexible. It is a public GraphQL API for reading products, collections, carts, and more, and it is the same API that headless storefronts use. This lesson explains how a theme can use it, what the token means, how to keep requests cheap, and when you should use a simpler tool instead. It targets Shopify's quarterly API versions (the examples use 2026-07; always check the current stable version before you copy a URL).

Network calls cannot run on this site, so the real fetch code below is read-only. The runnable examples are stand-ins: a tiny fake GraphQL server written in JavaScript that returns only the fields you ask for, and a client with caching and retries. They show the ideas honestly, but they are not Shopify.

Choose the lightest tool first

Before you reach for GraphQL, check whether something simpler already does the job. Shopify's storefront has several data paths, and each one fits a different need.

Need Best tool Why
Show data that is known at page load Liquid No extra request, cached with the page
Add, change or read the cart Ajax Cart API Built for it, no token needed
Re-render a section after a change Section Rendering API Returns ready-made HTML from your own Liquid
Search suggestions Predictive search endpoint Same-origin, small JSON
Arbitrary product, collection or metafield data in JavaScript Storefront API You choose the exact fields

The pattern is simple. If the answer can be HTML you already know how to write, ask for a section and let Liquid do the work. If JavaScript needs structured data you cannot get otherwise (for example the price and image of ten product handles that are not on this page), the Storefront API is the right tool.

flowchart TD
    A["Theme JS needs data"] --> B{"Is it cart data?"}
    B -- yes --> C["Ajax Cart API"]
    B -- no --> D{"Can a section render it as HTML?"}
    D -- yes --> E["Section Rendering API"]
    D -- no --> F{"Is it search suggestions?"}
    F -- yes --> G["Predictive search endpoint"]
    F -- no --> H["Storefront API (GraphQL)"]

Walk down the questions and stop at the first tool that fits.

The shape of a request

The Storefront API has one endpoint per store and API version. Every request is an HTTP POST with a JSON body that holds a query string and optional variables.

JavaScript
// Read-only: a real request from theme JavaScript (API version 2026-07).
const endpoint = 'https://your-store.myshopify.com/api/2026-07/graphql.json';

const query = `
  query Featured($handle: String!) {
    product(handle: $handle) {
      title
      availableForSale
      priceRange {
        minVariantPrice { amount currencyCode }
      }
      featuredImage { url altText }
    }
  }
`;

const response = await fetch(endpoint, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Shopify-Storefront-Access-Token': 'PUBLIC_TOKEN_HERE',
  },
  body: JSON.stringify({ query, variables: { handle: 'trail-jacket' } }),
});

const { data, errors } = await response.json();

A few things are worth noticing.

  • You list fields. Unlike a REST endpoint, GraphQL returns only the fields in your query. A card that needs a title, a price and an image should ask for exactly those three, and nothing else travels over the network.
  • Variables are separate. Pass user-influenced values (handles, search text) in variables, never by gluing strings into the query. This prevents a visitor from changing what your query means.
  • HTTP 200 does not mean success. GraphQL reports problems in an errors array, often alongside a 200 status. Always check errors and handle a null result, for example when a handle does not exist.
  • Prices are strings. amount is a decimal string such as "129.0", and currencyCode tells you the currency. Format it with Intl.NumberFormat rather than adding currency symbols by hand.

You can also add the @inContext(country: ..., language: ...) directive so the response uses the shopper's market: prices in the right currency and translated titles. In a theme you can read localization.country.iso_code and localization.language.iso_code from Liquid and hand them to your script.

Tokens: public by design

The Storefront API needs an access token. A theme runs in the shopper's browser, so whatever token it uses is visible to anyone who opens the developer tools. That is acceptable, because a public Storefront token is designed for exactly this: it can only read what a storefront visitor could already see, and it can create carts, but it cannot read orders, customers or settings.

Shopify also issues a private (delivery) token, sent in a different header (Shopify-Storefront-Private-Token) and meant for server-side calls only. Never put a private token in a theme, in a data- attribute, or in any file under assets.

Where does the public token come from? You create it by installing an app or sales channel that grants Storefront API access, or from a custom app in the store admin, and then choose the scopes it may read (products, collections, metaobjects, and so on). Scopes matter: if a field returns null or an access error, the token may lack the scope.

Treat the token as configuration, not as a secret. A tidy approach is to expose it as a theme setting so the merchant can rotate it without editing code, and to read it in Liquid:

LIQUID
<script type="application/json" id="StorefrontConfig">
  {
    "apiVersion": "2026-07",
    "token": {{ settings.storefront_token | json }},
    "country": {{ localization.country.iso_code | json }}
  }
</script>

A public token is not a license to expose private data. Do not give it scopes you do not need, and never reuse one token for both your theme and an admin-level integration. If a token leaks that can do more than read the catalog, rotate it. See Security in Themes.

A stand-in GraphQL server

To make GraphQL tangible, run the example below. It is a very small fake of the Storefront API: it parses a query's selection set and returns only the requested fields, and it reports an error for a field that does not exist. A real server does far more (types, validation, connections, cursors), but the core idea is the same.

JS A fake GraphQL server returns only what you ask for

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

No output.

Try changing $n to 3, or add handle to the selection. Notice the edges / node nesting: Storefront API lists are connections, and you pick the fields inside node. Real connections also give you pageInfo and cursor values to page through large lists.

Limits, cost and good manners

The Storefront API is built to handle storefront-scale traffic, and ordinary shopper requests from browsers are not throttled the way Admin API calls are. That does not make it free:

  • Query size and depth are limited. Very large or deeply nested queries are rejected. Ask for what you display, and request lists with first: N using a small N.
  • Throttling still exists. Shopify protects stores from abusive traffic, so a script that loops over hundreds of products can receive a 429 Too Many Requests response or a bot-protection challenge. Treat 429 as a signal to back off, and honor a Retry-After header if one is present.
  • Each request costs the shopper time. A request on a phone connection takes a noticeable fraction of a second, and many of them hurt your Core Web Vitals.

Good manners therefore mean: one query for many things instead of many queries for one, small page sizes, no calls from loops, and caching. GraphQL uses POST, and browsers and CDNs do not cache POST responses by default. You have to cache in your own code, for example in a Map for the page's lifetime or in sessionStorage with a short expiry.

sequenceDiagram
    participant UI as Theme JS
    participant C as Cache (Map)
    participant S as Storefront API
    UI->>C: lookup(query + variables)
    alt fresh hit
        C-->>UI: cached data
    else miss or expired
        UI->>S: POST /api/2026-07/graphql.json
        S-->>UI: 200 data or 429 Retry-After
        UI->>C: store with timestamp
        C-->>UI: data
    end

A tiny cache in front of the API removes most repeated requests; a retry loop handles the occasional 429.

The next stand-in builds that client. To keep the output the same on every run, it uses a pretend clock and a fake network that answers 429 twice before succeeding. In a real theme you would use Date.now() and fetch.

JS Caching and polite retries

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

No output.

The retry waits grow with each attempt (a simple backoff), the second call never touches the network, and the third call goes out again because the cached copy is older than the 60 second lifetime. That is the whole pattern: check the cache, call, back off on 429, store the result.

Failing gracefully

A theme must still work when the API does not. Wrap calls so that a failure hides the enhancement instead of breaking the page:

JavaScript
// Read-only: defensive use of the result.
async function loadRecommended(handles) {
  try {
    const { data, errors } = await storefront(buildQuery(handles));
    if (errors?.length || !data) return [];
    return handles.map((_, i) => data['p' + i]).filter(Boolean);
  } catch {
    return []; // the section simply renders nothing
  }
}

Design the empty state first: the section should look fine with no data, because the first request, the offline shopper and the blocked request all lead there. When the data is only a progressive enhancement (a "Recently viewed" strip), the markup that does not depend on it should be in the page already, as Liquid.

Finally, keep ownership clear. If the information is in your Liquid context, use Liquid. If a shopper action changes the cart, use the Ajax API. If you find yourself building a whole client-side app out of Storefront API calls, consider whether the project should be a headless storefront (for example with Hydrogen) rather than a theme.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A theme script needs the title, price and image of eight product handles that are not on the current page. Which tool fits best?

    The Storefront API returns structured data for fields you choose and can fetch several products in one request. The Ajax Cart API is only for carts, and the Admin API must never be called from a theme.
  2. 2. Where may a Storefront API token be used in theme JavaScript?

    A public token can only read what a visitor could already see, so it is safe to ship in a theme. Private and Admin tokens must stay on a server.
  3. 3. A GraphQL request returns HTTP 200 with a JSON body that has an errors array. What should the theme do?

    GraphQL commonly reports problems inside a 200 response. Always inspect errors and handle missing data.
  4. 4. Why does a theme usually need its own cache for Storefront API calls?

    POST responses are not cached automatically, so a small in-memory or sessionStorage cache with an expiry removes repeated requests.

Summary

  • Use Liquid for data known at page load, the Ajax Cart API for carts, the Section Rendering API for HTML, and the Storefront API for structured data that JavaScript needs on demand.
  • A request is a POST of { query, variables } to /api/<version>/graphql.json; pin the API version and update it on a schedule.
  • Public Storefront tokens are meant to be visible; private and Admin tokens never belong in a theme.
  • Ask only for the fields you display, pass user-influenced values as variables, and check errors even on a 200 response.
  • Cache results yourself, back off on 429, and design an empty state for failures.

Next: Webhooks and Orders for Theme Developers