Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 28 ยท GraphQL

GraphQL Storefront API

Learn the BigCommerce GraphQL Storefront API: endpoint, storefront tokens, product and cart queries, fragments, cursor pagination, impersonation and caching.

The REST APIs are built for servers that manage a store. The GraphQL Storefront API is built for the other side: code that renders a shopping experience. It lets a theme, a headless site or a mobile app ask for exactly the product fields a page needs, in one request, using a credential that is safe to ship to a browser. Stencil themes use it internally, and headless storefronts rely on it almost entirely.

In this lesson you learn where the endpoint lives, how storefront tokens work, what product, cart and customer queries look like, and how fragments, cursors and caching fit in. The real requests are read-only snippets, because they need a live store. The runnable part is a tiny GraphQL-style resolver written in JavaScript over mock data. It is a teaching stand-in, not the real server: it understands just enough syntax (fields, arguments, fragments) to show how a query is walked and why you get back exactly the shape you asked for.

Endpoint and tokens

Each storefront has a GraphQL endpoint on its own domain: the store's address followed by /graphql. With multiple storefronts (channels), use the domain of the channel you are querying, so you get that channel's catalog and pricing. Requests are POST with a JSON body holding the query string and optional variables, and the credential goes in an Authorization: Bearer header (read-only):

HTTP
POST /graphql HTTP/1.1
Host: shop.example.com
Authorization: Bearer <storefront token>
Content-Type: application/json

{"query": "query { site { settings { storeName } } }"}

A storefront token is a limited credential. You create it with the REST API, using an admin credential on your server, and you can restrict it to one channel, give it an expiry and list the origins (CORS) allowed to use it. Because it can only read public storefront data and act on carts, it can live in a front-end bundle. Compare this with the admin token from API Accounts, Tokens and Scopes, which must never leave your server. Create tokens with the shortest lifetime that suits your deployment, and rotate them on a schedule.

flowchart LR
    S["Your server<br/>(admin token)"] -->|"1. create token<br/>(REST)"| BC["BigCommerce"]
    BC -->|"2. storefront token"| S
    S -->|"3. give to storefront code"| F["Browser or<br/>headless app"]
    F -->|"4. POST /graphql<br/>Bearer token"| BC

The admin credential stays on the server; only the limited storefront token reaches the front end.

Product queries

Everything storefront-related hangs off the site field. A product query names the product by an identifier and lists the fields you want (read-only):

GRAPHQL
query ProductPage($id: Int!) {
  site {
    product(entityId: $id) {
      entityId
      name
      sku
      path
      prices {
        price { value currencyCode }
      }
      defaultImage { url(width: 640) altText }
    }
  }
}

Two habits keep queries healthy. Ask only for fields the page shows, because every extra field costs time and complexity budget (see GraphQL Admin API and Choosing Between APIs for how cost is limited). And use variables ($id) instead of pasting values into the query string, so the same query text can be cached and nothing is built by string concatenation.

Fragments

When several queries need the same set of fields, name that set once as a fragment and spread it in. A product card on a category page and a product card in a search result should show identical fields, so they share a fragment (read-only):

GRAPHQL
fragment ProductCard on Product {
  entityId
  name
  path
  prices { price { value currencyCode } }
}

query Category {
  site {
    products(first: 12) {
      edges { node { ...ProductCard } }
    }
  }
}

Changing the card later means editing one fragment. In the stand-in below you will see a fragment spread resolved by copying the fragment's fields into the place where it is used, which is conceptually all a spread does.

Cursor pagination

Lists such as products are connections. You ask for first: N items, optionally after: "<cursor>", and each item is wrapped in an edge with a node (the product) and a cursor (an opaque position marker). A pageInfo object tells you whether more pages exist and which cursor to pass next:

GRAPHQL
query Page($after: String) {
  site {
    products(first: 20, after: $after) {
      pageInfo { hasNextPage endCursor }
      edges { cursor node { entityId name } }
    }
  }
}

Treat cursors as opaque strings. Do not decode them, build them or store them for long: they are only valid as "continue from here" markers. Cursor pagination stays stable when items are added while you page, which page numbers cannot guarantee.

Carts and customers

The Storefront API can read and change carts through mutations such as creating a cart and adding line items, and it returns the cart's totals and a checkout redirect link. Carts and the Checkout API covers that in detail, including how the cart connects to checkout. Customer data is different: it is private. A normal storefront token only sees what an anonymous visitor sees. For logged-in data in a headless setup, your server asks BigCommerce for a customer-impersonation token, which is a stronger, server-held token that can act on behalf of a given customer, and then passes that customer's identity along with its requests. Keep that token on the server, never in the browser, and scope it narrowly. The details of the request headers and creation call are in the official reference; check them there rather than guessing.

Caching

Storefront queries for catalog data are good candidates for caching, because many shoppers ask the same question. Two rules help. First, cache anonymous responses only: anything fetched with a customer-specific token must not be shared. Second, key the cache on the query text plus the variables plus the channel, since each of those changes the answer. Headless Storefronts builds a full fetch layer with revalidation on top of this idea.

A tiny resolver stand-in

This stand-in runs a query through a hand-written parser and resolver. The data is a small mock catalog. What is real: the shape of the query and of the answer (site, edges, node, pageInfo) mirrors the real API. What is stand-in: the parser handles only the syntax this lesson uses, there is no schema, validation, authentication or variables, and the cursor format is our own.

JS Run a query against mock data

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

No output.

The answer contains entityId, name and prices from the fragment plus sku from the query, and nothing else, even though the mock record had more. The second lookup, for a product that does not exist, resolves to null rather than failing, which matches how a missing product behaves. The alias missing: renames the key in the answer, so the same field can be requested twice under different names.

Walking all pages

Now the cursor loop. A client keeps calling with after set to the previous endCursor until hasNextPage is false. The second stand-in reuses the engine idea in a smaller form, adds a cache keyed by query text, and counts how many real "server" calls were made.

JS Follow cursors and cache the results

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

No output.

Seven items with a page size of three need three calls. The second walk is served from the cache, so the call count does not change. In production, the cache needs an expiry and the page size should be a deliberate choice, not an accident.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a storefront token be used in browser code while an admin token cannot?

    Storefront tokens are limited by design. An admin token can modify the store, so it must stay on your server.
  2. 2. What does a fragment give you?

    A fragment avoids repeating the same field list and keeps one place to edit.
  3. 3. How should you treat a pagination cursor?

    Cursors are opaque. Use pageInfo.endCursor as the next after value and stop when hasNextPage is false.
  4. 4. Which responses may be shared in a cache between shoppers?

    Cache anonymous data only. Customer-specific data must never be served to another visitor.

Summary

  • The Storefront GraphQL API lives at /graphql on the storefront's domain and uses a limited bearer storefront token that is created with an admin credential.
  • Queries start at site; ask only for the fields a page shows and pass values as variables.
  • Fragments name reusable field sets; connections use first, after, edges, node and pageInfo.
  • Customer-specific access needs an impersonation token that stays on the server.
  • Cache anonymous responses, keyed by query, variables and channel.

Next: GraphQL Admin API and Choosing Between APIs