Documentation menu

DocsFoundation

Architecture

This doc explains how Groundwork's pieces fit together: the request lifecycle from server.ts through a route's loader, the directory layout and why logic lives in app/lib/ while presentation stays in app/components/, the token-based theming approach, and the full list of extension points (markets, wishlist, recently-viewed, B2B, bundles, notify-back-in-stock) with the reasoning behind each one.

It's for a developer about to extend Groundwork on a real project: someone deciding where a new feature belongs, how to add context to every loader without a global import, or what the theme-contract boundary actually protects. It assumes you know React and general SSR concepts. You don't need to know Hydrogen yet, so it's a reasonable second stop even before you've written any Hydrogen code.

Afterwards you'll know where session handling, cart logic, market switching and theming live, and which parts of the codebase are meant to be extended and which are best left alone.

Before you start: skim Overview first for the project structure at a glance. This doc goes deeper into the same layout without re-introducing it.

Related: Theme Contract for the formal token spec this doc's theming section points to, plus B2B-Ready Data Layer, Bundles & Upsell and Notify Me When Back in Stock, which expand on the extension points this doc covers in one line each.

Source: docs/ARCHITECTURE.md

This document explains how the pieces of this template fit together and why they're structured the way they are. It assumes you know React and general SSR concepts. You don't need to know Hydrogen.

