Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 28 ยท Practice and Review

Practice Exercises

Ten BigCommerce development exercises with hints and runnable Node solutions: scopes, pagination, batches, install callbacks, webhooks, templates, theme settings, carts and caching.

Reading about a platform is easy; building with it is what makes the ideas stick. This lesson gives you ten exercises that cover the whole track: APIs, apps, themes and headless storefronts. Each exercise has a task, a hint and a worked solution. Do the task in your own editor first, even if you only get halfway. Ten minutes of struggling teaches more than reading the answer.

BigCommerce itself cannot run on this site, so every solution is a runnable stand-in in plain Node.js: a fake API, a fake token endpoint, a small template engine. They follow the shape of the real thing but are simplified models, and each one says what is real and what is imitation. Real platform calls (REST endpoints, GraphQL, Stencil files) appear only as read-only snippets.

flowchart LR
    A["APIs<br/>1-2"] --> B["Sync<br/>3-4"]
    B --> C["Apps<br/>5-6"]
    C --> D["Themes<br/>7-8"]
    D --> E["Commerce<br/>9-10"]

Five pairs of exercises: API basics, safe syncing, app plumbing, themes, cart and cache.

Exercises 1 and 2: API basics

Exercise 1: choose the smallest set of scopes. A script must read products, update product prices, read orders and read customers. List the scopes the API account needs, using the least privilege rule from API Accounts, Tokens and Scopes: modify access only for areas that are written, read-only everywhere else.

Hint: group the needed calls by area, then decide per area whether any call writes.

Exercise 2: fetch every page. A list endpoint returns at most 5 rows per page, whatever limit you ask for. Write a client that returns all 12 rows. Show also why the "stop when I get fewer rows than I asked for" shortcut fails. This is the lesson of The Catalog API (V3).

Hint: the response tells you total_pages; trust it.

Solutions. The scope names follow the real naming style (store_v2_products, store_v2_products_read_only), but the mapping from calls to areas is our own simplification. The server in exercise 2 is a fake that mimics the V3 pagination envelope.

Node.js Solutions 1 and 2: scopes and pagination

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 answer is store_v2_customers_read_only, store_v2_orders_read_only, store_v2_products: only products need modify access. The naive loop sees 5 rows, assumes it reached the end and returns early, so it silently drops 7 of the 12 rows.

Exercises 3 and 4: safe syncing

Exercise 3: batch with partial failure. Send 10 product updates in batches of 3 to an endpoint that reports success or failure per item. Item 7 is invalid for good. Items 4 and 8 fail with a temporary error on their first attempt. Retry only the temporary failures, up to three rounds, and report what succeeded and what did not. Never resend items that already succeeded.

Hint: a batch response has one result per item. Use the retryable flag to decide.

Exercise 4: plan an idempotent sync. A supplier feed lists SKUs with names and prices. Compare it with the catalog and produce a plan of create, update and unchanged actions. Reject duplicate SKUs in the feed. Do not delete catalog items that are missing from the feed. Apply the plan, then plan again: the second plan must contain no changes. The reasoning behind this is Idempotency.

Hint: key everything by SKU, and compare the fields you manage, not whole objects.

Node.js Solutions 3 and 4: retrying a batch and planning a sync

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.

In exercise 3, items 1 to 10 are sent in round one; items 4 and 8 come back as temporary failures and are retried alone in round two, where they succeed, while item 7 is reported once and never resent. In exercise 4, the first plan creates the apron, updates the tote's price and leaves the mug alone; after applying it, the second plan has nothing left to do. That "plan twice, change nothing" property is how you test that a sync job is safe to re-run. Real code would also batch the apply step (see The Catalog API (V3)).

Exercises 5 and 6: app plumbing

Exercise 5: handle the install callback. When a merchant installs your single-click app, the platform calls your auth callback with a one-time code, the granted scope and a context such as stores/abc123. Write a handler that rejects a callback with missing parameters, a malformed context, or a scope that lacks something you require. Then exchange the code for a token, store the token under the store hash, and show that using the same code a second time fails. The full flow is in App Types and the OAuth Flow.

Hint: an authorization code can be exchanged exactly once. Treat the exchange as a function that can say no.

Exercise 6: a webhook receiver. Webhooks are registered with a destination and optional custom headers. Use a secret header that you set at registration. Write a receiver that rejects a wrong or missing secret with 401 using a constant-time comparison, rejects a body that is not valid JSON with 400, and processes each event only once even if the platform delivers it twice. See Webhooks and Webhooks and Signatures.

Hint: the payload includes a hash field. The stand-in uses it as the dedupe key, because a retry carries the same payload. Webhook payloads are small notifications (scope and an id), so a real handler fetches the resource afterwards.

Node.js Solutions 5 and 6: install callback and webhook receiver

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 install handler treats the callback as untrusted input: it checks the shape first, then the scopes, and only then spends the one-time code. The replay returns code rejected because the fake endpoint, like the real one, will not honor a code twice. In exercise 6 the order event is processed once; the second delivery is acknowledged with 200 but ignored, which tells the sender to stop retrying without doing the work twice.

