Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 28 ยท Projects

Project: A Headless Product Page

Build a headless BigCommerce product page: fetch a product with the GraphQL Storefront API, cache it, render safe HTML and add to cart, with a runnable Node stand-in.

In this project you build the heart of a headless storefront: one product page that gets its data from the GraphQL Storefront API, renders HTML you control, and lets a visitor add the product to a cart. Everything around it (checkout, payment, order management) stays on BigCommerce, which is exactly why headless projects often start with the catalog pages and hand the shopper to the hosted checkout.

The real calls need a store, a channel and a storefront token, so the real queries and framework code are shown read-only. The runnable parts are stand-ins written in plain Node.js: a fake GraphQL endpoint that understands a small subset of query syntax, a data layer with a cache, an HTML renderer and a cart action. The stand-ins are honest about their limits: the real GraphQL server validates far more, and the real cart lives on BigCommerce, not in a Map. Background is in Headless Storefronts and GraphQL Storefront API.

What you will build

The page has three layers. Keep them separate, because that is what makes a headless site testable and fast.

  1. Data layer. A function getProduct(id) that sends one GraphQL query, checks for errors, caches the result for a short time and returns plain data.
  2. View layer. A function that turns that data into HTML. It escapes every value, formats money with the currency from the API and disables the button when the product is out of stock.
  3. Action layer. A server-side handler for "add to cart" that validates the form, creates or updates a cart and redirects the shopper.
flowchart LR
    B["Browser"] --> S["Your server<br/>(Next.js or Node)"]
    S --> C["Cache"]
    C -->|miss| G["BigCommerce<br/>GraphQL Storefront API"]
    S -->|"add to cart"| G
    G -->|"redirect URL"| S
    S -->|"302"| H["Hosted checkout"]

Reads go through a cache; the cart action talks to the API and then sends the shopper to checkout.

The real query (read-only)

A storefront request goes to your store's GraphQL endpoint with a storefront token in the Authorization: Bearer header. The token is created for a channel with the REST API (see API Accounts, Tokens and Scopes) and can be limited to the origins you list. The query asks only for the fields the page needs:

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

Asking for fewer fields is the main performance lever in GraphQL: the server only does the work you request, and the payload stays small. Because the query text and variables are the same for every visitor, the response for a public product can be cached. Never cache a response that was fetched with a customer-specific token; see Headless Storefronts for the caching rules.

In a Next.js app you would call this from a server component or route handler, so the token never reaches the browser. This skeleton is read-only:

JavaScript
// app/products/[id]/page.js (read-only skeleton)
export const revalidate = 60; // regenerate at most once a minute

