Builder SDK
@usethrottle/builder is the headless client of Throttle Builder. A store reads the published pages, the header and footer, the slots and the site settings with it, and clears its own cache when
the Builder says something changed.
npm install @usethrottle/builder The client
import { createBuilderClient } from '@usethrottle/builder';
const builder = createBuilderClient({ builderKey: process.env.THROTTLE_BUILDER_KEY! }); // tb_pk_...
const site = await builder.site({ locale: 'en' }); // { generation, siteVersion, settings }
const pages = await builder.pages.list(); // [{ id, slug, pageType, title, updatedAt, path }]
const page = await builder.pages.get('about', { locale: 'en' }); // LoadedPage | { redirectTo }
const header = await builder.parts.get('header'); // { generation, document }
const slot = await builder.slots.get('product.below');
const bundle = await builder.bundle({ page: 'about', slots: ['shop.above'], locale: 'en' });
// { generation, site, header, footer, page?, slots } | Option | Default | Meaning |
|---|---|---|
builderKey | required | A publishable key (tb_pk_...), sent as X-Builder-Key. A secret key (tb_sk_) is refused with a TypeError. |
baseUrl | https://builder.usethrottle.dev | The Builder host. |
timeoutMs | 3000 | Per read, the body included. |
fetch | global fetch | Your own fetch, for tests. |
previewToken | none | Reads drafts with X-Builder-Preview. Never cached, never answered from a last good copy. |
Every read takes { locale }, which picks the text of a translated value (the locale, then its language, then English). A page slug or slot name is a
non-empty string of at most 128 characters.
The client sends no Origin header, so on a server it needs a key of the server or app channel. A
browser key works only from the exact https origins it lists. A page document of an older schema version is upgraded on read, and one of a newer version
throws BuilderUnavailableError with reason unsupported-document, so an old SDK never renders what it cannot read.
Answers
| Read | Route | Answer |
|---|---|---|
site() | GET /v1/site | The published site settings resolved for one locale, with generation and siteVersion. |
pages.list() | GET /v1/pages | The published pages: id, slug, pageType, title, updatedAt and path. |
pages.get(slug) | GET /v1/pages/:slug | A page with its document, or { redirectTo } (a site path) for an address that moved. An unpublished page is 404 PAGE_NOT_FOUND. |
parts.get(name) | GET /v1/parts/:name | The header or footer document. Unpublished is an empty document. |
slots.get(name) | GET /v1/slots/:name | A slot document. Unpublished is an empty document. |
bundle({ page, slots }) | GET /v1/bundle | Site, header, footer, optionally one page and the named slots, in one read. |
A page answer also carries a seo object (title, description, shareImage and noindex) next to its document. Every document carries its frozen custom widgets and frozen assets, so
rendering needs no further request. A page, part, slot or bundle answer can also carry savedSections (the published section of every saved section
the document references, by the id of its document) and code ({ enabled, scriptOrigin, codeSiteId }: whether the store runs
code widgets and where their scripts come from); the client passes both through unchanged, and a code store allows script-src https://builder.usethrottle.dev. The shapes are in the document schema.
Errors and last good answers
import {
BuilderUnavailableError,
BuilderNotFoundError,
PreviewExpiredError,
} from '@usethrottle/builder';
try {
await builder.pages.get('about');
} catch (error) {
if (error instanceof BuilderNotFoundError) return notFound(); // 404 PAGE_NOT_FOUND
if (error instanceof BuilderUnavailableError) console.error(error.reason, error.status);
throw error;
} | Error | When |
|---|---|
BuilderUnavailableError | A timeout, a network failure, a non-success status, a body that is not what the API sends, or a document from a newer schema. reason is timeout, network, status, invalid-response or unsupported-document; status holds the HTTP status when there was one. |
BuilderNotFoundError | A page that is not published and has no redirect. |
PreviewExpiredError | A preview token that is expired or not valid (401). A preview read never falls back to the published page. |
A published read that fails with BuilderUnavailableError within 10 minutes of a good one answers the good one (per process, at most 200 reads
kept) and logs once. After that the failure reaches you. A not-found or an expired preview is an answer, and is never softened.
Caching in Next.js
Every published read is kept until a change notice clears it: next: { revalidate: 3600, tags }. The hour is only a safety net behind the
notices, and there is no option for a shorter time, so a Builder read can never cost ISR writes on a timer. The client never calls revalidatePath.
A preview read is no-store.
| Tag | On |
|---|---|
throttle-builder | Every read. |
throttle-builder:site | The site settings. |
throttle-builder:pages | The page list. |
throttle-builder:page:<slug> | One page. |
throttle-builder:part:<name> | The header or the footer. |
throttle-builder:slot:<name> | One slot. |
A read carries the tag of what it holds, so a change clears only that. A change to the site or the menus clears the site, header and footer reads and never the pages.
Constants and helpers: BUILDER_TAGS, scopesToTags and UNTIL_CHANGED_REVALIDATE_S.
Change notices: @usethrottle/builder/next
// app/api/throttle/builder-revalidate/route.ts
import { createRevalidateHandler } from '@usethrottle/builder/next';
export const POST = createRevalidateHandler({
secret: process.env.THROTTLE_BUILDER_WEBHOOK_SECRET, // or a list, to rotate a secret
});
The handler checks the X-Throttle-Builder-Signature header and clears the cache tags of the notice's scopes with revalidateTag, never a path. When a notice names more than 20 tags it clears the coarse tag once instead.
| Status | Meaning |
|---|---|
200 | { revalidated: [...tags] } |
400 | The body is not a builder.changed notice. |
401 | The signature is missing, stale (over 300 seconds) or wrong. |
413 | The body is over 64 KB. |
500 | No signing secret is set in this environment. Nothing is revalidated. |
The signature is t=<unix seconds>,v1=<hex>, an HMAC-SHA256 over throttle.builder-notice.v1.<t>.<raw body> (up to 8 v1 values are accepted, compared in constant time). The label means a
catalog or webhook signature never verifies as a Builder notice. To check one yourself:
import { verifyBuilderNotice } from '@usethrottle/builder';
const ok = await verifyBuilderNotice({
rawBody, // the body exactly as received
header: request.headers.get('x-throttle-builder-signature') ?? '',
secret: process.env.THROTTLE_BUILDER_WEBHOOK_SECRET!,
now: Math.floor(Date.now() / 1000), // unix seconds
}); secret may be a list. Add the new secret, change it in the Builder, then remove the old one.
A backstop for a missed notice: @usethrottle/builder/watch
'use client';
import { useRouter } from 'next/navigation';
import { useGenerationWatch } from '@usethrottle/builder/watch';
export function BuilderWatch() {
const router = useRouter();
useGenerationWatch({
builderKey: process.env.NEXT_PUBLIC_THROTTLE_BUILDER_KEY!,
// Ask the store's own route to clear the cache first, then re-render.
onChange: () => {
void fetch('/api/throttle/builder-sync', { method: 'POST' })
.catch(() => undefined)
.then(() => router.refresh());
},
});
return null;
}
It reads the site generation with a conditional request (an unchanged answer is a 304) at most every 30 seconds (60 by default), only while the tab
is visible, and calls onChange when it moves. It never revalidates a cache itself. It takes a publishable key and refuses a secret one.
router.refresh() renders from the server's data cache, so the store needs a route that clears it. createWatchSyncHandler from @usethrottle/builder/next is that route: it reads the site generation from the Builder (at most once every 20 seconds per instance), and compares it with the generation the store's own data cache holds (a throttle-builder-tagged read of the same answer, shared by every instance). Only when they differ does it clear the throttle-builder tag, so a cold start or repeated calls clear nothing: purges follow real publishes. It answers 500 with no key and 502 when the Builder cannot be read.
// app/api/throttle/builder-sync/route.ts
import { createWatchSyncHandler } from '@usethrottle/builder/next';
export const POST = createWatchSyncHandler({ builderKey: process.env.NEXT_PUBLIC_THROTTLE_BUILDER_KEY }); Preview
previewMiddleware(req), getPreviewToken() and PREVIEW_COOKIE from @usethrottle/builder/next carry a one-hour preview token from the link a merchant opens to the client. See rendering.
Build mode
createBuilderClient({ mode: 'build' }) and getReleaseBundle() read a frozen release once and answer every other read
from it. They are described in Builder delivery modes.