Developers / Throttle Builder

Rendering Builder pages

@usethrottle/builder-react draws a published page document as React and gives the store its header, footer, slots and site design. It reads through the SDK and never calls a cache API of its own.

Entries

EntryHolds
@usethrottle/builder-reactClient entry ("use client"): BuilderProvider, BuilderHeader, BuilderFooter, BuilderSlot, BuilderPage, BuilderPageView, BuilderRenderer, AssetImage, compileResponsiveCss, createRendererRegistry, basicPack and the types. Re-exports BuilderUnavailableError and BuilderNotFoundError.
@usethrottle/builder-react/serverServer loaders: loadSite, loadBuilderPage, builderSitemap, getBundle.
@usethrottle/builder-react/nextcreateBuilderPage, which returns { Page, generateMetadata }.

It needs React 18 or newer, and Next.js 15 or newer for ./next. The widgets come from packs: the Builder's own basic widgets are always present, and @usethrottle/storefront-react/builder adds the catalog and commerce widgets (see the widget guideline).

The site: loadSite and BuilderProvider

Read the site design once per request
import { loadSite } from '@usethrottle/builder-react/server';

const site = await loadSite({
  builderKey: process.env.THROTTLE_BUILDER_KEY!, // or client: builder
  locale: 'en',
  slots: ['product.above', 'product.below', 'shop.above', 'shop.below'],
  packs,                                          // WidgetPack[]
  mediaOrigin: process.env.THROTTLE_MEDIA_ORIGIN ?? '',
});
// { status: 'ok', ... } or { status: 'unavailable', locale } when the Builder is down

loadSite makes one Builder read for the request (the settings, header, footer and the slots you name) and resolves the data of their widgets that does not depend on the shopper. Reads of one request are shared: an ask that an earlier read already covers reuses it, and asks in the same tick merge into one. A layout does not know the page, so on a Builder page route the layout read and the page read are two reads unless loadSite is given page.

The provider goes in a client module
'use client';
import { BuilderProvider, BuilderHeader, BuilderFooter, BuilderSlot } from '@usethrottle/builder-react';

<BuilderProvider packs={packs} site={site}>
  <BuilderHeader />
  {children}
  <BuilderFooter />
</BuilderProvider>

// Where the catalog renders a slot, give it what it knows:
<BuilderSlot name="product.below" context={{ product }} />

BuilderProvider is a client component, because a pack holds components and functions that a server component cannot pass down: create the packs in a client module of your store. It fills the site design (menus, brand, announcement, strings, theme), the slot outlets and the page renderer for the rest of the tree. site is plain data, so the server can pass it. Give the provider a builderKey or a client only if a BuilderPage below it reads its own page in the browser; that needs a key of the browser or app channel.

The Builder being down never blanks the store
With no answer and no last good answer, loadSite returns { status: 'unavailable' } and logs once per process. The header, footer and slots then render nothing and the catalog pages keep working. A Builder page throws BuilderUnavailableError and lets your error boundary answer, never a blank 200. A widget that throws blanks only itself.

Media. An image shows only when its src is https on exactly mediaOrigin. With no origin, no image shows. The logo, favicon and share image follow the same rule.

Saved sections

A page, header, footer or slot can hold a reference to a saved section: one section kept once and used by many pages. The read answer carries the published section of every saved section the document uses (savedSections), and the renderer draws it where the reference stands. loadSite and loadBuilderPage keep it with the page or part, so there is nothing to pass.

Every id inside a saved section is written as <reference id>-<inner id> in data-b-id, so two references to the same saved section on one page never share CSS. A reference whose section the answer does not hold renders an empty box with data-b-missing and nothing else; the rest of the page is not affected. A page holds at most 20,000 nodes with its saved sections expanded; references past that are left out and render as missing.

Code widgets

A code widget is a widget with markup, CSS and a script. The page document holds only the markup, the CSS and the script's hash; the script itself is served from the Builder, one file per widget. A store runs a code widget only when all of these hold: the merchant turned code on in the dashboard (code.enabled in the read answer), the widget is not turned off, the page is on the route allow-list, and the render is a live store page (not the editor, not a preview, and not interactive={false}). Then the widget carries data-b-code, its input as <script type="application/json" data-b-code-input> and one <script async src> for its script. In every other case only its markup and CSS are drawn, marked data-b-code-inert, and no script is written.

Tell the provider which page it renders
'use client';
import { usePathname } from 'next/navigation';
import { BuilderProvider } from '@usethrottle/builder-react';

<BuilderProvider
  packs={packs}
  site={site}
  pathname={usePathname()}                 // code runs only where this path is allowed
  catalogRoutes={['/p/{handle}', '/c/{handle}']} // optional: your catalog route templates
>
  {children}
