Recipes
Each recipe is a real file that is typechecked against the package, so the code you copy is the code that compiled. Every
amount a recipe draws goes through formatMoney or a component that uses it; none divides by 100 or writes a currency
symbol.
Restyle with Tailwind
Pass utility classes per part key in classNames. They are added after the package's classes and win because the
package's CSS lives in @layer throttle, below Tailwind's components and utilities layers. The
one requirement is the layer order, declared first in your CSS.
/* app/globals.css with Tailwind v4. Declare the layer order first. `throttle` sits between Tailwind's
`base` (its preflight reset) and `components` / `utilities`: the reset cannot undo the storefront's
own rules, and a utility class still beats the storefront. */
@layer theme, base, throttle, components, utilities;
@import 'tailwindcss';
@import '@usethrottle/storefront-react/styles.css';
// Restyle with Tailwind: pass utility classes per part key. They are added after the package's own classes
// and, because the package's CSS sits in @layer throttle below `utilities`, they win without !important.
import { ProductCard, ShopAll } from '@usethrottle/storefront-react';
import type { ListProduct } from '@usethrottle/catalog';
const classNames = {
'product-card': 'rounded-2xl shadow-sm hover:shadow-md',
'product-card-title': 'text-base font-semibold tracking-tight',
'shop-all-heading': 'text-4xl font-bold',
};
export function Shop() {
return <ShopAll source={{ kind: 'all' }} classNames={classNames} />;
}
export function OneCard({ product, generatedAt }: { product: ListProduct; generatedAt: string }) {
return <ProductCard product={product} generatedAt={generatedAt} classNames={classNames} />;
}
Part keys are listed in STOREFRONT_PART_KEYS, and every element shows its own in data-throttle-part in the browser inspector.
Swap the Price slot
A slot gets the props its default takes. The price slot gets minor, currency, compareAtMinor and priceContext; draw them with formatMoney(minor, currency).
// Swap the Price slot of every card. The slot receives the amounts in minor units and the record's own
// currency; show them with formatMoney, never with your own division or a currency symbol.
import { formatMoney } from '@usethrottle/money';
import { ProductCard, type PriceProps } from '@usethrottle/storefront-react';
import type { ListProduct } from '@usethrottle/catalog';
function MemberPrice({ minor, currency, compareAtMinor, priceContext }: PriceProps) {
return (
<p data-price-context={priceContext}>
<strong>{formatMoney(minor, currency)}</strong>
{compareAtMinor !== undefined && compareAtMinor > minor ? <s> {formatMoney(compareAtMinor, currency)}</s> : null}
</p>
);
}
export function Card({ product, generatedAt }: { product: ListProduct; generatedAt: string }) {
return <ProductCard product={product} generatedAt={generatedAt} slots={{ Price: MemberPrice }} />;
}
Rearrange ShopAll sections
Give ShopAll.Root children and place the pieces yourself. Put filters in the top bar or a drawer with filterLayout, and choose pagination and columns; each defaults to your catalog's setting.
// A shop page laid out by hand: the filters in a top bar, the sort beside the count, no sidebar.
import { ShopAll } from '@usethrottle/storefront-react';
export function ShopPage() {
return (
<ShopAll.Root source={{ kind: 'all' }} filterLayout="topbar" pagination="load_more" columns={{ desktop: 4, mobile: 2 }}>
<ShopAll.Breadcrumbs />
<ShopAll.Heading />
<ShopAll.SlotAbove />
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<ShopAll.ResultCount />
<ShopAll.SortSelect />
</div>
<ShopAll.FilterBar />
<ShopAll.ActiveFilters />
<ShopAll.ProductGrid />
<ShopAll.Pagination />
<ShopAll.SlotBelow />
</ShopAll.Root>
);
}
Headless filters with useShopAll
useShopAll() answers the facets, the selection (query) and the actions (toggleValue, setValues, setRange, setSort, setPage, clear). The selection is the URL, so your markup stays shareable and
the back button works. Wrap in <Unstyled> to drop the package's classes for what you draw.
// Headless filters: your own markup from `useShopAll()`. The selection lives in the URL; these calls change it.
import { ShopAll, Unstyled, useShopAll } from '@usethrottle/storefront-react';
function MyFilters() {
const { facets, query, toggleValue, clear, selectedCount } = useShopAll();
return (
<form aria-label="Filters">
{facets.map((facet) => (
<fieldset key={facet.key}>
<legend>{facet.label}</legend>
{facet.values.map((value) => (
<label key={value.value}>
<input
type="checkbox"
checked={(query.filters[facet.key] ?? []).includes(value.value)}
onChange={() => toggleValue(facet.key, value.value)}
/>
{value.label} ({value.count})
</label>
))}
</fieldset>
))}
{selectedCount > 0 ? (
<button type="button" onClick={() => clear()}>
Clear all
</button>
) : null}
</form>
);
}
export function Shop() {
return (
// <Unstyled> drops the package's base classes (data-throttle-part stays) for everything inside.
<Unstyled>
<ShopAll.Root source={{ kind: 'all' }}>
<MyFilters />
<ShopAll.ProductGrid />
<ShopAll.Pagination />
</ShopAll.Root>
</Unstyled>
);
}
Add GA4
Pass gaAnalytics() as analytics. Your page loads gtag.js or Google Tag Manager; the storefront pushes the
ecommerce events (view_item_list, select_item, view_item, add_to_cart, remove_from_cart, view_cart, begin_checkout). To send them through Throttle's own scripts instead, use throttleScriptsAnalytics(scripts) with @usethrottle/scripts. To send your own events, useTrack().
// GA4: the storefront reports view_item_list, select_item, view_item, add_to_cart, remove_from_cart,
// view_cart and begin_checkout. Prices in the payloads are decimal amounts (19.99), made with @usethrottle/money.
import { StorefrontProvider, gaAnalytics } from '@usethrottle/storefront-react';
import type { ReactNode } from 'react';
// The page loads gtag.js (or Google Tag Manager) itself. `dataLayer` pushes { event, ecommerce } for GTM;
// 'gtag' calls gtag('event', name, payload) directly.
const analytics = gaAnalytics({ target: 'dataLayer' });
export function Providers({ children }: { children: ReactNode }) {
return (
<StorefrontProvider catalogKey="pc_pk_your_browser_key" analytics={analytics}>
{children}
</StorefrontProvider>
);
}
A Vite (client-only) store
No server is needed: the provider reads the catalog's settings in the browser with a browser key, and its history router
is the default. Add your site's origin to the key's allowed websites. Persist the cart session with cartStorage, or a reload starts a new cart.
// src/App.tsx of a Vite (client-only) app: no server, no Next.js.
// main.tsx renders it with createRoot(document.getElementById('root')!).render(<App />).
import { CartDrawer, ShopAll, StoreFrame, StorefrontProvider } from '@usethrottle/storefront-react';
import '@usethrottle/storefront-react/styles.css';
// Keep the cart's session id in the browser, so a reload keeps the cart.
const cartStorage = {
get: () => localStorage.getItem('throttle-cart'),
set: (id: string) => localStorage.setItem('throttle-cart', id),
remove: () => localStorage.removeItem('throttle-cart'),
};
export function App() {
return (
// The browser key is public: your site's origin must be one of its allowed websites.
<StorefrontProvider
catalogKey="pc_pk_your_browser_key"
preset="editorial"
locale="en"
currency="USD"
cartStorage={cartStorage}
>
<StoreFrame>
<ShopAll source={{ kind: 'all' }} />
</StoreFrame>
<CartDrawer />
</StorefrontProvider>
);
}
Add an account page
Install @usethrottle/auth, add the account publishable key to your catalog's brand settings, and render AccountPage. In Next.js, createAccountPage(store) does it in three lines.
// An account page: the dashboard for a signed-in shopper, sign-in for a signed-out one. It needs
// `@usethrottle/auth` and the account key in your catalog's brand settings (or `throttlePublishableKey`).
import { AccountPage } from '@usethrottle/storefront-react/account';
export function Account() {
return <AccountPage view="dashboard" onSuccess={() => window.location.assign('/')} />;
}
Pick a preset in code
Without a Throttle Builder your props decide the theme; with one, the Builder does and a development warning names the prop
it shadowed. appearance.variables always has the last word. See Theming.
// Pick a preset and adjust tokens in code. For the theme group, a Throttle Builder's design wins over
// these props, and these props win over the catalog's theme. `appearance.variables` always has the last word.
import { StorefrontProvider } from '@usethrottle/storefront-react';
import { PRESET_TOKENS } from '@usethrottle/ui/presets';
import type { ReactNode } from 'react';
export function Providers({ children }: { children: ReactNode }) {
return (
<StorefrontProvider
catalogKey="pc_pk_your_browser_key"
preset="bold"
scheme="auto"
theme={{ radius: 2, spacingScale: 'roomy' }}
appearance={{ variables: { colorPrimary: '#0b6b3a' } }}
>
{children}
</StorefrontProvider>
);
}
// The tokens of a preset, for your own CSS: PRESET_TOKENS.clean | .editorial | .bold.
export const boldTokens = PRESET_TOKENS.bold;
A collection shelf and a product carousel
Both read their products in the browser unless you give them initialData from loadMerchProducts, which lets a
server component send the first render with the products already in it.
// A home page section: a collection shelf and a product carousel. Give each `initialData` from
// `loadMerchProducts` on the server and it renders at once and asks for nothing.
import { CollectionShelf, ProductCarousel } from '@usethrottle/storefront-react';
import { createStorefrontServerClient, loadMerchProducts } from '@usethrottle/storefront-react/server';
export async function Home() {
const client = createStorefrontServerClient({ catalogKey: process.env.THROTTLE_CATALOG_SERVER_KEY ?? '' });
const shelf = await loadMerchProducts({ client, source: { kind: 'collection', handle: 'summer' }, limit: 4 });
const newest = await loadMerchProducts({ client, source: { kind: 'newest' }, limit: 8 });
return (
<>
<CollectionShelf handle="summer" eyebrow="New in" limit={4} layout="grid" initialData={shelf} />
<ProductCarousel source={{ kind: 'newest' }} title="Just arrived" limit={8} cardMeta="category" initialData={newest} />
</>
);
}
Arrange the product page
// A product page with your own arrangement inside the page's state: one gallery, then the buy box,
// the sections, related products and reviews.
import { ProductPage } from '@usethrottle/storefront-react';
import type { ProductData } from '@usethrottle/storefront-react/server';
export function Product({ data }: { data: ProductData }) {
return (
<ProductPage.Root initialData={data} baseUrl="https://shop.example" reviewsLayout="columns">
<ProductPage.JsonLd />
<ProductPage.Breadcrumbs />
<ProductPage.SlotAbove />
<ProductPage.Gallery />
<ProductPage.BuyBox headingLevel={1} />
<ProductPage.ProductSections />
<ProductPage.RelatedProducts />
<ProductPage.Reviews />
<ProductPage.SlotBelow />
<ProductPage.StickyAddToCart />
</ProductPage.Root>
);
}
Keep an open tab fresh without webhooks
The signed webhook is the primary way a change reaches your store. If you cannot set it up, the open-tab check still works:
the provider's generationWatch (every 60 s at the least) sees the catalog's generation move and POSTs to syncPath before it refreshes the page, and createGenerationSyncHandler clears the cache only when the generation
really moved, at most once a minute. A visitor with a tab open sees a change within about a minute; a store with no open tabs
updates through the one-hour safety limit.
// app/api/throttle/revalidate/route.ts
// The catalog's signed `storefront.changed` webhook: the primary path. The signature is checked first
// (an unsigned request is a 401 and clears nothing). One coarse tag, at most once a minute per instance.
import { createRevalidateHandler } from '@usethrottle/storefront-react/next';
export const POST = createRevalidateHandler({ secret: process.env.THROTTLE_WEBHOOK_SECRET });
// app/api/throttle/sync/route.ts
// The open tab's backstop: the tab POSTs here when it sees the catalog's generation move, so a store without
// the webhook still catches up. Clears only if the generation really moved, one coarse tag, at most once a minute.
import { createGenerationSyncHandler } from '@usethrottle/storefront-react/next';
import { createStorefrontServerClient } from '@usethrottle/storefront-react/server';
import { store } from '@/lib/store';
export const { POST } = createGenerationSyncHandler({
client: createStorefrontServerClient({ catalogKey: store.catalogKey }),
});
generationWatch below 60 s, and do not clear the cache with revalidatePath or a short
revalidate: those are the settings that turn a catalog edit into hundreds of ISR writes. The reasons and the
checklist are on Keeping ISR costs down.
Widget packs for the Throttle Builder
@usethrottle/storefront-react/builder exports catalogPack() and commercePack()
for @usethrottle/builder-react. They wrap the components on this page (the product grid, collection shelf, featured product,
product carousel, category list, reviews list, search box, language and currency switches, cart button, account button) as Builder widgets, and add the
data sources that feed them. The entry needs @usethrottle/builder-react and @usethrottle/builder-schema
(both optional peers of this package); the core package never imports them.
// A plain module with no "use client" directive: the server imports it for loadSite(), and the client
// module that renders <BuilderProvider> imports it too.
import type { ThrottleAuth } from '@usethrottle/auth';
import type { CartStorage } from '@usethrottle/catalog/react';
import { catalogPack, commercePack } from '@usethrottle/storefront-react/builder';
// Pass the same cart storage and auth you give StorefrontProvider, so the cart count and the greeting read the shopper's own.
export function createPacks(cartStorage: CartStorage, auth: ThrottleAuth) {
return [
catalogPack({
catalogKey: process.env.NEXT_PUBLIC_CATALOG_KEY ?? '',
cartStorage,
// What a change of language or currency does is the store's business (a cookie and a refresh, a route).
onLocaleChange: (locale: string) => {
document.cookie = `locale=${locale}; path=/`;
},
onCurrencyChange: (currency: string) => {
document.cookie = `currency=${currency}; path=/`;
},
}),
commercePack({ auth }),
];
}
// Pass `packs` to loadSite() on the server and to <BuilderProvider> in the browser.
- Data sources.
catalog.products,catalog.product,catalog.collection,catalog.categoriesandcatalog.reviewsresolve on the server;context.productandcontext.listingare what a slot hands over (the product page's product, the listing page's listing), not a read;catalog.cartandthrottle.customerare per shopper and resolve in the browser only. A page makes one lookup request for all the catalog ids it stores (so a renamed collection still renders) and one list request per widget, never one per product. - Money. A money field is
{ amount, currency, display }, withamountin minor units anddisplayfromformatMoney. A template prints onlydisplayorcurrency. - Slots.
product.aboveandproduct.belowknow{ product };shop.aboveandshop.belowknow{ listing }. - Manifest.
@usethrottle/storefront-react/builder-pack.jsonis the data-only part of both packs (widget definitions, data sources, slot points), generated at build time. The Builder's server validates documents with it and never imports React. - Cost. The packs read through the catalog client's
until-changedpolicy (an hour at most, cleared by the catalog's cache tags). They never callrevalidatePathand never revalidate on a shorter time.