The stack

  • React Router 7 (framework mode) owns routing, data loading, server-side rendering and the build (react-router build).
  • Hydrogen 2026-10 is a library this app composes. It doesn't own the request. It provides a Storefront API client, request handlers for Shopify-owned URLs (cart API, checkout redirects, the Storefront API proxy, Customer Account login), a client-side cart store, and <ShopifyScripts> for analytics, consent and Shopify's runtime. Presentational pieces classic Hydrogen shipped (<Money>, <Image>, <Pagination>) are small local components in app/components/.
  • Oxygen (Shopify's edge runtime, compatible with Cloudflare Workers) or Vercel (Node.js functions) hosts it. Locally, @shopify/mini-oxygen runs the app in Oxygen's runtime through Vite, whichever host you deploy to. See DEPLOYMENT.md.
  • Vite is the build tool and dev server for everything above.

Request lifecycle

  1. A request comes into the host's entry file: server.ts on Oxygen, server.vercel.ts on Vercel. It gathers the host's settings, query cache, waitUntil and visitor-IP header, and hands the request to handleHostRequest (app/lib/host.ts), which puts them in React Router's context. From here on the code is the same on both hosts.
  2. The root route's middleware (app/root.tsx) runs for every request, including data requests. It builds the Storefront client for the visitor's market (app/lib/storefront.ts), then lets Hydrogen's handleShopifyRoutes answer Shopify-owned URLs before routing: /api/cart, /checkout, cart permalinks, the Storefront API proxy, ?variant= links and, when Customer Accounts are configured, /account/login|authorize|refresh|logout.
  3. Otherwise React Router matches a route in app/routes/ and runs its loader/action. Routes reach the Storefront client through context.get(storefrontContext) and the customer account through context.get(customerAccountContext). Both are request-scoped and never module-global, so nothing leaks across requests.
  4. On the way out the middleware commits the session cookie, tries Shopify URL redirects on a 404 (handleShopifyRedirects), and applies Shopify's response headers. entry.server.tsx sets the Content-Security-Policy.

The middleware needs React Router's future.v8_middleware flag (react-router.config.ts). Without it /api/cart silently 404s.

Directory layout

app/
  components/   Presentational and lightly-stateful UI. No data fetching.
  graphql/      Customer Account API documents (Storefront API queries live inline in routes/lib).
  lib/          Framework-agnostic logic: session handling, cart fragments, search, redirects, URL building.
  routes/       File-based routes (via @react-router/fs-routes). One file per URL pattern.
  styles/       Global CSS. Component-level styling is intentionally left open: bring your own approach (CSS Modules, Tailwind, vanilla-extract, etc).
  root.tsx      App shell: HTML document, layout, error boundary.
  entry.client.tsx / entry.server.tsx   React Router hydration/render entry points.

app/lib/ is where template consumers should look first when extending the app: it's plain TypeScript with no JSX, which is why it's also where most of the example unit tests live (see TESTING.md).

Running into a build error or a console warning that doesn't seem to trace back to anything you changed? Check TROUBLESHOOTING.md first. It covers a couple of known gotchas (browser-extension-caused hydration warnings, why npm audit fix --force is unsafe here) before you go digging.

Design tokens and theming

app/styles/tokens.css defines every color, spacing, type, radius, and shadow value as a CSS custom property (--sb-*), with light values by default, dark values via prefers-color-scheme, and a manual override via data-theme on <html> (set server-side from a cookie in root.tsx, so there's no flash of the wrong theme). app/styles/tailwind.css maps those same tokens into Tailwind's @theme, so Tailwind utilities and plain CSS against the tokens always resolve to identical values.

A theme is built against this token layer. Individual components don't come into it. See THEME_CONTRACT.md for the full spec: which tokens are required, how the light/dark/override cascade resolves, and what a future theme (beyond the Barebones/Signal pair) needs to satisfy to install cleanly.

Data flow: Storefront API

GraphQL documents are colocated with the route or component that uses them and typed via codegen: npm run codegen runs @shopify/hydrogen-codegen (configured in codegen.ts) against the Storefront and Customer Account schemas that ship with the installed @shopify/hydrogen (API version 2026-10). Generated types land in storefrontapi.generated.d.ts and customer-accountapi.generated.d.ts. Never edit these by hand. Run codegen after changing a query; unlike the classic shopify hydrogen dev --codegen, npm run dev does not regenerate them.

Routes call storefront.query(QUERY, {variables, cache}) (app/lib/storefront.ts): it throws on GraphQL errors, defaults to Cache.short() and types the result from the generated operation map, the contract classic Hydrogen's context.storefront had. Under it is Hydrogen 2026-10's client.graphql(), which returns {data, errors} and caches nothing unless asked. Hydrogen's own template types queries with gql() and a TypeScript plugin instead. Moving to that is a possible follow-up, and it wasn't part of the framework migration.

Sessions and auth

app/lib/session.ts implements a signed-cookie session manager (Hydrogen's WritableCustomerSessionManager: get, set and remove an item, plus a commit() that returns the cookie). Only Customer Account login reads it (the cart keeps its own cart cookie), so it can be swapped for KV, a database or another auth provider without touching routes.

Customer Accounts are wired in app/lib/customer-account.ts and switch on when the store sets SHOP_ID, PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID and SESSION_SECRET. Shopify's OAuth refuses plain-http origins, so locally they work under npm run dev:https only; on Mock.shop, or over http, /account answers 503 instead of starting a login that can't complete. Account routes call requireCustomerAccessToken, which sends signed-out visitors to /account/login and refreshes an expired token once through /account/refresh. Link to those paths with plain <a>/<form> instead of <Link>/<Form>, because Hydrogen's handlers serve them and no route does.

Why Mock.shop by default

This template is meant to be evaluated and extended before anyone connects a real Shopify store. resolveStoreTarget (app/lib/storefront.ts) uses Mock.shop when PUBLIC_STORE_DOMAIN is a Mock.shop domain, MOCK_SHOP=1 is set, or (in development only) no domain is set at all, so npm run dev and npm run build work immediately after npm install. A production build (npm run preview, any real Oxygen deployment) intentionally throws instead of silently falling back to Mock.shop if PUBLIC_STORE_DOMAIN isn't set. A forgotten store link shouldn't be able to serve mock data in production. .env.example sets PUBLIC_STORE_DOMAIN="mock.shop" explicitly so preview works out of the box too. Run npx shopify hydrogen link when you're ready to point it at a real store.

Extension points

  • Additional context (a CMS client, a reviews API, feature flags): create a React Router context with createContext<YourClient>(), context.set() it in the root middleware (app/root.tsx), and read it with context.get() in any loader or action. It's fully typed from the context object, the same way storefrontContext is.
  • Manual routes: app/routes.ts combines file-based routes with room for explicit route definitions. Use it for routes that don't fit the file-based convention.
  • Cart fragment: app/lib/cart-handlers.ts extends Hydrogen's default cart query with the fields this template's cart UI reads (gift cards, buyer identity, variant prices, bundle components); add fields there. The fragment must be named CartFragment.
  • Cart UI: the cart is a client store (app/lib/cart.ts): useCart() reads it, useCartForm() builds forms that post to Hydrogen's /api/cart handler and update the store optimistically. The root loader seeds it so the cart renders on the server. Changes Hydrogen's handler doesn't cover (gift cards, /discount/:code links) run as mutations in app/lib/cart-mutations.ts, then call useCartActions().refresh().
  • Analytics and consent: <ShopifyScripts> in app/root.tsx creates Shopify's analytics bus and Customer Privacy (no banner by default; see ANALYTICS_CONSENT). app/components/AnalyticsTrackers.tsx publishes page, product, collection, search and cart views, and useCartAnalytics() derives add/remove events from the cart store. Add your own analytics with window.Shopify.analytics.addDestination(); destinations only receive events once Customer Privacy allows it.
  • "Notify me when back in stock": app/lib/notifyBackInStock.ts ships as a documented stub (it validates input but doesn't persist or send anything). It isn't tied to any one ESP or waitlist app. See docs/guides/notifyBackInStock.md for how to wire it to Klaviyo, a custom serverless endpoint, or a metafield-backed app.
  • Free-shipping threshold: app/lib/freeShipping.ts exports FREE_SHIPPING_THRESHOLD as a plain constant instead of an env var. It's a per-store marketing decision, so change it directly. Set it to 0 to effectively turn the progress bar off.
  • Cart attributes: app/components/CartSummary.tsx's CartGiftWrap is a worked example of the cart attributes API (register('attributeValue', …) + the attributes-update intent, which replaces the whole attribute list, so the form resubmits the other attributes unchanged). It's a single {key, value} checkbox. Add more the same way for other custom attributes (gift message, referral source, etc.); note is a dedicated field (it isn't an attribute) and already has its own UI right below it.
  • Multi-currency / locale switcher (Shopify Markets): app/lib/market.ts defines SUPPORTED_MARKETS, a starter list mapping a market id to a {country, language} pair. Replace it with whatever markets the connected store actually has configured (Settings → Markets), or query localization { availableCountries } for a fully dynamic list. <MarketSelector> (in the footer) posts to /set-market, which stores the choice in the sb_market cookie; app/lib/storefront.ts reads that cookie once per request via getMarketFromRequest and localizes the request's Storefront client to it, so every route's existing @inContext(country: $country, language: $language) query picks it up automatically, with no per-route changes. Mirrors the sb_theme cookie pattern used by <ThemeToggle>. Note that Hydrogen 2026-10's own Markets support (defineShopifyI18n) resolves the market from the URL (a path prefix like /fr-ca, or a domain per market) and asks apps not to resolve it from a cookie. This template keeps the cookie, so no URL changes, through the fixed-locale form of createShopifyRequestContext; Hydrogen has deprecated that form for removal in its next major. Moving to URL-based markets is a product decision (it changes every storefront URL), and the switch is local to createRequestStorefrontClient.
  • Wishlist / save-for-later: app/lib/wishlist.ts is a localStorage-backed, anonymous, device-local wishlist. It needs no backend or account. <WishlistProvider> (wrapped around the app in PageLayout.tsx) hydrates from storage on mount and persists on every change; useWishlist() exposes {items, toggle, has} to <WishlistButton> (used on ProductItem grid cards and the PDP's ProductForm) and the /wishlist page. To make it follow a customer across devices instead, replace loadWishlistFromStorage/saveWishlistToStorage with reads/writes against a Customer Account metafield (e.g. a JSON list on the customer). The pure list operations (addWishlistItem, removeWishlistItem, toggleWishlistItem, parseWishlist) don't know or care where the list is persisted, so they carry over unchanged.
  • Recently viewed products: app/lib/recentlyViewed.ts mirrors the wishlist's localStorage approach exactly: the same anonymous, device-local storage and the same upgrade path to a Customer Account metafield. <RecentlyViewedProvider> (also wrapped around the app in PageLayout.tsx) tracks views; <RecentlyViewedTracker> records the current product on mount (used in products.$handle.tsx), and <RecentlyViewedProducts excludeId={...}> renders the rail, filtering out whichever product is currently being viewed.
  • Related products / cross-sell: products.$handle.tsx queries the Storefront API's productRecommendations(productId:) field. That's Shopify's actual recommendation engine (sales data, product metadata, tags), so nobody curates the list by hand. It's fetched in loadDeferredData (after the critical product data resolves, since it needs the product's id) and streamed in via <Suspense>/<Await> so a slow or failed call never blocks the page. The RelatedProduct fragment matches ProductItem/CollectionItem/RecommendedProduct's shape exactly, so the same <ProductItem> grid card renders it.
  • Bundles / upsell section: <BundleUpsell> (app/components/BundleUpsell.tsx) renders a fixed list of products with one "Add bundle to cart" action (multiple AddToCartButton lines at once) and a summed total via computeBundleTotal (app/lib/bundle.ts). It's a rendering pattern and leaves the bundling logic to you. See docs/guides/bundlesUpsell.md for the three ways to source the item list (a COMPLEMENTARY-intent product recommendation, a curated metafield, or Shopify's native product Bundles).
  • B2B-ready data layer: app/lib/b2b.ts implements quantity rules and volume pricing against real Storefront API fields (ProductVariant.quantityRule/.quantityPriceBreaks). <QuantitySelector> and <ProductForm>'s <VolumePricing> are wired up and working today, with no B2B account needed. Company accounts, negotiated catalogs, and net-terms checkout require a Shopify Plus B2B store and are documented but not wired up. See docs/guides/b2b.md for exactly what that involves and where it plugs into the request wiring in app/lib/storefront.ts and app/lib/cart-handlers.ts.