</BuilderProvider>
  • Route allow-list. It lives in the renderer and is not a setting. Code never runs on /checkout, /cart, /account, /sign-in, /sign-up, /login, /register, /order(s) and /pay (and below them), whatever else matches, and the same words on any segment of the path (/fr/checkout, /de/account/orders), whatever your page route is. The words include common synonyms (basket, bag, payment, my-account, login, password, wallet and others); a handle with one of those names (a product called bag) runs no code either. The limit: with a root-level page route such as /{handle}, code may run on any root-level page whose name is not on that list, so never put your own checkout or account under another root page name. Elsewhere it runs only on /, your page route (routes.page of the site settings) and the catalog routes: /p/{handle}, /c/{handle}, /collections/{handle}, /tags/{tag}, /search and /shop, or the templates you pass as catalogRoutes. The path is normalised first (/pages/../checkout is /checkout). Without pathname no code runs.
  • Leaving a code route is a full page load. A script that has loaded cannot be unloaded, so when a client-side navigation moves from a page that loaded code to a path that is not a code route (checkout, account, sign-in, cart), BuilderProvider loads the new address again from the server and no code survives there. The check also runs when the provider unmounts. Put BuilderProvider in a layout that also covers checkout, account and sign-in: only then does it draw an empty placeholder instead of the denied page while the reload is pending. pathname is the path without a Next basePath, and the unmount check reads the browser's full path, so with a basePath leaving the provider's layout can cause one needless reload. Pass pathname for this to work.
  • Settings. A code widget gets its desktop settings in its input; tablet and phone overrides of its settings are not applied (hiding it per device works as for any widget). Anchors of nodes inside a saved section are written <reference id>-<anchor> so two references never share an HTML id.
  • Re-checked on the store. The renderer validates a code widget's markup and CSS again with the same rules as a template widget, and refuses a snapshot that carries a script or a bad hash. A disabled widget renders nothing.
  • The switch. When the merchant turns code off, the store emits no code: the read answer says enabled: false and the script URL answers a no-op.
  • Preview. mode="preview" on the provider (the Builder's own preview page) draws code widgets with a "Runs on your store" badge and never runs them. Check code on the store's preview link.
Allow the script origin in your Content-Security-Policy
Code widgets load their script from the Builder, so a store with a strict policy adds script-src https://builder.usethrottle.dev. Code can read and change anything on your store pages.

Slots

A slot is a named place around a catalog page where the merchant can add content. The catalog pack declares four, in CATALOG_SLOT_POINTS:

SlotWhereContext
product.aboveAbove the product page{ product }
product.belowBelow the product page{ product }
shop.aboveAbove every listing: shop, collection, category, tag and search{ listing }
shop.belowBelow every listing{ listing }

Pass the slot names to loadSite; the catalog route helpers render them through the provider. A slot that is unpublished or empty renders nothing.

Next.js: createBuilderPage

One route for every Builder page
// app/pages/[handle]/page.tsx
import { createBuilderPage } from '@usethrottle/builder-react/next';

const route = createBuilderPage({
  fromParams: 'handle',      // or slug: 'about' for a fixed route
  builderKey: process.env.THROTTLE_BUILDER_KEY!,
  packs,
  storeUrl: process.env.NEXT_PUBLIC_SITE_URL!,            // your store's origin: the Builder does not publish it
  mediaOrigin: process.env.THROTTLE_MEDIA_ORIGIN ?? '',   // the same value as loadSite; no og:image without it
  // pagePath: (page) => (page.pageType === 'home' ? '/' : page.path)   if home is served at /
  // locale: 'en' | (params) => string   default: params.locale, else 'en'
  // slots: [...]                         the slots the layout reads, so both share one read
});
export default route.Page;
export const generateMetadata = route.generateMetadata;

Page reads the page, answers notFound() for an unpublished one and a permanent redirect for a page whose address changed, and lets BuilderUnavailableError reach your error boundary. A redirect is followed only when it is a path on your site. The route needs a provider above it, which the layout has.

generateMetadata applies the page's own search settings (page.seo) over the site defaults: the title (through the site's title template), the description, the openGraph and twitter share image, robots: { index: false } for a page set to noindex, and a canonical link with openGraph.url. It needs storeUrl (your store's origin, which the Builder does not publish) for the canonical, and mediaOrigin (the same value as loadSite) for the image. The canonical is the site's page route plus the slug, so the home page is /pages/home; a store that serves home at / passes pagePath. On a [locale] route the canonical gets /<locale>, with alternates.languages and x-default; do not also pass the locale option there. No structured data (JSON-LD) is emitted. See the search and sharing guide.

The sitemap

app/sitemap.ts
// app/sitemap.ts
import { builderSitemap } from '@usethrottle/builder-react/server';

export default async function sitemap() {
  return builderSitemap({
    builderKey: process.env.THROTTLE_BUILDER_KEY!,
    storeUrl: process.env.NEXT_PUBLIC_SITE_URL!, // required: an https://shop.example.com origin
    // locale: 'en', localeRoute: true, pagePath: ...   the same values as createBuilderPage
  });
}
// [{ url: 'https://shop.example.com/pages/about', lastModified: Date }, ...]

builderSitemap lists the published pages, at the page route (home at /pages/home), with their last change time. It leaves out pages set to noindex, using the noindex of the page list, with no read per page. An unavailable Builder gives an empty list and one warning, never a failed sitemap (a build-mode client fails the build instead). Without a storeUrl it returns an empty list and says why. Pass localeRoute: true for a [locale] route, to list each page once per site locale under /<locale> (not with a locale option on the page route), and the same pagePath as createBuilderPage.

Change notices

In live mode the Builder sends a signed builder.changed notice when something is published. Mount createRevalidateHandler from @usethrottle/builder/next at the endpoint you set in the Builder (the SDK page has the signature, the cache tags and the status codes). It clears the cache tags of the scopes that changed and nothing else, so one edited page refreshes that page.

A client component can also call useGenerationWatch from @usethrottle/builder/watch as a backstop for a missed notice. It reads the site generation at most every 30 seconds while the tab is visible.

Preview

Preview mode
// middleware.ts
import { previewMiddleware } from '@usethrottle/builder/next';

export function middleware(request: Request) {
  return previewMiddleware(request) ?? undefined;
}

// app/preview/[handle]/page.tsx: a preview-only route
import { createBuilderClient } from '@usethrottle/builder';
import { getPreviewToken } from '@usethrottle/builder/next';
import { loadBuilderPage } from '@usethrottle/builder-react/server';

export default async function PreviewPage({ params }: { params: Promise<{ handle: string }> }) {
  const client = createBuilderClient({ builderKey, previewToken: await getPreviewToken() });
  const page = await loadBuilderPage({ client, slug: (await params).handle, locale: 'en', packs });
  // render it with the provider's page view
}

A merchant opens a preview link of a draft at 390, 768 or 1280 pixels. previewMiddleware moves the throttle_builder_preview query parameter into an HTTP-only, Secure, SameSite=Lax cookie for one hour. A client with a preview token reads drafts, is never cached and never answers from a last good copy; an expired token throws PreviewExpiredError. getPreviewToken makes its render dynamic, so call it only on a preview-only route.

Interactions, countdown, entrance and custom CSS

A section or inner section with an interaction (tabs, accordion, carousel or toggle) draws its columns (1 to 6) as panels. The interaction can differ per device: a section that is tabs on desktop and an accordion on phone is drawn twice and shown by breakpoint classes, like a widget's markup variants. Without an interaction a section renders exactly the markup it always did.

ModeMarkupWithout JavaScript
tabsrole="tablist", tab, tabpanel; roving tabindex; arrow keys, Home and EndEvery panel is shown, each under its title.
accordionNative <details> / <summary>; with accordionMultiple off the items share a nameWorks as is.
toggleOne native <details>; the labels swap with CSSWorks as is.
carouselA scroll-snap track, aria-roledescription="carousel", slides labelled from panelTitle, Previous and Next buttonsThe track scrolls by touch and keyboard.

A carousel does not autoplay unless carouselAutoplay is on, and never does when the shopper asks for reduced motion. While it plays a visible Pause button is shown, and hover or focus pauses it. basic.countdown draws its target date as text; a script of about 1.5 KB (minified and gzipped, shipped inside the core entry) ticks it every second, applies expiredBehavior at zero, and updates a polite screen reader label once a minute. Without script a countdown whose target has passed still shows only its date, because expiry is decided in the browser (the page may be cached). The entrance animation (a common prop of every node) only starts after that script has set html[data-b-js], and is off under prefers-reduced-motion: reduce, so content is never hidden without script.

BuilderProvider and BuilderRenderer take interactive (default true). The editor's edit mode passes false: every panel is drawn expanded in a plain row, and nothing animates or ticks.

The site's theme.customCss is sanitised again by the provider (never emitted as stored), scoped under [data-b-root] (the element every Builder page, header, footer and slot renders inside) and emitted once, in @layer throttle-custom, after the renderer's own layer.

What the renderer guarantees

  • The renderer is a pure function of its props, so a page looks the same on the server, in a client tree and in the editor.
  • It never builds an HTML string. Text and template values go through React; a link or image URL is checked again before it is written.
  • Every custom widget sits in its own box (contain: layout paint; isolation: isolate; overflow: clip), and its CSS is scoped to it, so one widget cannot paint over or take clicks from another.
  • Interactions, countdown and entrance work from server-rendered markup: no panel is hidden and no content is invisible until the small script has run, and reduced motion turns the animation off.
  • A code widget runs only on a live store page, on an allowed route and with the merchant's code switch on. Nowhere else does the renderer write a script.
  • A page renders at most 20,000 nodes, and a template loop at most 100 items.
  • Data that depends on the shopper (the signed-in customer, the cart) is never in the server render. It fills in after mount.

Build mode

The same components render a frozen release at build time with no Builder request while the store runs. See Builder delivery modes for the build client, builderStaticParams and create-store --builder-mode build.