Next.js and caching
The /next entry gives a Next.js App Router store one helper per route, a provider wired to Next's router,
and the two handlers that clear the cache when your catalog changes. The defaults are set so a store does not write
to the ISR cache on every change, every visit or every deploy. Read Keeping ISR costs down before you go live.
Setup
Next.js 15 or newer. Both keys are needed: the server reads with the server key, the browser with the browser key (see the overview).
# .env.local
# Browser key: sent to the browser. The catalog answers it only from your allowed websites.
NEXT_PUBLIC_THROTTLE_CATALOG_KEY=pc_pk_...
# Server key: your server reads with it. NEVER a NEXT_PUBLIC_ variable.
THROTTLE_CATALOG_SERVER_KEY=pc_pk_...
NEXT_PUBLIC_SITE_URL=https://shop.example
THROTTLE_WEBHOOK_SECRET=whsec_...
// lib/store.ts: server code only. What every route needs, built once.
import { getPreviewToken } from '@usethrottle/storefront-react/next';
// Your server reads with the SERVER key (no NEXT_PUBLIC_ prefix): a server request carries no website origin,
// so the catalog refuses a browser key there. Never put the server key in a NEXT_PUBLIC_ variable.
const catalogKey = process.env.THROTTLE_CATALOG_SERVER_KEY;
if (!catalogKey) throw new Error('Set THROTTLE_CATALOG_SERVER_KEY (your catalog server key) in .env.local.');
export const store = {
catalogKey,
baseUrl: process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000',
// Draft preview reads the request's cookies, so every route renders per request. Preview deployments only.
...(process.env.THROTTLE_PREVIEW === '1' ? { previewToken: getPreviewToken } : {}),
};
In app/providers.tsx use StorefrontNextProvider from /next/client. It is StorefrontProvider with Next's useRouter, usePathname and useSearchParams and next/link, and with the open-tab check wired to the sync route (syncPath, below). Pass settings from loadSettings in the layout so the first paint needs no request, and import @usethrottle/storefront-react/styles.css in the layout, before your own CSS, with injectStyles={false}: the sheet then ships as a cached file, with the layer order
first, instead of inside every page's HTML. To serve images from your own origin, add a /media/:path* rewrite to the catalog and
pass imageOrigin="".
Route helpers
| Helper | Route | Notes |
|---|---|---|
createShopAllPage({ ...store, source }) | The shop, a collection, a category or a tag. source is all, collection, category or tag. | Reads the page's searchParams, so it renders per request. A missing handle is a 404, a renamed one a 308. |
createProductPage({ ...store, staticParams }) | A product, by handle. | staticParams defaults to 0. See the cost section. |
createSearchPage(store) | Search results, query in ?q=. | Dynamic, never cached, noindex. |
createAccountPage(store) | The account page (needs @usethrottle/auth). | Never indexed. |
// app/p/[handle]/page.tsx. The other routes are the same three lines with their own helper:
// createShopAllPage({ ...store, source: 'collection' }), createSearchPage(store), createAccountPage(store).
import { createProductPage } from '@usethrottle/storefront-react/next';
import { store } from '@/lib/store';
// staticParams defaults to 0: no product is prerendered, because every deploy writes every prerendered
// page again (ISR writes). Each product renders on its first visit and is then cached until the catalog changes.
const route = createProductPage({ ...store, staticParams: 0 });
export default route.Page;
export const generateMetadata = route.generateMetadata;
Each helper returns { Page, generateMetadata } (and generateStaticParams for products), built on loadShopAll, loadProduct, loadSearch and the metadata builders from /server. Use those
directly if you want your own page around the components. Shared options:
| Option | Meaning |
|---|---|
catalogKey | The server key (or the browser key where no server key exists). |
baseUrl | Your origin, for canonical URLs and Open Graph. |
previewToken | Draft preview (getPreviewToken). It reads cookies, so the route renders per request: preview deployments only. |
site | A function returning the site design, for the title template and the share image (a Builder store passes its own). |
primaryCache | 'default' or 'no-store'. See the cost section. |
Keeping ISR costs down
1. The cache policy: kept until the catalog changes
createStorefrontServerClient reads on STOREFRONT_CACHE_POLICY: every kind of read (settings, navigation,
pages, product, listings, facets, related, reviews) is 'until-changed'. A read is kept, with the catalog
SDK's one-hour safety limit as the longest it can go without a check, and cleared sooner when the catalog changes.
Nothing revalidates in under one hour. Next regenerates a page on its lowest revalidate time, so one short
time on one read would regenerate every shop, collection and product page, per filter, sort and page, that often.
-
Override one kind with
cachePolicy: { listings: '120m' }if you must. Keep any override at an hour or more. - Never set
revalidateunder 3600 on a route, innext: { revalidate }on a fetch, or in route segment config. - A request with a customer token, a cart or a preview token is never cached, whatever the policy says.
2. Search is no-store and dynamic
STOREFRONT_CACHE_POLICY.search is 'no-store', and loadSearch (and any listing carrying a q) reads with cache: 'no-store'. Every query is a new URL; caching them is what makes a hosting
bill grow. createSearchPage reads searchParams, so Next renders it per request. If you write your own search
route, read searchParams or export dynamic = 'force-dynamic'.
3. One coarse tag, cleared at most once a minute
Every read carries a single tag, throttle-catalog (CATALOG_TAG). A change clears that tag, not one tag per
product or per route, and the clearing is coalesced: at most once a minute per server instance
(REVALIDATE_WINDOW_MS, a floor you cannot lower), however many notices arrive. A burst of merchant edits is one
regeneration, not one per product. A change that arrives inside the window is left pending and applied by the first
call after it; there is no timer, because Next applies a tag clearing when the request that called it ends. With several
instances each has its own window.
Never use revalidatePath. It regenerates a named page whatever changed, and a loop over paths is a
write per path. The package never calls it, and a store should not either.
4. The signed revalidate handler and the sync handler
Two route files, both short:
// 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 }),
});
| Handler | Triggered by | What it does |
|---|---|---|
createRevalidateHandler({ secret }) | The catalog's signed storefront.changed webhook. The primary path. | Checks the signature first: an unsigned or wrongly signed request is a 401 and clears nothing. A verified notice clears the one tag, at most once a minute. A test event clears nothing. secret accepts a list, for rotating it. |
createGenerationSyncHandler({ client }) | An open tab that saw the catalog's generation move (the provider's generationWatch), before it refreshes. | Reads the live generation (at most once per minIntervalMs, default 5 s), and only if it differs from the one the cache holds clears the tag, at most once a minute. Answers 200 { changed, throttled? }, or 502 { changed: false } when the catalog cannot be read. A change found inside the window carries retryAfterMs; the tab asks again then. It needs no auth because it cannot empty the cache unless the generation really moved. |
Set the webhook up. Add THROTTLE_WEBHOOK_SECRET and point the catalog's storefront.changed
webhook at https://your-store/api/throttle/revalidate. Without it the store still updates, but only through open
tabs and the one-hour safety limit.
StorefrontNextProvider takes syncPath: the route the open tab POSTs to when its watch sees a new generation
(default '/api/throttle/sync'; null skips the POST, and the page refresh alone follows). generationWatch is one cheap conditional read per open tab (a 304 when nothing changed), every 60 s at the
least; raise it for a high-traffic store, never lower it. createGenerationSync, createCoalescedRevalidate, CATALOG_TAG and REVALIDATE_WINDOW_MS are exported for a store that writes its own route; the coalescer is the
part to keep.
5. staticParams defaults to 0
createProductPage prerenders no product at build unless you ask: staticParams defaults to 0.
Each product is rendered on its first visit and then served from cached catalog data until the catalog changes. Every deploy writes all of its prerendered pages again, so staticParams: 50 is about 100 ISR writes (HTML and data per page)
per deploy, however few products changed. If you want some, set staticParams: n for the n most recently
updated products (capped at 50), and treat n as a number of writes per deploy. A catalog that cannot be read at build
time does not fail the build; those products render on their first visit instead.
The product route never reads searchParams on the server (the browser takes ?variant= from the URL), because
reading it makes the page dynamic, and Next will not serve a prerendered route that does.
6. primaryCache: 'no-store' and its trade-offs
By default the product, collection or category a page is about is read from the long cache, so a deleted product can
answer a cached 200 until the webhook or the watch clears it. A store without the webhook can pass primaryCache: 'no-store' to loadProduct and loadShopAll, or to createProductPage and createShopAllPage.
| 'default' | 'no-store' | |
|---|---|---|
| Freshness of the page's own product or collection | Until the webhook, the open-tab check or the one-hour limit. | Live on every request: a deleted product is a 404 and a renamed one a 308 at once. |
| Rendering and ISR writes | Whatever the route does today: per request in the scaffolded store (its catalog pages read the request), or cached and regenerated by Next when the tag is cleared. | The route always renders on demand: Next treats a no-store read as dynamic, so it is never written to the ISR cache. |
| Cost per visit | A render from cached data, or a cached page with no render. | A render and one catalog read, on every visit. A traffic spike is a spike of catalog reads. |
| Everything else on the page | Cached. | Config, lists, related products and reviews stay cached. |
It is the one opt-in live read. Keep the default when the webhook is set up.
7. Deploys, preview and the layout
- Deploys. Each production deploy starts with an empty page cache, so every page that is visited is written again. Merge changes in batches instead of deploying a line at a time.
- Preview.
THROTTLE_PREVIEW=1adds the preview token, which reads cookies and makes every route render per request. Leave it unset in production. - The store layout. The scaffolded store renders its catalog pages per request from cached catalog data, so it writes almost no ISR (only the static
account and not-found pages, once per deploy). Do not add
generateStaticParamsor a shortrevalidateunless you accept the writes that static pages bring.
8. Bots and deep pagination
A crawler multiplies URLs: every filter combination, sort and page number is a different address, and each is a different read. The package keeps most of that out of the index and out of your cache, and you should add the rest:
- Search and filtered URLs are
noindex,follow(two or more filter values, a non-default sort, a search term), and their canonical keeps at most one filter value, so crawlers consolidate on the clean URL. - Disallow the unbounded URLs in
robots.txt: the search path and thesort=andfilter.query keys. A crawler that never requests them never costs you a read for them. - Deep pagination is the same shape.
?page=4000is one more cached read. Keep numbered pagination (the default windowed links, not an endless list of page links) and rate-limit or challenge bots at your host's firewall; do not respond to a crawl by prerendering more. - Never prerender listings. A listing page depends on its query string; the helpers render it per request.
Checklist
- The server client is
createStorefrontServerClient(the cache policy above), with no override under an hour. - No
revalidateunder 3600 anywhere, and norevalidatePath. - The webhook is set up and
THROTTLE_WEBHOOK_SECRETis set. staticParamsis 0, or a number you accept as writes per deploy.- Search renders per request and reads no-store.
generationWatchis 60 s or more.- The server key is not a
NEXT_PUBLIC_variable, andTHROTTLE_PREVIEWis unset in production.