export default async function ProductPage({ params }) {
  const { id } = await params;
  const res = await fetch(process.env.BC_GRAPHQL_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.BC_STOREFRONT_TOKEN}`,
    },
    body: JSON.stringify({ query: PRODUCT_QUERY, variables: { id: Number(id) } }),
  });
  const { data, errors } = await res.json();
  if (errors) throw new Error(errors[0].message);
  return <Product product={data.site.product} />;
}

Notice the two checks that beginners skip: a GraphQL response can have HTTP status 200 and still contain errors, and data.site.product can be null when the product does not exist or is not visible on this channel.

Step 1: a data layer you can test

The stand-in below does what the real data layer does. fakeGraphQL understands a query shaped like the one above: it reads the selection set, rejects unknown fields with an error (like a real server) and returns only the fields you asked for. createProductLoader wraps any fetcher with a time-based cache and counts upstream calls, using an injected clock so the demo is deterministic.

Node.js Data layer with a fake GraphQL endpoint and a cache

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first call goes to the network, the second (30 seconds later) is served from the cache, and the third (70 seconds after the first) misses again because the entry expired. The request for a missing product returns null instead of throwing, and a query for a field that does not exist produces an errors array while still being an ordinary response object. That mirrors real GraphQL, where a failed request is not an HTTP error.

Step 2: render the page safely

The view layer takes the product and returns HTML. The rules are short and worth memorizing:

  • Escape every string you insert into HTML, including names and descriptions. Merchants can type angle brackets into a product name, and a headless site that skips escaping becomes a cross-site scripting hole. Frameworks like React escape for you; plain string templates do not.
  • Format money with the currency code from the API and a locale-aware formatter. Do not hard-code a dollar sign. The reasoning is the same as in Currencies and Localization.
  • Only emit image URLs that start with https://.
  • Show a sale price only when one exists, and show the original price struck through next to it.
  • Disable the button, and say why, when the item is out of stock.
Node.js Render the product page as escaped HTML

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The name Canvas <b>Tote</b> & Co comes out as harmless text, the sale price replaces the regular one with the old price struck through, and the mug page has no <img> at all because its URL is not https://. The mug's euro price is formatted with a euro sign because the formatter received the currency code. The button is disabled for the out-of-stock mug.

Step 3: add to cart and hand off to checkout

Never trust the browser. The form posts to your server, which validates the input, talks to BigCommerce with its own credentials and answers with a redirect. In the real GraphQL API, a cart is created with a mutation, and later items are added to the same cart by its entityId; the redirect URLs for the cart page and hosted checkout come from a second mutation. These mutations are read-only here:

GRAPHQL
mutation CreateCart($productId: Int!, $quantity: Int!) {
  cart {
    createCart(input: { lineItems: [{ productEntityId: $productId, quantity: $quantity }] }) {
      cart { entityId }
    }
  }
}

Store the returned cart ID in an HttpOnly, Secure, SameSite=Lax cookie so the next click adds to the same cart. For the checkout hand-off, ask for the cart's redirect URLs and send the shopper there with a 302. The idea behind the cart is covered in Cart Design and the REST equivalents in Carts and the Checkout API.

The stand-in keeps carts in a Map and checks the same things your real action should: integer product ID, quantity between 1 and 10, product exists, product in stock.

Node.js The add-to-cart action with validation and a redirect

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first add creates cart-1, the second add reuses it because the cookie points to a cart that exists, and the cart ends up with three totes on one line. Bad input and unavailable products are rejected before any cart is touched. In production, remember that stock can change between page render and click, so the platform still checks again, and your action should handle an error response from the real API in the same way.

Making it production-ready

A product page is the first slice; here is what a real project adds, in the order that usually pays off:

  • Caching and revalidation. Cache public product pages for a short time and revalidate on a webhook such as store/product/updated so changes appear quickly. Never share one cache between guests and logged-in customers.
  • SEO. Use the product's path for your canonical URL, render a title and meta description on the server and add structured data. See Ecommerce SEO.
  • Variants and options. Extend the query with option values, and keep the selected variant in the URL so the page can be shared.
  • Errors. Show a friendly page when the product is null, and log (without secrets) when the API returns errors.
  • Tests. The data and action layers are plain functions, so test them against a mock like the one above; see Testing Apps and Themes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the storefront token be used in server code in this project?

    Server-side fetching gives you caching and control over the output. A storefront token is limited in power, but there is still no reason to ship more of your integration to the browser than necessary.
  2. 2. A GraphQL request returns HTTP 200. What must the data layer still check?

    GraphQL reports failures inside the body. A missing or hidden product is also returned as null rather than as a 404.
  3. 3. Why does the page renderer escape the product name?

    Product names and descriptions are data, not markup. Escape all of it unless you deliberately render sanitized rich text.
  4. 4. What should the add-to-cart handler do when the form says quantity 99 and the limit is 10?

    Validate on the server, because anything in a form can be edited. Reject invalid input early with a clear status.
  5. 5. Which cache is safe to share between all visitors?

    Public catalog data is the same for everyone, so it can be shared. Customer-specific, cart and checkout data must not be.

Summary

  • A headless product page has a data layer, a view layer and an action layer; keep them separate and testable.
  • Ask GraphQL only for the fields you render, and always check both errors and a null product.
  • Cache public product data briefly, revalidate on webhooks and never share customer-specific responses.
  • Escape every inserted string, format money with the API's currency code and allow only https:// image URLs.
  • Validate the cart form on the server, keep the cart ID in an HttpOnly cookie and hand the shopper to hosted checkout with a redirect.
  • The stand-ins here imitate the shape of the real API; the real server does far more validation and holds the real cart.

Next: Practice Exercises