Exercises 7 and 8: themes

Exercise 7: a tiny template engine. Theme templates use Handlebars. Build a renderer with {{name}} (HTML-escaped), {{{html}}} (raw), {{#each items}}...{{/each}} and {{#if flag}}...{{/if}}. Make sure a product name containing {{secret}} or <script> is output as plain text and is not interpreted. Real Stencil uses the Handlebars engine with extra helpers (see Handlebars Templates, Helpers and Page Context); this is only a model.

Hint: render in a single pass over the template with one regular expression, so output is never scanned again.

Exercise 8: theme settings to CSS variables. A theme's config.json holds settings such as colors and sizes that merchants change in the theme editor. Turn them into a :root { --name: value; } block. Accept only values of the right type (a hex color, a size in px or rem) and fall back to the default for anything else, so a malicious or mistyped setting cannot break out of the CSS. See Theme Settings, SCSS and JavaScript.

Hint: validate by pattern per setting type, not by trying to remove "bad" characters.

Node.js Solutions 7 and 8: a renderer and a settings generator

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.

In exercise 7, the title and the hostile product name come out escaped, the {{secret}} inside the product name stays literal text because the output is never rescanned, and only footer (a deliberately raw triple-brace value) keeps its tags. Only trust triple braces for markup you control; the same rule applies in real Handlebars. In exercise 8, the valid green color and rem size pass, while the injected red;} body{display:none and the oversized radius fall back to defaults. In a real theme you would generate this in SCSS or inject settings into the page with a helper, but the idea of validating by pattern is identical.

Exercises 9 and 10: cart and cache

Exercise 9: cart totals in integer cents. Compute subtotal, discount, shipping and total for a cart. Support a percentage coupon and a fixed-amount coupon, never let the discount exceed the subtotal, and give free shipping at or above a threshold (checked after the discount). Keep all money as integer cents, as in Money as Integers. The real platform calculates totals for you (see Carts and the Checkout API); doing it once yourself shows why rounding rules matter.

Hint: round a percentage discount once, to a whole cent, and clamp at the subtotal.

Exercise 10: stale-while-revalidate cache. For a headless storefront, build a cache that serves fresh data for 60 seconds, serves stale data for up to 120 more seconds while refreshing in the background, and fetches normally after that. Two simultaneous requests for a stale key must cause only one refresh. The caching strategy is discussed in Headless Storefronts.

Hint: keep a map of in-flight refreshes and a clock you can inject for testing.

Node.js Solutions 9 and 10: totals and a stale-while-revalidate 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.

For the cart, the 10% coupon is rounded once to a whole cent (485 cents on a 4,850-cent subtotal), the fixed coupon subtracts exactly 20.00, and the huge coupon is clamped to the subtotal, so the total never goes negative and shipping is waived on an empty payable amount. In the cache run, the first request is a miss, the one at 30 seconds is fresh, and the two at 90 seconds both get the stale v1 while exactly one background refresh runs. The next request sees v2 as fresh, and the one at 400 seconds is expired, so it waits for a new fetch: three upstream fetches for six requests.

How to keep practicing

If you finished these, try changing them. Add a third coupon type, make exercise 3 back off between rounds, let the renderer support {{else}}, or make the webhook receiver reject events whose scope you did not subscribe to. Then build one of the projects, starting with Project: A Headless Product Page, and read your code as if a teammate wrote it: where are the secrets, what happens on a retry, and what happens when the API says no?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A reporting script reads orders and customers and never writes. Which scopes fit best?

    Least privilege means the smallest access that works. A leaked read-only token cannot change data.
  2. 2. In a batch of 10 updates, 2 items fail with a temporary error. What should the client resend?

    Per-item results tell you what to retry. Resending successful items wastes quota and can cause duplicates.
  3. 3. Why does the install handler check the scope before exchanging the code?

    Validate input first, then perform the one-time exchange. A token that lacks required scopes would only fail later.
  4. 4. A product name contains {{secret}}. How should a safe renderer treat it?

    Data is not template code. A single pass over the template, with escaping for values, keeps merchant text inert.
  5. 5. With a stale-while-revalidate cache, what does a visitor get when the entry is older than the fresh time but inside the stale window?

    The visitor gets a fast answer and the cache heals itself. After the stale window ends, the next request waits for fresh data.

Summary

  • Exercises 1 and 2 train least-privilege scopes and correct pagination with total_pages.
  • Exercises 3 and 4 train partial-failure batches and sync plans that are safe to run twice.
  • Exercises 5 and 6 train an install callback that validates before it exchanges a one-time code, and a webhook receiver that checks a secret in constant time and ignores duplicates.
  • Exercises 7 and 8 train safe templates and validated theme settings.
  • Exercises 9 and 10 train integer-cent cart math and a stale-while-revalidate cache.
  • Every solution is a stand-in; the real platform adds validation, scale and security you should still read about in its documentation.

Next: Interview Questions