Contenter CMS — Developer Guide
How to connect a storefront to the Contenter CMS, so that editors can build its pages, layouts and themes, and preview every change in place before they publish it.
The CMS stores content. Your storefront renders it with your own components. The @contenter/* SDK sits in between: it reads the content, maps each CMS component onto one of yours, and — inside the CMS editor — turns your storefront into a live, clickable preview.
Start with How your storefront connects: the base URL and the key, and the rules that keep both on the server.
Packages
Eight packages, released together under one version.
| Package | What it is | You need it for |
|---|---|---|
@contenter/cms-protocol |
The wire contract between the editor and your storefront. No dependencies. | Always (a dependency of the others) |
@contenter/cms-client |
The delivery client, the environment config, Web-standard route handlers. | Always |
@contenter/react |
Renders CMS content with your React components; /next adds the App Router helpers. |
React / Next.js |
@contenter/preview-core |
The live-preview runtime, framework-free. | Live preview |
@contenter/preview-react |
<CmsProvider> — live preview for React. |
Live preview in React |
@contenter/react-components |
Eleven ready-made components, if you want a head start. | Optional |
@contenter/vue |
The Vue 3 renderer; /nuxt adds the Nuxt helpers. |
Vue / Nuxt |
@contenter/preview-vue |
Live preview for Vue. | Live preview in Vue |
Getting the SDK
The CMS distributes the SDK itself. /sdk on the hosted cms-api lists the current release — every package's version, its tarball and the npm integrity your lockfile will record — together with a ready-to-paste install command for each kind of storefront:
curl -s https://api.cms-contenter.medienwerft.de/api/sdk | jq -r '.install.next.command'
Run the command it prints. Two rules:
- Install a profile in one command. The packages depend on each other by version range; given all the tarballs at once, npm satisfies those ranges from them. Installed one at a time, npm looks for the dependency on the public registry and fails with a 404.
- Use npm 11.10 or newer. npm 11.6 fails to resolve
@contenter/reactwhen@contenter/preview-reactand@contenter/react-componentsare installed together.
The tarball URLs never change their contents — a new release is a new file name — so your lockfile stays valid and a CI install is reproducible.
The API underneath
The SDK is a thin layer over cms-api's read API. Its OpenAPI description is at /openapi.json and an interactive console at /docs, both served by every cms-api deployment.
How your storefront connects
Editors work in the CMS; your storefront reads what they publish from the CMS's API, cms-api. Two settings in your storefront's configuration decide that connection: the base URL, and the key your storefront proves itself with.
| Editors work in | the Medienwerft Service Hub |
CMS_API_BASE_URL |
https://api.cms-contenter.medienwerft.de/api |
| Content reads authenticate with | the CMS API key (CMS_API_KEY) |
Editor origin (CMS_EDITOR_ORIGINS) |
https://app.cms-contenter.medienwerft.de |
| Publish → cache refresh | a webhook from cms-api |
cmsConfigFromEnv() reads these from the environment and configures the client; you do not set anything up in code.
The CMS API key does three jobs: it authenticates content reads, it lets the editor open your storefront's preview, and it protects the endpoint that tells the editor which components your storefront has. See Credentials.
The rules
- Every credential stays on the server. None of the variables in this guide needs a
NEXT_PUBLIC_orVITE_prefix, and none of them may have one. The browser receives content, never a key. - The base URL is the cms-api base, nothing more. It ends in
/api. Never append/storefront— the client does.
Next: Quick start: Next.js.
Quick start: Next.js
From an empty Next.js App Router project to a storefront that renders CMS pages and previews them live in the editor. Every file below is taken from examples/next-app in the CMS repository, which builds and runs as shown.
You need: Next.js 15 or newer, React 18 or 19, npm 11.10 or newer, and the values from How your storefront connects.
1. Install
Copy the next command from /sdk (.install.next.command) and run it. It installs five packages in one go: cms-protocol, cms-client, react, preview-core and preview-react. Use next-with-components instead to add the eleven ready-made components this quick start renders.
2. Configure
Create .env.local:
CMS_API_BASE_URL=https://api.cms-contenter.medienwerft.de/api
CMS_API_KEY=cms_…
CMS_SITE=main
CMS_LOCALE=en
CMS_EDITOR_ORIGINS=https://app.cms-contenter.medienwerft.de
Where each value comes from: Credentials. Every variable: Environment reference.
3. The client
// src/lib/cms.ts — server-only
import { cmsConfigFromEnv } from '@contenter/cms-client';
import { createServerCmsClient } from '@contenter/react/next';
const env = cmsConfigFromEnv();
export const SITE = env.site ?? 'main';
export const LOCALE = env.locale ?? 'en';
export const DEFAULT_LAYOUT_ID = env.defaultLayoutId ?? 'default';
export const EDITOR_ORIGINS = env.editorOrigins;
for (const problem of env.problems) console.warn(`[cms] ${problem}`);
// Reads the environment itself, on first use. Published reads are cached for 60 s
// and tagged, so a publish can refresh them at once (chapter 12).
export const cms = createServerCmsClient({ revalidate: 60 });
env.problems is where a misconfiguration announces itself in words — a missing variable, a {tenant} placeholder with no tenant, a NEXT_PUBLIC_ key. Printing it at startup saves most of Troubleshooting.
// src/cms/server.ts
import { createServerCms } from '@contenter/react/next';
import { cms, LOCALE, SITE } from '@/lib/cms';
export const { CmsLayout, CmsPage, resolvePage, getLayout } = createServerCms({
client: cms,
site: SITE,
locale: LOCALE,
});
4. The components
The CMS stores each component as a type plus props; your registry maps each type to a React component. Start with the ready-made set and replace it type by type (Components and the registry):
// src/cms/registry.ts
export { defaultRegistry as registry } from '@contenter/react-components';
5. The chrome and the provider
Header, main and footer are yours; the CMS fills the slots you place in them. Declare the composition once — the public routes and the editor's preview route both render it.
// src/cms/Providers.tsx
'use client';
import type { ReactNode } from 'react';
import { CmsProvider } from '@contenter/preview-react';
import { registry } from '@/cms/registry';
export function Providers({ editorOrigins, children }: { editorOrigins: string[]; children: ReactNode }) {
return (
<CmsProvider registry={registry} originAllowlist={editorOrigins}>
{children}
</CmsProvider>
);
}
// src/cms/shell.tsx
import type { ReactNode } from 'react';
import { CmsContentSlot } from '@contenter/react/client';
import type { CmsChromeArgs } from '@contenter/react/next';
import { Providers } from './Providers';
import { CmsLayout, CmsPage, getLayout } from './server';
import { cms, DEFAULT_LAYOUT_ID, EDITOR_ORIGINS, LOCALE, SITE } from '@/lib/cms';
export function chrome({ children }: CmsChromeArgs): ReactNode {
return (
<Providers editorOrigins={EDITOR_ORIGINS}>
<header><CmsContentSlot slot="top" /></header>
<main>{children}</main>
<footer><CmsContentSlot slot="bottom" /></footer>
</Providers>
);
}
export const previewConfig = {
cms: { CmsLayout, CmsPage, getLayout },
client: cms,
site: SITE,
locale: LOCALE,
defaultLayoutId: DEFAULT_LAYOUT_ID,
chrome,
};
<CmsProvider> is inert outside the editor: shoppers get your components and no preview code.
6. The routes
// src/app/layout.tsx
import type { ReactNode } from 'react';
import { SITE } from '@/lib/cms';
export default function RootLayout({ children }: { children: ReactNode }) {
// data-cms-site scopes the theme's CSS variables (chapter 7).
return (
<html lang="en">
<body data-cms-site={SITE}>{children}</body>
</html>
);
}
// src/app/(storefront)/layout.tsx
import type { ReactNode } from 'react';
import { CmsThemeLink } from '@contenter/react';
import { CmsLayout } from '@/cms/server';
import { chrome } from '@/cms/shell';
import { DEFAULT_LAYOUT_ID, LOCALE, SITE } from '@/lib/cms';
export default function StorefrontLayout({ children }: { children: ReactNode }) {
return (
<>
<CmsThemeLink site={SITE} basePath="/api/cms/theme" />
<CmsLayout layoutId={DEFAULT_LAYOUT_ID} site={SITE} locale={LOCALE}>
{chrome({ children, mode: 'public', layoutId: DEFAULT_LAYOUT_ID })}
</CmsLayout>
</>
);
}
// src/app/(storefront)/[...slug]/page.tsx — and the same with slug="" in (storefront)/page.tsx
import { CmsPageSlots } from '@contenter/react/client';
import { cmsMetadata } from '@contenter/react/next';
import { CmsPage, resolvePage } from '@/cms/server';
type Props = { params: Promise<{ slug: string[] }> };
export async function generateMetadata({ params }: Props) {
return cmsMetadata(await resolvePage({ slug: (await params).slug }));
}
export default async function Page({ params }: Props) {
return (
<CmsPage slug={(await params).slug}>
<CmsPageSlots />
</CmsPage>
);
}
These routes read no searchParams, so Next can render them statically and cache them. Editing never makes a public route dynamic — the editor uses its own route:
// src/app/cms-editor/page.tsx
import { createCmsEditorPreview, cmsPreviewMetadata } from '@contenter/react/next';
import { previewConfig } from '@/cms/shell';
export const dynamic = 'force-dynamic';
export const metadata = cmsPreviewMetadata;
export default createCmsEditorPreview(previewConfig);
And four one-line API routes:
// src/app/api/cms/draft/route.ts — drafts for the preview, gated by a preview token
import { createCmsDraftRoute } from '@contenter/react/next';
import { cms } from '@/lib/cms';
export const GET = createCmsDraftRoute({ client: cms });
// src/app/api/cms/component-registry/route.ts — tells the editor which components you have
import { createComponentRegistryRoute } from '@contenter/react/next';
import { defaultComponentDefinitions } from '@contenter/react-components/definitions';
import { EDITOR_ORIGINS } from '@/lib/cms';
export const { GET, OPTIONS } = createComponentRegistryRoute({
definitions: defaultComponentDefinitions,
apiKey: process.env.CMS_API_KEY,
allowedOrigins: EDITOR_ORIGINS,
});
// src/app/api/cms/theme/[site]/cms-theme.css/route.ts — the theme as a stylesheet
import { createCmsThemeCssRoute } from '@contenter/react/next';
import { cms } from '@/lib/cms';
export const GET = createCmsThemeCssRoute({ client: cms });
// src/app/api/cms/revalidate/route.ts — refresh the cache on publish
import { createCmsRevalidateRoute } from '@contenter/react/next';
export const POST = createCmsRevalidateRoute({ secret: process.env.CMS_REVALIDATE_SECRET });
7. See it
npm run dev and open http://localhost:3000: the homepage of CMS_SITE in CMS_LOCALE, rendered with your components. A path with no CMS page renders your not-found.
8. Connect the editor
In the CMS, for the site and locale:
- Preview domain → your storefront's origin (
http://localhost:3000while developing). The editor loads/cms-editoron it. - Component registry →
https://your-storefront/api/cms/component-registry. - Revalidate target →
https://your-storefront/api/cms/revalidate, with the revalidate key asCMS_REVALIDATE_SECRETin your environment. See chapter 12.
Open a page in the editor. Your storefront appears in the preview, components outline on hover, and a click selects one for editing. If the preview stays blank, its diagnostics panel says why — see Live preview.
Credentials
A storefront holds two secrets. Both live in server-side environment variables, never in the browser bundle.
| Credential | Variable | Used for |
|---|---|---|
| CMS API key | CMS_API_KEY |
Reading content, the editor's preview route, the draft route, the component registry endpoint |
| Revalidate key | CMS_REVALIDATE_SECRET |
Accepting cache-refresh calls after a publish |
The CMS API key
Where: in the CMS, Settings → API key. It starts with cms_.
A static, read-only key for one tenant. Content reads present it (X-CMS-API-Key); because it does not change per request, responses stay cacheable by a CDN.
The editor also uses it to open your storefront: it loads /cms-editor?editMode=true&cmsApiKey=…, and the preview route compares that value with CMS_API_KEY before it renders anything unpublished. That is why the key must stay on the server — a copy in the browser bundle (NEXT_PUBLIC_CMS_API_KEY) hands every visitor the way into the preview route and every draft.
The browser never needs it. The preview route embeds a short-lived preview token signed with the key, and the draft route accepts that instead (see Live preview).
The revalidate key
Where: in the CMS, Settings → Revalidate key, generated there and entered as CMS_REVALIDATE_SECRET. It authenticates the call cms-api makes to your storefront after a publish, so a fresh page is visible in seconds rather than after the cache period. Without it, /api/cms/revalidate answers 503 and pages refresh when their cache period ends. See chapter 12.
It must not be the CMS API key: this endpoint changes cache state.
How the client sends them
createCmsClient({ apiKey }) sends the key as X-CMS-API-Key. Read content from your server, and let the browser talk only to your own routes.
Errors
- 404 → the getters return
null; render your own not-found page. - 401, 403, 429, 5xx →
CmsHttpErrorwithstatus,messageandurl, so you can tell a credential problem from an outage and, for example, serve a stale page on a 5xx.
import { CmsHttpError } from '@contenter/cms-client';
try {
return await cms.getPage(site, locale, url);
} catch (e) {
if (e instanceof CmsHttpError && e.status >= 500) return serveStale();
throw e;
}
Environment reference
cmsConfigFromEnv() reads these variables. createServerCmsClient() with no baseUrl, and createCmsClientFromEnv(), read them through it.
| Variable | Required | Meaning |
|---|---|---|
CMS_API_BASE_URL |
no | The cms-api base. Unset, it defaults to the hosted cms-api, https://api.cms-contenter.medienwerft.de/api — or, when CMS_TENANT (or NEXT_PUBLIC_EMPORIX_TENANT) is set, to the Emporix installation's function, https://api.emporix.io/cloud-functions/{tenant}/functions/contenter-cms-api. Set it for your own cms-api, or for an Emporix function created before fixed ids (its id is a UUID). |
CMS_API_KEY |
yes | The CMS API key. Server-only. |
CMS_SITE |
no | The site rendered where a route does not say. |
CMS_LOCALE |
no | The locale rendered where a route does not say. |
CMS_DEFAULT_LAYOUT_ID |
no | The layout the editor's preview falls back to. |
CMS_EDITOR_ORIGINS |
for preview | The editor's exact origin(s), separated by commas or spaces. Empty allows any origin — local development only. |
CMS_REVALIDATE_SECRET |
no | The revalidate key. Server-only. |
None of these needs a NEXT_PUBLIC_ or VITE_ prefix. For the non-secret ones (base URL, site, locale, layout, origins) a framework prefix is accepted as an alternative spelling — VITE_CMS_SITE, NUXT_PUBLIC_CMS_LOCALE — so a client-rendered app can configure itself the same way. The secrets are read only under the names above.
What it returns
const env = cmsConfigFromEnv();
env.client // pass to createCmsClient(), or use createCmsClientFromEnv()
env.site, env.locale, env.defaultLayoutId
env.editorOrigins // string[]
env.revalidateSecret
env.problems // string[] — what to change, in words
It never throws; everything wrong ends up in problems. Print them at startup. createCmsClientFromEnv() is the strict variant: it reads the environment on the first request rather than at import, warns once about every problem, and says once which default base URL it took (env.baseUrlDefault is 'hosted' or 'emporix' then).
The checks behind problems:
CMS_API_BASE_URLending in/storefront, or holding a{tenant}with no tenant set;- no
CMS_API_KEY; - a key in a
NEXT_PUBLIC_variable.
Older names
Storefronts built before this release used other names. They still work and print a one-time deprecation warning:
| Old | Now |
|---|---|
NEXT_PUBLIC_CMS_API_KEY, NEXT_PUBLIC_CMS_EDITOR_API_KEY |
CMS_API_KEY — and move it out of the browser bundle |
NEXT_PUBLIC_DEFAULT_SITE |
CMS_SITE |
VITE_CMS_API_URL |
CMS_API_BASE_URL (or VITE_CMS_API_BASE_URL) |
CMS_BACKEND |
nothing — it is no longer read |
Pages, layouts and slots
Shapes
getPage(site, locale, url) returns a ResolvedPage:
interface ResolvedPage {
page: CMSPage; // title, url, components (slotId -> CMSComponent[])
layout: CMSLayout | null; // contentSlots + components (may hold placeholders)
theme: CMSTheme | null; // { base_theme?, variables: { '--token': 'value' } }
resolvedSite: string; // may differ from requested via site fallbacks
resolvedLocale: string;
}
interface CMSComponent { id: string; type: string; props: Record<string, unknown>; children?: CMSComponent[]; }
Layout ↔ page merge
The layout provides the page chrome and declares where page content goes via
ContentPlaceholder components (props.placeholderId). The page provides the
content, keyed by slot id. resolvePageTree(resolved) merges them into one
ordered, framework-neutral RenderNode[]:
- Layout slots render in
contentSlotsorder. - Each
ContentPlaceholderis replaced in place by the page's components for the matchingplaceholderId. - Any page slot the layout never consumed is appended afterward (so content is never lost).
- With no layout, the page's slots render directly, in order.
<CmsPage> calls resolvePageTree and renders the result — you don't call it
yourself unless you want the neutral tree (e.g. for a non-React renderer).
The component registry
Every RenderNode.type is looked up in your registry; the matched component
receives the CMS props (spread), the resolved cmsNode, and rendered
children. Unknown types render a dev-only placeholder in development and
nothing in production — they never crash the page. See
component registry.
Theme
Every resolved page carries its site's theme — CSS custom properties the editor manages. How to emit them is in Themes.
Server vs client rendering
<CmsPage>(from@contenter/react) is RSC-safe — no hooks, no client JS. Use it for SSR/production.<CmsLivePage>(from@contenter/react/client) re-renders on live edits and is used inside the preview provider. It still SSRs, but ships client JS — use it only on the preview path.
Slotted composition
The whole-tree renderer (<CmsPage resolved registry>) renders a
resolved page top-to-bottom in one place. The slotted composition API instead lets you
author the page chrome in React and drop CMS-managed slots exactly where you want them —
a natural fit for Next.js App Router's split layout.tsx / page.tsx. Both APIs use the
same data and registry; pick per route.
// layout.tsx
<CmsLayout layoutId="default" locale={locale} site={site}>
<header><CmsContentSlot slot="top" /></header>
<main>{children}</main>
<footer><CmsContentSlot slot="bottom" /></footer>
</CmsLayout>
// page.tsx (nested under the layout)
<CmsPage slug={slug} locale={locale} site={site} searchParams={searchParams}>
<CmsContentSlot slot="main" />
</CmsPage>
Layout slots (top, bottom) and page slots (main) are defined independently — the
layout owns its chrome slots, the page owns its content slots. At render time
<CmsContentSlot slot> resolves a slot by id from a flat merged map; the layout/page
distinction survives only as an editor styling hint.
Setup
Three pieces:
1. A server factory bound to your CMS client (server-only module):
// src/cms/server.ts
import { createServerCms } from '@contenter/react/next';
import { cms, SITE, LOCALE } from '@/lib/cms';
export const { CmsLayout, CmsPage, resolvePage } = createServerCms({
client: cms,
site: SITE, // defaults; overridable per component / by editor searchParams
locale: LOCALE,
});
2. A client provider at the app root (the registry holds React components, so it can't
cross the RSC boundary — provide it client-side). <CmsProvider> also starts the
live-preview runtime when inside the editor:
// src/cms/Providers.tsx
'use client';
import { CmsProvider } from '@contenter/preview-react';
import { registry } from './registry';
// `editorOrigins` comes from the server: cmsConfigFromEnv().editorOrigins (CMS_EDITOR_ORIGINS).
export function Providers({ editorOrigins, children }) {
return (
<CmsProvider registry={registry} originAllowlist={editorOrigins}>
{children}
</CmsProvider>
);
}
Delivery-only (no live editing)? Use
<CmsRegistryProvider registry>from@contenter/react/clientinstead of<CmsProvider>.
3. Compose CmsLayout / CmsPage with <CmsContentSlot> (see the snippet at the top).
How layout + page compose (hoisting)
Next.js does not pass searchParams to layout.tsx, so CmsLayout always fetches the
published layout (a forced dynamic read would opt the route out of caching). CmsPage
does get searchParams, so it fetches the editor-aware page and its layout. Because the
chrome slots (top/bottom) live in layout.tsx — outside the page — the page hoists its
editor-aware layout up to the layout scope after hydration, and the chrome slots re-render with
the editor version. This is automatic; you don't wire anything.
Providers nest and merge: a nested (page) scope exposes {...parentSlots, ...ownSlots}
(inner wins). Slot ids don't collide across layout and page by convention, so the merge is
lossless and <CmsContentSlot slot> resolves uniformly wherever you place it.
CmsContentSlot
<CmsContentSlot slot="main" renderWhenEmpty={false} className="…" />
- Renders the slot's components through the registry.
- Skips rendering when the slot is empty (unless
renderWhenEmptyor editor mode). - In editor mode: a dashed outline (layout vs page slots differ, via CSS vars
--cms-slot-layout/--cms-slot-page) and an empty-slot placeholder; the container carriesdata-cms-slot-idso the editor can highlight it.
Live preview & metadata
CmsPage renders the LIVE version and reads no searchParams, so routes stay
static/ISR-cacheable. In the editor the client loads the draft and overlays it (see
Next.js integration); a
cmsLayout override is still honored for previewing a specific layout. Use the
factory's resolvePage in generateMetadata so it shares the page fetch with the render:
export async function generateMetadata({ params }) {
const { slug } = await params;
return cmsMetadata(await resolvePage({ slug }));
}
Pass emptyOnNoResult to render layout-only (no 404) when a page doesn't exist.
Live editing
Inside the CMS editor iframe, <CmsProvider> starts the preview runtime: UPDATE_SLOT
re-renders the affected <CmsContentSlot> live, UPDATE_LAYOUT/UPDATE_METADATA update slot
config/metadata, and click-to-edit / overlays / theme live-preview work as in the
live-preview guide. Live edits ride a shared overlay so a single edit
applies across the layout and page scopes at once.
When to use which
Whole-tree <CmsPage resolved registry> |
Slotted CmsLayout/CmsPage/CmsContentSlot |
|
|---|---|---|
| Chrome authored in | The CMS (layout + ContentPlaceholder) |
Your React (layout.tsx) |
| Slot placement | Automatic (placeholder injection) | Explicit (<CmsContentSlot slot>) |
| Best for | CMS-driven full pages | App-driven shells with CMS slots (Next layout/page split) |
Components and the registry
A registry maps a CMS component type to a React component.
Want something rendering today?
@contenter/react-componentsships 11 components with their prop schemas — enough for an editor that works before you have authored anything. See default components below; the rest of this page is how to write your own.
Two halves, and why it matters
A component type is two things: a React component that renders it, and a definition the editor reads to build its property panel. Keep them in separate modules:
src/cms/components/*.tsx 'use client' — the React components
src/cms/definitions/*.ts plain data — the CMSComponentTypeDefinitions
src/cms/registry.ts 'use client' — pairs them with defineComponent()
Not a style preference. The component-registry route serialises the definitions on the server,
and anything exported from a 'use client' module is an opaque reference there — so a route built
from the React registry publishes nothing:
// ✅ the form that works
createComponentRegistryRoute({ definitions: componentDefinitions })
// ❌ silently published `{"components":{}}` when the components are client modules
createComponentRegistryRoute({ registry })
The SDK now refuses to serve an unusable payload — it answers 503 with a message naming this as
the cause — but the fix is to publish the half that can be read. A definitions module must import
its prop helpers from @contenter/cms-protocol (which has no React, so it cannot become a client
module), never from a client kit that re-exports them.
Keep the two halves honest from your own test suite:
import { assertRegistryMatchesDefinitions } from '@contenter/react';
expect(assertRegistryMatchesDefinitions(registry, componentDefinitions)).toEqual([]);
Prop shorthands
P from @contenter/cms-protocol — one builder per field type, so a definition reads as a schema
rather than as object literals:
import { P, defineComponentType } from '@contenter/cms-protocol';
export const Hero = defineComponentType('Hero', {
label: 'Hero',
fieldDefinitions: { linkField: P.link('Link') },
props: {
headline: P.text('Headline', { required: true }),
image: P.media('Background'), // defaults to allowedTypes: ['image/*']
align: P.select('Alignment', [['start', 'Left'], ['center', 'Centred']]),
cta: P.ref('linkField', { label: 'Call to action' }),
items: P.array('Cards', P.object('Card', { title: P.text('Title') })),
},
defaultProps: { align: 'start' },
});
extra is spread last, so every default is overridable. P.ref + fieldDefinitions declares a
shape once and reuses it; the serialiser resolves the reference, so the editor sees the full shape.
Default components (@contenter/react-components)
import { defaultRegistry } from '@contenter/react-components';
import { defaultComponentDefinitions } from '@contenter/react-components/definitions';
Section, Container, Grid, Columns, Spacer, Hero, Heading, RichText, Image,
Button, ProductCard — between them exercising every field type the property panel can draw.
Inline styles reading --cms-* tokens with fallbacks; className/style merge last, so
overriding never needs !important.
Extend rather than fork — the definitions are exported individually:
export const definitions = {
...defaultComponentDefinitionMap,
Hero: { ...defaultComponentDefinitionMap.Hero, props: { ...defaultComponentDefinitionMap.Hero.props, eyebrow: P.text('Eyebrow') } },
PriceTable: { label: 'Price table', props: { /* … */ } },
};
export const registry = { ...defaultRegistry, PriceTable };
component and customSearch are deliberately unused by the set — the first because it composes
through children + allowedComponents, the second because it needs a storefront-supplied
resolver. See the package README.
import { defineComponent, cmsEditable, editableProps, type CmsComponentProps, type CmsRegistry } from '@contenter/react';
// A `media` field arrives as a { url, alt } object, not a bare URL — see “Media fields” below.
function Hero({ headline, image, cmsNode }: CmsComponentProps<{ headline?: string; image?: { url?: string; alt?: string } }>) {
return (
<section {...cmsEditable(cmsNode)} style={{ backgroundImage: image?.url ? `url(${image.url})` : undefined }}>
<h1 {...editableProps('headline', 'text')}>{headline}</h1>
</section>
);
}
export const registry: CmsRegistry = {
Hero: defineComponent(Hero, {
label: 'Hero',
props: {
headline: { label: 'Headline', type: 'text', required: true },
image: { label: 'Background', type: 'media', allowedTypes: ['image/*'] },
},
}),
// A bare component works too (minimal definition inferred):
// Text: Text,
};
CmsComponentProps<P>
Each component receives:
- the CMS
props(typed asP, spread onto the component), cmsNode— the resolvedRenderNode(id, type, slotId, …), andchildren— the already-rendered child nodes (for container types).
defineComponent(component, definition?)
Pairs a component with an editor type definition — label, a props schema
(field types: text | textarea | number | boolean | color | url | media | select | object | array | component | category | product), defaultProps, and
allowedComponents. This definition powers:
- the visual editor's property panel (via
REQUEST_COMPONENT_TYPES), and - AI-agent discovery through the MCP server.
Pass a mapProps: (props) => props transform alongside the definition to adapt the
raw CMS props before they reach your component at render time (see
Media fields). It's applied by the renderer only — never
serialized — so the editor still reads and writes the raw props.
getComponentTypeDefinitions(registry) derives the CMSComponentTypeDefinition[]
the preview runtime returns to the editor. To let the editor and MCP server
discover your types outside the editor iframe, publish the registry from
your storefront as an HTTP endpoint (Next.js) or a static file (Vite) — see
publishing the component registry.
Media fields
A media field (type: 'media') resolves to an object, not a bare URL — it's
what the media picker writes into the prop:
type MediaValue = { url?: string; alt?: string; filename?: string };
url is loadable directly by the browser: it is the cms-api /media-file proxy for
a private blob (edge-cached, served by unguessable id). Handle it one of two ways.
Consume the object — type the prop as the media value and read .url / .alt:
function Image({ src, cmsNode }: CmsComponentProps<{ src?: MediaValue }>) {
return <img {...cmsEditable(cmsNode)} {...editableProps('src', 'media')} src={src?.url} alt={src?.alt ?? ''} />;
}
Normalize with mapProps — keep a plain contract (e.g. imageUrl: string) and
flatten the object at render time, so the component itself stays media-shape-agnostic:
const mediaUrl = (v?: MediaValue | string) => (typeof v === 'string' ? v : v?.url ?? v?.filename);
ProductCard: defineComponent(ProductCard, {
label: 'Product card',
props: { imageUrl: { label: 'Image', type: 'media' } },
// The CMS delivers `imageUrl` as { url, alt }; hand the component a plain URL.
mapProps: (p) => ({ ...p, imageUrl: mediaUrl(p.imageUrl as MediaValue) }),
}),
Either way the editor edits the raw media object; mapProps only transforms the
value on its way into the component. The components in @contenter/react-components use
both patterns.
Editing helpers
Spread these so the component participates in visual editing. They always emit data-attributes (harmless in production); the preview runtime only attaches behavior when the editor is connected.
cmsEditable(cmsNode)— on the component root: makes the whole component selectable/highlightable.editableProps(fieldPath, fieldType)— on the element bound to one prop: makes it inline-editable.fieldPathis dot-notation into raw props (cta.label,items.2.title).
Unknown types & errors
- An unregistered
typerenders a dev placeholder / nothing in prod. Override via<CmsPage fallback={MyFallback} />. - Wrap subtrees with
CmsErrorBoundary(from@contenter/react/client) to isolate a throwing component. Error boundaries are client-only.
Themes
A theme is a set of CSS custom properties — --brand, --radius, --font-heading — that editors change in the CMS theme editor. Your stylesheet uses the variables; the CMS sets them. A site has a default theme and may have named alternatives.
Scoping
The variables are emitted as one CSS rule, scoped so they apply to the right part of the page:
| Theme | Selector |
|---|---|
has a base_theme |
.<base_theme> |
| the site's default | body[data-cms-site="<site>"] |
| a named theme | body[data-cms-theme="<name>"] |
So put the attributes on <body>. themeBodyAttributes(theme) returns the right ones (data-cms-site, plus data-cms-theme for a named theme):
<body {...themeBodyAttributes(theme)}>
Names and values are sanitised on the way out: a variable name that is not a valid custom property is dropped, and characters that could close the rule ({, }, <, >) are removed from values.
Two ways to emit it
As a stylesheet — recommended. The browser caches it, a CDN can serve it, and a Content Security Policy needs no nonce for it.
// app/api/cms/theme/[site]/cms-theme.css/route.ts
import { createCmsThemeCssRoute } from '@contenter/react/next';
import { cms } from '@/lib/cms';
export const GET = createCmsThemeCssRoute({ client: cms });
// in a layout
<CmsThemeLink site={SITE} basePath="/api/cms/theme" />
The route serves /{basePath}/{site}/cms-theme.css; cmsThemeCssUrl(site, options) builds the same URL wherever you need it. Its query parameters decide the caching:
| URL | Cache-Control |
For |
|---|---|---|
…/cms-theme.css |
max-age=0, s-maxage=10, stale-while-revalidate=60 |
a plain link — always correct, briefly cached |
…/cms-theme.css?v=<anything else> |
max-age=31536000, immutable |
a link that changes with each publish |
…/cms-theme.css?v=draft or ?v=live-preview |
private, no-store |
the editor |
…?theme=<name> |
as above | a named theme |
Pass a value that changes on publish as version to get the long cache. With no theme the route answers an empty stylesheet rather than a 404, so pages log no error; when cms-api is unreachable it answers 503 and is never cached.
Mount the route somewhere that does not collide with your page routes. A root-level app/[site]/cms-theme.css route next to a catch-all page route is legal in Next but easy to get wrong; under /api it cannot be.
Inline. <CmsThemeStyle theme={theme} /> renders the same rule as a <style> element during server rendering. Use it when you already have the theme (a resolved page carries it) and do not want an extra request.
<head><CmsThemeStyle theme={resolved.theme} /></head>
In the editor
While an editor changes the theme, the live preview applies the edits on top of your page in a separate <style id="cms-theme-overrides">. To show an editor what a token would be without their change, the preview briefly disables every CMS theme source and measures. It finds the inline <style data-cms-theme> and any stylesheet link to /cms-theme.css on its own. If you serve the persisted theme from some other path, name it with getThemeBaselineExclusions on the provider.
Which tokens the theme editor offers, and how it groups and labels them, comes from your storefront: pass getThemeTokenManifest to <CmsProvider>. Without one, the preview answers an empty manifest marked fallback: true. See Capabilities for the manifest's shape.
Next.js in depth
SSR-first LIVE delivery (static/ISR-cacheable) + in-iframe visual editing with a client-side draft overlay.
Server client
createServerCmsClient (from @contenter/react/next) wires Next caching:
published/live reads get { next: { revalidate, tags } } (cacheable); only an
explicit non-live version read forces no-store. Keep the API key server-only.
// src/lib/cms.ts — SERVER ONLY
import { createServerCmsClient } from '@contenter/react/next';
export const SITE = 'main';
export const LOCALE = 'en';
export const cms = createServerCmsClient({
baseUrl: process.env.CMS_API_BASE_URL!, // include /api on Vercel
apiKey: process.env.CMS_API_KEY, // never NEXT_PUBLIC_
revalidate: 60,
// `tags` defaults to `defaultCmsTags` (the canonical cms:site:* / cms:page:*
// grammar the CMS publishes against). Omit it unless you need to customise.
});
Slotted routes
Bind the server components to your client once, then compose with
<CmsContentSlot>. The routes read no searchParams and set no
force-dynamic, so they render LIVE and stay static/ISR:
// src/cms/server.ts — SERVER
import { createServerCms } from '@contenter/react/next';
import { cms, LOCALE, SITE } from '@/lib/cms';
export const { CmsLayout, CmsPage, resolvePage } = createServerCms({ client: cms, site: SITE, locale: LOCALE });
// src/app/(storefront)/[...slug]/page.tsx
import { CmsContentSlot } from '@contenter/react/client';
import { cmsMetadata } from '@contenter/react/next';
import { CmsPage, resolvePage } from '@/cms/server';
export async function generateMetadata({ params }: { params: Promise<{ slug: string[] }> }) {
return cmsMetadata(await resolvePage({ slug: (await params).slug }));
}
export default async function Page({ params }: { params: Promise<{ slug: string[] }> }) {
return (
<CmsPage slug={(await params).slug}>
<CmsContentSlot slot="main" />
</CmsPage>
);
}
Chrome slots (top/bottom) live in layout.tsx's <CmsLayout>; mount
<CmsProvider> (a client component) at the app root so the editor's live-preview
runtime starts inside the iframe. See examples/next-app for the full wiring.
resolvePageis a cached fetch shared withgenerateMetadata(dedup).- 404 →
CmsPagecallsnotFound(); passemptyOnNoResultto render layout-only. - The server renders LIVE; the editor overlays the draft client-side (next section).
Live preview & caching (drafts)
Public routes always render the LIVE version — even while the editor is open —
so they stay static/ISR-cacheable (no force-dynamic, no no-store). Editing
happens on a separate, gated preview route that renders nothing on the server:
the client loads the entity the editor named and overlays it before the iframe is
revealed, so previews show the draft with no live→draft flash — and an unpublished
page previews as easily as a live one.
Wiring (see examples/next-app):
- Don't read
searchParamson the render path of public routes and dropforce-dynamic, so they stay static.CmsPagedetects editor mode client-side from the iframe URL whensearchParamsis omitted. - Add the editor preview route at
/cms-editor— where all editing happens. Three lines, because the SDK ships it:// app/cms-editor/page.tsx import { createCmsEditorPreview, cmsPreviewMetadata } from '@contenter/react/next'; import { previewConfig } from '@/cms/shell'; export const dynamic = 'force-dynamic'; export const metadata = cmsPreviewMetadata; export default createCmsEditorPreview(previewConfig);previewConfigcarries the chrome your public routes already render — declare it once and both surfaces stay in step. Full snippet, including the gate, layout resolution and the requireddefaultLayoutId: live preview → the editor preview route. - Add the draft route — fetched with server credentials, never a browser key:
It answers// app/api/cms/draft/route.ts import { createCmsDraftRoute } from '@contenter/react/next'; import { cms } from '@/lib/cms'; export const GET = createCmsDraftRoute({ client: cms });?id=<page entity id>(what the preview route sends, viagetPageById— the only variant that resolves an unpublished page) as well as the?slug=form used on apreview_slugoverride. CmsProviderloads the draft from that route by default (draftEndpointdefaults to/api/cms/draft; passnullto disable, orloadDraftto override) and overlays it before the runtime announces readiness.
The editor keeps the iframe hidden behind a spinner until the storefront posts
IFRAME_READY — which the runtime now defers until the draft is applied (with a
~3s fallback timer) — so the reveal is flash-free.
SPA (no server route): use CmsPreviewProvider with baseUrl set; it fetches
the draft client-side with the editor-supplied cmsApiKey preview flag (present
only in the editor), never the published key.
Revalidation on publish
Live reads are tagged by default (see tags above), so a publish can purge
exactly the affected cache entries. Add the receiver route and the CMS POSTs the
tags to it on publish — content refreshes in seconds instead of waiting out the
revalidate TTL (which stays as a self-healing backstop):
// src/app/api/cms/revalidate/route.ts
import { createCmsRevalidateRoute } from '@contenter/react/next';
export const POST = createCmsRevalidateRoute({
secret: process.env.CMS_REVALIDATE_SECRET, // server-only; matches the tenant's revalidate key
});
- Opt-in / fail-safe. Without
CMS_REVALIDATE_SECRETthe route returns503(disabled) and the TTL is the only refresh path — nothing breaks. - Setup. Generate a revalidate key in CMS Settings, add the matching
per-site
…/api/cms/revalidateURL under Revalidate Targets, and copy the key into this storefront'sCMS_REVALIDATE_SECRET(e.g. Vercel project env) — the same lockstep asapi_key↔CMS_API_KEY. - Contract.
POST { tags?: string[], paths?: string[] }withAuthorization: Bearer <secret>; responds200/401/503.
Need to invalidate manually? Import the tag builders and call revalidateTag:
import { revalidateTag } from 'next/cache';
import { siteTag, pageTag } from '@contenter/react/next';
revalidateTag(siteTag('main'), 'max'); // flush a whole site
revalidateTag(pageTag('main', 'en', '/'), 'max'); // or one page
Theme placement
Render <CmsThemeStyle> in app/layout.tsx's <head> (or first in the page) and
set data-cms-site on <body> so the scoped CSS variables resolve — no FOUC.
Live preview
The CMS editor embeds your storefront in an iframe and drives it over
postMessage: live re-render as an editor types, click-to-select, inline
click-to-edit, theme live-preview, and product/category pickers. The SDK
implements the storefront half of that protocol so you get it for free.
Wire-level details are in the protocol reference.
Setup (React)
Two ways to wire it. Both are inert outside the editor (nothing to branch on
?editMode=true, no preview JS served to shoppers) and both overlay the draft
inside the editor before the iframe is revealed — so you always render the LIVE
page and let the provider handle preview.
Slotted (recommended — what the Next.js example uses). Mount <CmsProvider>
(from @contenter/preview-react) once at your app root, and render pages with the
slotted <CmsLayout> / <CmsPage> / <CmsContentSlot>. Inside the editor iframe
it starts the runtime and loads the draft from your draft route (draftEndpoint,
default /api/cms/draft), overlaying it.
'use client';
import { CmsProvider } from '@contenter/preview-react';
import { registry } from '@/cms/registry';
export function Providers({ children }: { children: React.ReactNode }) {
return (
<CmsProvider registry={registry} originAllowlist={['https://app.cms-contenter.medienwerft.de']}>
{children}
</CmsProvider>
);
}
Whole-tree (SPA / no slotted composition). Wrap <CmsLivePage> in
<CmsPreviewProvider>; set baseUrl (a browser-visible cms-api base) so it
fetches the draft client-side with the editor-supplied cmsApiKey flag — never
a published key — and overlays it:
'use client';
import { CmsLivePage } from '@contenter/react/client';
import { CmsPreviewProvider } from '@contenter/preview-react';
import { registry } from '@/cms/registry';
export function PreviewShell({ resolved }) {
return (
<CmsPreviewProvider
resolved={resolved}
registry={registry}
baseUrl={process.env.NEXT_PUBLIC_CMS_API_BASE_URL}
originAllowlist={['https://app.cms-contenter.medienwerft.de']} // the CMS editor origin(s)
onProductSearch={async (req) => searchProducts(req.query, req.categoryId)}
onCategoryTree={async () => getCategoryTree()}
onNavigate={(path) => { router.push(path); return true; }}
>
<CmsLivePage resolved={resolved} registry={registry} />
</CmsPreviewProvider>
);
}
Outside the editor the provider is inert — it just renders its children.
Activation
The runtime activates only when it is inside the editor iframe:
?editMode=true and framed (window.self !== window.top). The editor also
passes cmsApiKey, cmsSite, cmsLocale, cmsVersion, cmsLayout,
cmsThemeVersion, cmsReload — see the URL flags.
The editor preview route (required)
The editor previews everything on one dedicated storefront route — default
/cms-editor (DEFAULT_PREVIEW_PATH) — and names the entity to render in the
query string. Nothing is derived from the URL path, which is what lets an
unpublished page be previewed at all: public routes render LIVE and would 404.
| Flag | The preview renders |
|---|---|
cmsPage={page entity id} |
that page (…-draft / …-{timestamp} / bare = published) |
cmsLayout={layout entity id} |
that layout (and scopes live editing to layout slots) |
cmsComponent={component entity id} |
one Component Library entry alone — no layout, no header/footer |
| none of them | chrome only — enough for theme work |
You don't write it. createCmsEditorPreview is the route:
// app/cms-editor/page.tsx — the whole file
import { createCmsEditorPreview, cmsPreviewMetadata } from '@contenter/react/next';
import { previewConfig } from '@/cms/shell';
export const dynamic = 'force-dynamic';
export const metadata = cmsPreviewMetadata; // { robots: { index: false, follow: false } }
export default createCmsEditorPreview(previewConfig);
…where previewConfig is the chrome your public routes already render, declared once:
// src/cms/shell.tsx
import { CmsContentSlot } from '@contenter/react/client';
import type { CmsChromeArgs } from '@contenter/react/next';
import { CmsLayout, CmsPage, getLayout } from '@/cms/server';
import { cms, LOCALE, SITE } from '@/lib/cms';
import { Providers } from './Providers';
export function chrome({ children }: CmsChromeArgs) {
return (
<Providers>
<header><CmsContentSlot slot="top" /></header>
<main>{children}</main>
<footer><CmsContentSlot slot="bottom" /></footer>
</Providers>
);
}
export const previewConfig = {
cms: { CmsLayout, CmsPage, getLayout }, // from createServerCms
client: cms,
site: SITE,
locale: LOCALE,
defaultLayoutId: 'default', // required — see below
chrome,
};
// app/(storefront)/layout.tsx — the public side, same function
<CmsLayout layoutId="default">{chrome({ children, mode: 'public', layoutId: 'default' })}</CmsLayout>
What the factory does, and why each part is not yours to write
- Gates it.
isCmsPreviewAuthorized—editMode=trueplus a constant-timecmsApiKeycompare, failing closed in production — thennotFound(), never 403: a 403 confirms both that the route exists and that a key is configured. - Resolves the layout: the
cmsLayoutflag → the previewed page's ownlayout_id(one by-id read; the entity id already pins site, locale and version) → yourdefaultLayoutId. Then it verifies the layout exists, becauseCmsLayouttreats a miss as non-fatal and silent — right for a public route, wrong for a preview, where chrome-less is indistinguishable from a broken integration. defaultLayoutIdis required, with no default. A theme preview names no entity at all, and chrome is where most theme tokens are visible. Both reference storefronts used to hardcode a fallback and one disagreed with its own public route — it fell back to a layout name from an unset env var, which resolved to nothing and rendered chrome-less, silently.- Component mode is chrome-less, not "chrome optional". The editor previews one reusable block; a header/footer misrepresents it and swallows clicks meant for the entry. The factory renders no chrome at all rather than hiding it with CSS.
chromeis a shared value, not a preview option. The reason it exists: when both routes spell the composition out separately they drift, and the drift is invisible from either file. In the reference storefront the public route wrapped everything in a commerce context provider the preview route lacked — so brand-driven components rendered placeholders in the editor and real data once published.mode('public' | 'page' | 'layout' | 'theme' | 'component') is there for the rare thing that genuinely differs, like a cookie banner.- Content defaults to
<CmsPageSlots />— every page-content slot the page declares, in CMS order. A route namingmainrenders a slug-addressed template (product, category) empty, because that content lives entirely in the page's owncustom_slots. - Says what is wrong. When the preview cannot work, an in-iframe panel names the actual cause
instead of leaving the editor to report "no IFRAME_READY" for six different situations. Never
mentions the API key. Opt out with
diagnostics: false.
The two export const lines stay yours because Next requires route-segment config and metadata to
be static named exports of the page module — a factory cannot supply them. Reading searchParams
already opts the route out of static rendering; force-dynamic states the intent.
Notes
- Why the route owns its own shell instead of living in your chrome route group: a component
preview must render no chrome, and a Next
layout.tsxcannot readsearchParams— so a route inheriting a chrome layout could never tell which mode it is in. previewOnlyskips server resolution entirely — no live→draft flash, and nothing to resolve for a never-published page. The client fetches the named entity by id through/api/cms/draft:?resource=page&id=…,?resource=layout&id=…, or?resource=component&id=…. A library entry's content arrives as itsmainslot.- The path is configurable per tenant (Settings ▸ Integration ▸ Storefront
Endpoint Paths) for storefronts that can't use
/cms-editor. The default is what the SDK mounts, so a standard setup needs no configuration. preview_slugis the one exception: a page (or layout) carrying one is previewed on that real storefront path instead — the point being to see a slug-addressed template on a concrete instance (/product/{id}). The same flags ride along, so the client still overlays the same draft.
What you get
- Live re-render —
UPDATE_SLOTmessages flow into the renderer's live store;<CmsLivePage>re-renders in place. - Component types — the editor discovers your registry via
REQUEST_COMPONENT_TYPES(derived fromdefineComponentdefinitions). - Theme live-preview — CSS variable / base-theme changes apply instantly to a
single
<style id="cms-theme-overrides">node. If a route of yours also serves the persisted theme (say as a<link>), name it viagetThemeBaselineExclusions— otherwise the no-override baseline is measured with your stylesheet still applied and every token reports its overridden value as its baseline. - Click-to-edit — see below.
- Product / category pickers — via your
onProductSearch/onCategoryTree. - Navigation — in-preview link clicks are routed through the editor.
Click-to-edit
Two authoring helpers make components editable (both no-op behavior outside the editor; the attributes are always present):
cmsEditable(cmsNode)on the component root → the whole component is selectable (click) and highlightable (hover ring).editableProps(fieldPath, fieldType)on a field element:-
text/textarea/url→ double-click to edit in place. Reverts on Escape. The value is read fromtextContentonly (XSS-safe); the editor writes it back and re-broadcasts the slot.When it commits is the author's choice, not yours:
'blur'(the default — on Enter or when the field is left) or'live'(debounced while typing). Set your default withinlineCommit; the author overrides it from the editor's three-state menu, which can also switch inline editing off entirely. -
media/product/category→ double-click opens the editor's picker (viaINLINE_EDIT_REQUEST); the editor writes the chosen value back.
-
The editor is always the source of truth: your edits produce messages, the editor
mutates its model and re-broadcasts UPDATE_SLOT — the preview never writes
content directly.
Security — origin validation
The CMS editor posts with targetOrigin: '*'. The SDK closes that gap:
- Inbound messages are dropped unless they come from
window.parentand an allowed origin. - Replies target the captured parent origin — never
'*'.
Always set originAllowlist (or isAllowedOrigin) to your CMS editor
origin(s) in production. Without a policy the runtime warns and accepts any
origin (dev convenience only).
Also note cmsApiKey rides in the preview URL query string; the runtime scrubs it
from the visible URL after reading it. Prefer short-lived/scoped preview keys.
Non-React frameworks
Vue is already bound — do not hand-roll it. @contenter/preview-vue ships a
CmsPreviewProvider at prop parity with the React SPA one, @contenter/vue ships the slot
components, and there is a Nuxt entry point. See integrations/vue.md.
The one thing Vue lacks is an equivalent of React's slotted CmsProvider, so a Vue storefront
doing slotted composition uses the SPA provider.
For anything else, @contenter/preview-core is framework-agnostic: implement the PreviewHost
seam (component-type definitions, applySlots into your renderer's live state,
product/category callbacks) and mount createPreviewRuntime. @contenter/preview-react is the
reference binding.
Drafts and preview mode
Every read defaults to the published (live) page. Pass a version to fetch a
draft or a specific version:
await cms.getPage('main', 'en', 'faq'); // published (live)
await cms.getPage('main', 'en', 'faq', { version: 'draft' }); // current working draft
await cms.getPage('main', 'en', 'faq', { version: 'draft-1699887766' }); // a version id
await cms.getPageById('cms-page-faq-en-main-draft'); // by entity id (editor preview)
- The published page is integrity-verified and CDN-cacheable.
- A draft is unpublished — its layout and theme still resolve live, so a draft previews against the site's published chrome.
getPageByIdneeds no url, site, locale or version — the entity id carries all four. It's how the editor preview route resolves what it was told to render, and the only read that works for a page which has never been published (there is no live url to ask for). Never cached.
How editor preview works
Public routes always render the LIVE version on the server — even inside the
CMS editor — so they stay static/ISR-cacheable. Editing happens on a separate,
uncacheable route: the editor loads the storefront's
editor preview route
(default /cms-editor, gated on cmsApiKey), which renders no content
server-side and lets the client fetch the entity the editor named (cmsPage /
cmsLayout / cmsComponent) before the iframe is revealed — so there is no
live→draft flash, and an unpublished page previews like any other. See
Next.js integration → Live preview & caching.
Server-side draft reads happen only through a trusted seam, never a browser-held key:
- Next.js: a same-origin route from
createCmsDraftRoute({ client }), which fetches the draft with server credentials. It answers only a browser that carries the preview token:createCmsEditorPreviewembeds a short-lived token signed withCMS_API_KEYin the preview page, and the draft loader sends it back asX-Cms-Preview-Token. Both sides default toCMS_API_KEY, so there is nothing to wire. A hand-written preview route that does not embed the token must pass its ownauthorizeto the draft route — otherwise the preview showsHTTP 401in its diagnostics panel. - SPA (no server): the editor-supplied
cmsApiKeypreview flag (present only inside the editor), viaCmsPreviewProvider.
⚠️ Credential safety for drafts
A draft is readable with the same tenant credential as published content. So:
- Never put
CMS_API_KEYin the browser bundle (NEXT_PUBLIC_*,VITE_*). The editor sends the same key to the preview route, so a public copy opens the preview route — and every draft — to anyone. Keep it server-side; the preview token is what the browser carries instead. - Treat draft URLs / payloads as sensitive; don't link end users to them.
Published, read-only content in a browser bundle is fine — that's the intended use of the CDN-cacheable key.
The component registry endpoint
The CMS editor and the MCP server need to know which component types your storefront renders and what props they accept — so the editor's insert menu / property panel and AI authoring agents work against your real schema. Your storefront publishes this from its own registry, in a stable wire format:
{
"$schema": "https://emporix.io/cms/component-registry/v1",
"components": {
"Hero": { "type": "Hero", "label": "Hero", "props": { "headline": { "label": "Headline", "type": "text", "required": true } } },
"…": {}
}
}
The SDK derives this from your registry — $refs resolved, fieldDefinitions
inlined — via buildComponentRegistryPayload(registry) (from @contenter/react).
How you serve it depends on whether your frontend has a server.
Next.js (or any server / edge): a route
createComponentRegistryRoute (from @contenter/react/next) returns
Web-standard GET/OPTIONS handlers with CORS + optional key auth:
// app/api/cms/component-registry/route.ts
import { cmsConfigFromEnv } from '@contenter/cms-client';
import { createComponentRegistryRoute } from '@contenter/react/next';
import { componentDefinitions } from '@/cms/definitions';
export const { GET, OPTIONS } = createComponentRegistryRoute({
definitions: componentDefinitions, // NOT your React registry — see below
apiKey: process.env.CMS_API_KEY, // require a matching key when set
allowedOrigins: cmsConfigFromEnv().editorOrigins, // CORS for the editor (CMS_EDITOR_ORIGINS)
});
Pass
definitions, notregistry. This route serialises the prop schemas on the server, and anything exported from a'use client'module is an opaque reference there — so a payload derived from a registry of client components comes out empty. That used to be served as a200 {"components":{}}, whose only symptom was an empty property panel for every component in the editor. It is now a 503 naming the cause.{ registry }still works when the registry module really is server-readable (bare, hook-free components), but definitions are the form that always works: they are plain data. See component registry → two halves.
- Auth: when
apiKeyis set, callers must send it inX-Emporix-API-Key(the header the MCP server uses; override withapiKeyHeader). Unset = open (dev). Compared in constant time. Checked before the payload is built, so an unauthorized caller cannot learn that the registry is broken. - CORS: the editor calls this from the browser, so allowed origins are
echoed and preflight (
OPTIONS) is handled. - Caching:
Cache-Control: public, max-age=300(the MCP server also caches). - The handlers use only
Request/Response, so they work in Remix, Hono, edge, etc.
Point the CMS at https://your-store/api/cms/component-registry (CMS Settings →
component registries, per site).
Vite / static SPA: a build-time static file
A static SPA has no runtime server, so it can't serve a dynamic endpoint. Emit the same payload as a static asset at build time and let the CMS/MCP fetch it as a file:
// scripts/emit-registry.mts (run via predev / prebuild)
import { writeFile } from 'node:fs/promises';
import { buildComponentRegistryPayload } from '@contenter/react';
import { registry } from '../src/registry';
await writeFile('public/cms-component-registry.json', JSON.stringify(buildComponentRegistryPayload(registry), null, 2));
// package.json
"scripts": { "predev": "tsx scripts/emit-registry.mts", "prebuild": "tsx scripts/emit-registry.mts" }
Vite serves public/ at the root, so it's available at
/cms-component-registry.json in dev and copied into dist/ for production.
Set CORS via your static host's headers. (See examples/vite-app.)
Deploying the SPA behind a server or an edge/serverless function? Prefer the dynamic route (
createComponentRegistryRoute) there for auth + freshness.
Relationship to live preview
Inside the editor iframe the storefront answers REQUEST_COMPONENT_TYPES over
postMessage with the same definitions (getComponentTypeDefinitions(registry)).
The HTTP endpoint is the out-of-editor path (MCP agents, copy-to-locale,
site clone) — same registry, same schema, one source of truth.
Commerce pickers and prop decorators
The CMS stores content, not commerce data. When an editor picks a product for a teaser, the CMS stores the product's SKU; when a navigation shows categories, the CMS stores nothing about them at all. Your storefront supplies that data, in two places:
- Pickers — while an editor chooses a product or category, the editor asks your storefront (through the preview) what there is to choose from.
- Decorators — while a page renders, your storefront adds the data a component needs but the CMS does not store.
The CMS does not read your catalogue: the storefront is the one place that knows which products a shopper can see, at which price.
Pickers
Pass the handlers to <CmsProvider>. They run in the browser, inside the editor's preview, so they call your own API routes — not your commerce backend with a secret.
<CmsProvider
registry={registry}
originAllowlist={editorOrigins}
onProductSearch={async ({ query, categoryId, limit, site, locale }) =>
(await fetch(`/api/products?q=${encodeURIComponent(query)}&limit=${limit ?? 20}`)).json()
}
onCategoryTree={async () => (await fetch('/api/categories/tree')).json()}
onCustomSearch={async ({ searchId, query }) =>
searchId === 'manufacturer' ? (await fetch(`/api/manufacturers?q=${query}`)).json() : null
}
>
| Handler | Returns | Used by |
|---|---|---|
onProductSearch(request) |
ProductSearchResult[] — sku, name, optional imageUrl, price, categoryNames |
props declared with P.product(...) |
onCategoryTree() |
CategoryTreeNode[] — id, name, level, optional children, path, slug |
props declared with P.category(...) |
onCustomSearch(request) |
CustomSearchResult[] — id, label, optional sublabel, imageUrl — or null for a searchId you do not handle |
props declared with P.customSearch(label, searchId) |
A handler you leave out makes that picker report "not supported" in the editor instead of failing silently. onCustomSearch serves any entity you want editors to pick — manufacturers, stores, authors — without a CMS change: declare the prop, handle its searchId.
Decorators
A decorator receives a CMS component and returns extra props for it:
// src/cms/decorators.ts
import { createCmsDecorator } from '@contenter/cms-client';
export const decorate = createCmsDecorator({
byType: {
ProductTeaser: async (component, ctx) => ({
product: await getProduct(String(component.props.sku), ctx.locale),
}),
MainNavigation: async (_component, ctx) => ({
categories: await getCategoryTree(ctx.site),
}),
},
});
The result is a props patch, merged into the component's props; id, type, name and children cannot be overwritten. A decorator that throws or times out is logged and the component renders undecorated — a page with a missing teaser image beats a 500.
Wire it in both places
// server: every server-rendered read
createServerCms({ client: cms, decorate });
createCmsDraftRoute({ client: cms, decorate });
// client: every editor push
<CmsProvider registry={registry} decorate={decorate} decorateScope={{ site, locale }}>
Both are required. The editor sends the raw CMS content on every change, so whatever the server added is missing from that push. Wire only the server, and a decorated component loses its data the moment an editor types into it.
ctx.phase is 'server' or 'client'. A decorator may use a secret on the server; in the browser it must go through your own API. A decorator that cannot work in a phase returns null for it.
Caching
The SDK caches nothing for you, because only you know whether two components of one type need the same data. Wrap your reads in your framework's cache (React cache(), your data cache). For per-render deduplication, createCmsDecorator({ cacheKey }) keys results within one render pass and discards them afterwards.
Caching, revalidation and webhooks
The CMS tells other systems when content changes. An admin registers a receiver under Settings → Webhooks: a URL, the events it wants, optionally the sites it cares about, and how the CMS authenticates to it. From then on every matching change is POSTed there as a small JSON event.
Events
An event type is <kind>.<action>.
| Kind | |
|---|---|
page |
Pages |
layout |
Layouts |
theme |
Themes |
component |
Component Library entries |
| Action | Sent when |
|---|---|
created |
A new draft is created, including a page copied to another locale or site. |
updated |
A draft is saved, or a new draft is started from the live version. |
deleted |
The entity is deleted. |
submitted |
The draft is submitted for approval. |
withdrawn |
A pending draft is taken back out of approval. |
approved |
An approver approves the pending draft. |
rejected |
An approver rejects it. The reason is in data.approval.reason when one was given. |
published |
The draft goes live. |
restored |
An older version is restored, which also publishes it. |
A webhook subscribes with exact types (page.published), a whole kind (page.*) or
everything (*). A wildcard also covers event types added in later releases.
Changes made by the AI assistant and through the MCP server raise the same events, with the
agent's user as the actor. Deleting a single archived version, folder changes, media and
settings changes do not raise events yet. One exception: when a new folder takes over the path
of a page, the page is archived and leaves the website, and that raises page.deleted.
Test sends
Send test in the UI sends, by default, a webhook.test event with empty data — a
connection check. Pick any event type the webhook subscribes to instead, and it sends a
sample of that event: the same envelope, headers, auth and signature as the real thing, with
data in exactly that event's shape. Use it to build and debug a handler without waiting for
somebody to publish a page. Show what was sent in the UI displays the exact body.
Every test send carries "test": true in the envelope, and a sample's ids name nothing that
exists (cms-page-example-en-<site>). Real events never carry test, so a receiver that should
ignore tests can check that one field:
{ "id": "evt_…", "type": "page.published", "test": true, "…": "…",
"data": { "kind": "page", "id": "cms-page-example-en-shop", "baseId": "cms-page-example-en-shop",
"site": "shop", "locale": "en", "slug": "example", "name": "Example page" } }
In the UI, the sample's site is the webhook's first site, or, when the webhook listens to every
site, the first site in the CMS. Test sends are not logged and do not affect the webhook's health.
The same is available over the API: POST /webhooks/{id}/test with an optional
{ "event": "page.published", "site": "shop" } responds with the attempt result and the
payload it sent. Without site, the sample uses the webhook's first site, or example.
The request
POST /your/endpoint HTTP/1.1
content-type: application/json
user-agent: Contenter-Webhooks/1
webhook-id: evt_3f2c9a61d0e44b8c9a1e0d3b7c5f2a18
webhook-timestamp: 1790582400
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=
authorization: Basic Y21zOnNlY3JldA==
{
"id": "evt_3f2c9a61d0e44b8c9a1e0d3b7c5f2a18",
"type": "page.rejected",
"occurredAt": "2026-09-28T10:00:00.000Z",
"tenant": "acme",
"actor": { "id": "usr_8Hc2…" },
"data": {
"kind": "page",
"id": "cms-page-summer-sale-en-shop-draft",
"baseId": "cms-page-summer-sale-en-shop",
"site": "shop",
"locale": "en",
"slug": "summer-sale",
"name": "Summer sale",
"approval": { "status": "rejected", "reason": "Wrong price in the hero" }
}
}
The body is deliberately small, and it does not include the content. Use data.baseId to fetch
the entity from the API, so a slow or retried delivery can never hand you stale content.
The schema is also published as the contentLifecycle entry under webhooks in
the CMS API's /openapi.json.
Authentication
Each webhook uses one of these:
| Setting | Header the CMS sends |
|---|---|
| None | — |
| Custom header | <name>: <value>, e.g. X-Api-Key: … |
| Basic auth | Authorization: Basic base64(username:password) |
| Bearer token | Authorization: Bearer <token> |
Secrets are stored encrypted and are never shown again after saving. To change one, type a new
value. The header name cannot be one the CMS sets itself (host, content-*, user-agent,
webhook-*).
Signing can be switched on as well, and is recommended: it proves that a request came from
the CMS and has not been altered, which the auth header alone cannot. It follows the
Standard Webhooks specification, so any of its libraries
can verify it. The signing secret (whsec_…) is shown once, when signing is switched on or the
secret is rotated.
Verifying a signature (Node)
import { createHmac, timingSafeEqual } from 'node:crypto';
export function verifyCmsWebhook(secret: string, headers: Headers, rawBody: string): boolean {
const id = headers.get('webhook-id');
const ts = headers.get('webhook-timestamp');
const sigs = headers.get('webhook-signature');
if (!id || !ts || !sigs) return false;
// Refuse anything older than five minutes: a replayed request carries an old timestamp.
if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const expected = createHmac('sha256', key).update(`${id}.${ts}.${rawBody}`).digest();
return sigs.split(' ').some((entry) => {
const [version, sig] = entry.split(',');
const given = Buffer.from(sig ?? '', 'base64');
return version === 'v1' && given.length === expected.length && timingSafeEqual(given, expected);
});
}
Sign over the raw body, exactly as it was received. Parsing and re-serialising the JSON changes the bytes and breaks the signature.
Delivery and retries
- Answer
2xxwithin 3 seconds. The first attempt happens during the editor's save or publish call, so a slow receiver slows the editor down. Queue the work and acknowledge immediately. - Anything else is retried: a non-2xx status, a timeout, a connection error, or a redirect. Redirects are never followed. Retries are sent after 1 min, 5 min, 30 min, 2 h, 6 h, 12 h and 24 h. After that the delivery is marked failed for good.
- De-duplicate on
webhook-id. A retry, and a manual redelivery from the UI, carry the same id as the original. - Order is not guaranteed once a retry is involved. Use
occurredAtif order matters. - A webhook that fails continuously for 72 hours is switched off, with a note saying so in the UI. Switching it back on resets the failure count.
- The delivery log keeps every attempt for 30 days: payload, status, the first 1 KB of the response, and the error. Any entry can be redelivered from there.
URLs must be https and must not point at private or loopback addresses. This is checked when
the webhook is saved, and the hostname is resolved and checked again before every attempt.
Running it
| Variable (cms-api) | Purpose |
|---|---|
CMS_WEBHOOK_ENCRYPTION_KEY |
Encrypts webhook credentials at rest. Any secret of at least 16 characters. Without it, webhooks that carry a secret or a signature cannot be saved (503). |
CRON_SECRET |
Guards GET /cron, which runs the retry sweep. Without it, the route does not exist. |
CMS_WEBHOOK_ALLOW_INSECURE |
Development only. Allows http:// and private addresses, e.g. a receiver on localhost. |
On Vercel, cms-api/vercel.json schedules /api/cron every five minutes, and Vercel sends
Authorization: Bearer $CRON_SECRET by itself once the variable is set on the project.
Schedules more frequent than daily need a Vercel Pro plan. On a daily-only plan retries still
happen, just later. On Google Cloud Functions, create a Cloud Scheduler job that calls /cron
with the same header.
The feature is plan-gated as webhooks (on from the trial tier; operators can override it per
tenant).
Vite and client-only React
Client-side delivery for a fully headless SPA.
import { useLocation } from 'react-router-dom';
import { CmsPage, CmsThemeStyle, createCmsClient } from '@contenter/react';
import { useCmsPage } from '@contenter/react/client';
import { registry } from './registry';
const cms = createCmsClient({
baseUrl: import.meta.env.VITE_CMS_API_BASE_URL, // include /api on the hosted cms-api
apiKey: import.meta.env.VITE_CMS_API_KEY, // read the warning below first
});
export function App() {
const url = useLocation().pathname.replace(/^\/+/, '');
const { data, error, isLoading } = useCmsPage(cms, 'main', 'en', url);
if (isLoading) return <p>Loading…</p>;
if (error) return <p>Error: {error.message}</p>;
if (!data) return <h1>404</h1>;
return <><CmsThemeStyle theme={data.theme} /><CmsPage resolved={data} registry={registry} /></>;
}
- Set
data-cms-site="<site>"on<body>inindex.htmlso the theme selector resolves. useCmsPageis dependency-free (fetch + AbortController), re-fetches when its args change, and exposesrefetch.
⚠️ Credentials
A client-rendered app has no server, so whatever credential it uses is in every visitor's browser. Know what that gives away:
- The CMS API key reads drafts too, not only published content, and it is the key the editor
presents to any Next storefront's preview route. Shipping it in a
VITE_*variable is a decision to make those readable by anyone.
The safe shape is a small same-origin proxy that holds the key and forwards only the published
reads you need — createPageIndexHandler and the other Web-standard handlers in
@contenter/cms-client run in any serverless function. If you do ship the key, never preview
drafts with it client-side. See
drafts and preview mode.
SEO
This is the CSR path (no server render). For SEO/social metadata prefer the Next.js integration.
Vue and Nuxt
@contenter/vue renders CMS content in Vue, and @contenter/preview-vue wires the
CMS editor's visual editing. Both sit on the same framework-neutral core as the
React SDK — @contenter/cms-client (delivery + the RenderNode tree, incl. the
shared live store) and @contenter/preview-core (the entire preview runtime) — so
the same CMS content, the same registry keys and the same editor drive both
renderers.
Two rendering models, same as React — pick per route:
| Model | You get | Use when |
|---|---|---|
Whole-tree <CmsPage> |
the CMS decides the entire tree (layout+page merged) | simple CMS-owned pages |
Slotted <CmsSlotScope> + <CmsContentSlot> |
you author the chrome and drop CMS slots by id | you want control over markup, or chrome + page content in one shell |
Status. Delivery, rendering, slotted composition, visual editing, the Vite/CSR path and the Nuxt/Nitro server layer are implemented. Not yet: a published Nuxt module (the server layer is plain functions + Web handlers you wire yourself — three route files).
Install
npm i @contenter/vue @contenter/preview-vue
Vue 3.4+ is a peer. The packages ship h()-based component definitions (no SFCs),
so they impose no compiler requirements beyond your app's own.
Registry
Map CMS component types to Vue components. defineCmsComponent attaches the editor
type definition, so the editor and the MCP server can discover your props:
// src/cms/registry.ts
import { defineCmsComponent, type CmsRegistry } from '@contenter/vue';
import Hero from './components/Hero.vue';
import RichText from './components/RichText.vue';
export const registry = {
Hero: defineCmsComponent(Hero, {
label: 'Hero',
props: { headline: { label: 'Headline', type: 'text' } },
}),
RichText, // a bare component is fine
} satisfies CmsRegistry;
Keep the keys identical to a React storefront's registry and the same content
renders in both. (It's defineCmsComponent, not defineComponent, so it never
collides with Vue's own.)
Render a page
<script setup lang="ts">
import { CmsPage, CmsThemeStyle, createCmsClient } from '@contenter/vue';
import { registry } from '@/cms/registry';
const cms = createCmsClient({ baseUrl: import.meta.env.VITE_CMS_API_BASE_URL, apiKey: '…' });
const resolved = await cms.getPage('main', 'en', '/');
</script>
<template>
<CmsThemeStyle :theme="resolved?.theme" />
<CmsPage v-if="resolved" :resolved="resolved" :registry="registry" />
</template>
Vite (CSR, no server)
A plain Vue + Vite SPA is fully supported — no server, no SSR:
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { CmsPage, CmsThemeStyle, createCmsClient, useCmsPage } from '@contenter/vue';
import { registry } from '@/cms/registry';
const cms = createCmsClient({
baseUrl: import.meta.env.VITE_CMS_API_BASE_URL,
apiKey: import.meta.env.VITE_CMS_API_KEY, // a browser-held key — see Vite → Credentials
});
const route = useRoute();
// Pass a getter (or ref) so navigation re-fetches; a plain string is read once.
const { data, isLoading } = useCmsPage(cms, SITE, LOCALE, () => route.path);
</script>
<template>
<p v-if="isLoading">Loading…</p>
<template v-else-if="data">
<CmsThemeStyle :theme="data.theme" />
<CmsPage :resolved="data" :registry="registry" />
</template>
<p v-else>404 — no published CMS page matched this URL.</p>
</template>
Every useCmsPage input accepts a value, ref or getter and is read reactively;
the in-flight request is aborted when inputs change or the component unmounts.
Three things specific to CSR:
- cms-api is browser-callable. It reflects the request
Origin, allowsX-CMS-API-Key, and answers preflight — so reading directly from the browser works, no proxy needed. - The bundled key is public. Use it for published content only. Drafts are
not read with it: inside the editor
<CmsPreviewProvider baseUrl>uses thecmsApiKeythe editor puts on the preview URL, which never ships in your bundle. - Publish the registry as a static file. With no server, emit
buildComponentRegistryPayload(registry)topublic/cms-component-registry.jsonin a prebuild step (the React Vite example does exactly this) and point CMS Settings ▸ Component registries at that URL.
For the editor preview route in an SPA: add /cms-editor to your router and make
the host serve index.html for it (Vite dev does; on a static host add a rewrite).
A server-side gate is impossible without a server — and unnecessary here: the route
renders nothing unless the editor supplies cmsApiKey in the URL, because that's
what the draft loader needs. No unpublished content is reachable without it.
Slotted composition — author your own chrome
<CmsPage> renders whatever the CMS says, in the CMS's order. When you want the
markup to be yours and only the contents to come from the CMS, wrap your shell in
<CmsSlotScope> and place <CmsContentSlot> wherever a slot belongs:
<script setup lang="ts">
import { CmsSlotScope, CmsContentSlot, provideCmsRegistry } from '@contenter/vue';
import { registry } from '@/cms/registry';
const props = defineProps<{ layout: CMSLayout; page: CMSPage }>();
provideCmsRegistry(registry); // or wrap in <CmsRegistryProvider :registry>
</script>
<template>
<CmsSlotScope kind="layout" :layout="props.layout">
<header class="site-header">
<MyLogo />
<CmsContentSlot slot="top" />
</header>
<CmsSlotScope kind="page" :page="props.page" :layout="props.page.layout">
<main class="prose"><CmsContentSlot slot="main" /></main>
</CmsSlotScope>
<footer><CmsContentSlot slot="bottom" /></footer>
</CmsSlotScope>
</template>
That's the same three-piece shape as the React SDK (CmsLayout / CmsPage /
CmsContentSlot) — an outer scope for chrome, an inner scope for page content. What the
scope does:
- seed ⊕ overlay — SSR props are the seed; the shared
cmsSlotOverlay(written by the preview runtime) overrides per slot, so live edits win immediately. - parent merge, inner wins — a nested scope sees the parent's slots plus its own; on a slot-id collision its own wins.
- layout hoist — the page scope hands its (editor-aware) layout up to the outermost scope, which re-derives chrome from it. So a draft layout arriving with the page updates the header/footer too.
- editor affordances — in the editor each slot gets a dashed outline (purple =
layout, green = page), empty slots get a placeholder, and every wrapper carries
data-cms-slot-idfor the runtime to highlight. Outside the editor an empty slot renders nothing (renderWhenEmptyoverrides).
useCmsSlots() exposes the merged scope (slotComponents, slotConfig,
metadata, isEditorMode) as a computed ref if you need to branch on it. Unlike
React there's no server/client split to manage — one provide/inject scope serves
SSR and the browser.
Nuxt / Nitro (SSR)
@contenter/vue/nuxt is the server half. It imports nothing from Nuxt — every
export is a pure function or a Web-standard Request → Response handler you mount
with fromWebHandler — so it can't drift with Nuxt internals and needs no h3 peer.
// server/utils/cms.ts
import { createServerCmsClient } from '@contenter/vue/nuxt';
export const cms = createServerCmsClient({
baseUrl: process.env.CMS_API_BASE_URL!, // include /api on Vercel
apiKey: process.env.CMS_API_KEY, // server-only; never runtimeConfig.public
});
Caching differs from Next by design: Nitro caches at the route/function level
(routeRules, defineCachedEventHandler, cachedFunction), so the client's job is
to make sure the reads that must never be cached say so — the editor's by-id
reads and any explicit draft get cache: 'no-store' automatically. For your own
cache keys / CDN purges, cmsReadTags(ctx) gives the canonical
cms:site:* / cms:page:* grammar the CMS publishes against.
Three route files and one head call:
// server/routes/api/cms/draft.get.ts — the editor's draft loader
import { createCmsDraftHandler } from '@contenter/vue/nuxt';
import { cms } from '~/server/utils/cms';
export default fromWebHandler(createCmsDraftHandler({ client: cms }));
// server/routes/api/cms/component-registry.get.ts
// `definitions`, not `registry`: this runs in Nitro, and importing a registry of SFC/async
// components here drags their browser half into the server bundle — while a `defineAsyncComponent`
// entry carries no readable definition at all. Definitions are plain data. An unusable payload is a
// 503 rather than a 200 with an empty object.
import { createCmsRegistryHandler } from '@contenter/vue/nuxt';
import { componentDefinitions } from '~/cms/definitions';
export default fromWebHandler(
createCmsRegistryHandler({ definitions: componentDefinitions, apiKey: process.env.CMS_API_KEY }).GET,
);
// server/routes/api/cms/revalidate.post.ts — the publish webhook
import { createCmsRevalidateHandler } from '@contenter/vue/nuxt';
export default fromWebHandler(
createCmsRevalidateHandler({
secret: process.env.CMS_REVALIDATE_SECRET, // unset ⇒ disabled (503), fails safe
invalidate: async ({ tags, paths }) => {
// Your layer: purge a CDN, sweep useStorage('cache') keys, bump a version…
},
}),
);
// in a page component
useHead(cmsHead(resolved)); // title + description
The paths above are the defaults the CMS assumes (/api/cms/component-registry,
/api/cms/revalidate), so a standard Nuxt storefront needs no endpoint
configuration in CMS Settings.
Make components editable
The DOM contract is shared with React, so the helpers are the same — bound with
v-bind instead of spread:
<script setup lang="ts">
import { cmsEditable, editableProps, type CmsComponentProps } from '@contenter/vue';
const props = defineProps<CmsComponentProps<{ headline: string }>>();
</script>
<template>
<section v-bind="cmsEditable(props.cmsNode)">
<h1 v-bind="editableProps('headline', 'text')">{{ props.headline }}</h1>
</section>
</template>
Visual editing
Wrap the renderer in <CmsPreviewProvider> and render <CmsLivePage> off a live
store, so editor keystrokes re-render in place. Outside the editor iframe the
provider is inert — it renders its slot and ships no preview behavior to
shoppers.
<script setup lang="ts">
import { CmsLivePage, createLiveStore, useLiveSlots, type ResolvedPage } from '@contenter/vue';
import { CmsPreviewProvider } from '@contenter/preview-vue';
import { registry } from '@/cms/registry';
const props = defineProps<{ resolved: ResolvedPage }>();
const store = createLiveStore(props.resolved.page.components);
const liveSlots = useLiveSlots(store);
</script>
<template>
<CmsPreviewProvider
:resolved="props.resolved"
:registry="registry"
:store="store"
:origin-allowlist="[CMS_EDITOR_ORIGIN]"
:base-url="CMS_API_BASE_URL"
>
<CmsLivePage :resolved="props.resolved" :registry="registry" :live-slots="liveSlots" />
</CmsPreviewProvider>
</template>
- Pass the same
storeto the provider anduseLiveSlots— that shared instance is what turns an editor message into a re-render. originAllowlistis required in production — it's the origin check on the editor's postMessages. Without it the runtime warns and accepts any origin (dev only). See live preview → security.baseUrllets the provider load the draft client-side with the editor-suppliedcmsApiKeyflag (present only inside the editor) — never your published key. It resolves whatever the editor named:cmsPage(a page entity id),cmsComponent(a Component Library entry), else the current path.useIsPreview()returns a ref that isfalseon the server and until mount, so edit affordances never cause a hydration mismatch.
The editor preview route
The editor previews everything on one gated storefront route (default
/cms-editor) — full contract in
live preview → the editor preview route.
In Vue/Nuxt: add that route, gate it, never cache it, mark it noindex, and render
the shell inside <CmsPreviewProvider> so the client resolves the named entity.
isCmsPreviewAuthorized is re-exported from @contenter/vue/nuxt (it lives in the
neutral wire package, so it is not React-specific):
<!-- pages/cms-editor.vue -->
<script setup lang="ts">
import { isCmsPreviewAuthorized } from '@contenter/vue/nuxt';
const route = useRoute();
if (!isCmsPreviewAuthorized(route.query as Record<string, string>, useRuntimeConfig().cmsApiKey)) {
throw createError({ statusCode: 404, statusMessage: 'Not Found' });
}
useHead({ meta: [{ name: 'robots', content: 'noindex, nofollow' }] });
definePageMeta({ layout: 'storefront' });
</script>
<template>
<!-- Nothing resolved server-side: the client loads cmsPage / cmsComponent -->
<CmsPreviewProvider :resolved="emptyResolved" :registry="registry" :store="store" :base-url="cmsApiBase">
<CmsSlotScope kind="page" is-editor-mode>
<CmsContentSlot slot="main" />
</CmsSlotScope>
</CmsPreviewProvider>
</template>
Add routeRules: { '/cms-editor': { cache: false } } (or ssr: false) so it is
never cached.
Component mode renders no chrome. When cmsComponent is on the URL, render the
entry alone — skip the layout/header/footer entirely (don't hide them with CSS). In
Vue this is trivial: the page reads the query itself, so branch in the template
(definePageMeta({ layout: false }) when a component id is present, or compose the
chrome conditionally). No Next-style route-group constraint applies here, because a
Vue page can read its own query.
Component registry endpoint
Publish your component types so the editor and MCP server discover them:
// Nuxt: server/routes/api/cms/component-registry.get.ts
import { buildComponentRegistryPayload } from '@contenter/vue';
import { registry } from '~/cms/registry';
export default defineEventHandler(() => buildComponentRegistryPayload(registry));
/api/cms/component-registry is the path the CMS assumes by default. See
publishing the component registry.
Troubleshooting
404 for every page / getPage returns null
Check baseUrl includes /api on the Vercel deployment, and that site/locale
match a published page. getPage returns null on 404 by design.
401 Unauthorized
Missing/invalid credential. Verify CMS_API_KEY (Settings → API key) or your
bearer token + tenant. The key is tenant-scoped and read-only.
baseUrl double-append warning
You passed a base ending in /storefront. Pass only the cms-api base — the client
appends /storefront/... itself.
Theme not applied
<CmsThemeStyle> must be rendered and <body> must carry
data-cms-site="<site>" (unless the theme sets base_theme, whose class you must
apply). Confirm resolved.theme is non-null.
Preview iframe never connects
The runtime activates only when ?editMode=true and framed. Confirm the editor's
preview domain points at your app and the URL carries editMode=true. Also check
the editor preview route
exists at the configured path (default /cms-editor) — the editor loads that
route for every preview, and its own gate 404s when cmsApiKey doesn't match the
storefront's key. The editor reveals the iframe and banners after ~8 s of silence.
Preview shows nothing / empty slots
The preview route renders no content server-side (previewOnly); the client loads
whatever the editor named — cmsPage (page entity id), cmsLayout, or
cmsComponent. Check the draft route resolves an id (getPageById), and that
the flag is actually on the URL. No flag at all is legitimately chrome-only (the
theme editor with no page selected).
Preview messages ignored / "accepting messages from any origin" warning
Set originAllowlist (or isAllowedOrigin) to your CMS editor origin. Inbound
messages from other origins are dropped; without a policy the runtime warns and
accepts all (dev only).
Live edits don't re-render
Use <CmsLivePage> (from @contenter/react/client) inside <CmsPreviewProvider>
on the preview path — the plain server <CmsPage> does not subscribe to live
updates.
Overlay ring misaligned
The overlay measures the element carrying data-cms-component-id. Ensure your
component root spreads cmsEditable(cmsNode) and renders a real box (not
display: contents).
"use client" / RSC errors in Next
Import client pieces from @contenter/react/client and @contenter/preview-react
(both are client entries). @contenter/react root, @contenter/react/next, and
@contenter/cms-client are server-safe.
Draft content leaking Never fetch drafts client-side with a browser-exposed key. Do draft preview server-side or via a same-origin proxy. See draft & preview mode.
Capabilities reference
Every capability the @contenter/* SDK provides, the export that provides it, and how you turn it
on. The third column is the one that matters: several capabilities exist but are inert, or default
to a permissive posture, until you configure them. A capability you did not configure is not a
capability you have.
The topic guides teach; this page enumerates. If something is not on this page, the SDK does not do it — see What the SDK deliberately does not do for the notable absences and what to do instead.
Packages and entry points
Nine packages, fourteen entry points.
| Package | Entry points | Runtime deps |
|---|---|---|
@contenter/cms-protocol |
. |
none |
@contenter/cms-client |
. |
none |
@contenter/react |
. · ./client · ./next |
react (peer), next (optional peer) |
@contenter/react-components |
. · ./definitions |
react, @contenter/react (peers) |
@contenter/preview-core |
. |
none (DOM) |
@contenter/preview-react |
. |
react, @contenter/react (peers) |
@contenter/vue |
. · ./nuxt |
vue (peer) |
@contenter/preview-vue |
. |
vue, @contenter/vue (peers) |
@contenter/mock-commerce |
. · ./data |
none |
Two boundaries to know before reading further:
@contenter/react/clientis a Client Component boundary. Importing it marks the module'use client'. This is why component definitions (plain data) and component implementations (React) ship as separate entry points everywhere — see the component registry.@contenter/cms-protocoland@contenter/cms-clientareplatform: 'neutral'and zero-dep. Anything in them is available to every framework binding, which is why the framework-neutral half of a capability always lives there.
Delivery & rendering
| Capability | Surface | Configured how |
|---|---|---|
| Fetch a published or draft page | createCmsClient({ baseUrl, apiKey, fetch?, headers? }) → getPage(site, locale, url, { version? }) |
baseUrl includes /api on Vercel. version: 'draft' reads unpublished content. |
| Fetch by id, layout, theme, page index | getPageById · getComponentById · getLayout · getTheme · getPageIndex |
— |
| Turn a page bundle into a render tree | resolvePageTree(resolved) → RenderNode[] |
Pure and synchronous. Merges layout + page slots via mergePageSlots. |
| Whole-tree render | <CmsPage resolved registry> (@contenter/react, @contenter/vue) |
One component renders everything. Simplest; use when your route owns the whole page. |
| Slotted composition | createServerCms({ client, site?, locale? }) → { CmsLayout, CmsPage, resolvePage, getLayout } (@contenter/react/next); the slots come from <CmsContentSlot> in /client |
Fits Next's layout.tsx/page.tsx split. Per-render scope overrides come from props and the cmsSite/cmsLocale flags. See slotted composition. |
| Render every slot a page declares | <CmsPageSlots /> (@contenter/react/client) |
Prefer over a hardcoded slot="main" — a page's own custom_slots is how slug-addressed templates are built, and a route naming one slot renders those pages empty. |
| Per-component prop mapping | defineCmsComponent({ component, definition, mapProps }) |
Sync, render-time only. The editor still reads and writes the raw CMS props. For anything needing an await, see prop decoration below. |
| Async prop decoration | createCmsDecorator({ byType, all?, children?, failOpen?, timeoutMs?, cacheKey?, onError? }) (cms-client) |
For data the CMS does not store — a nav component's category tree, live stock. Wire it in both places or the editor's first push strips it: createServerCms({ decorate }) (and/or createCmsDraftRoute({ decorate })) server-side, CmsProvider/CmsPreviewProvider's decorate prop client-side. Decorators return a props patch, shallow-merged; id/type/name/children are untouchable. Cache inside your decorator — the SDK does none. |
| Theme CSS | <CmsThemeStyle theme> · themeCss · themeSelector · themeBodyAttributes |
Emits a <style data-cms-theme> — deliberately not an href/precedence stylesheet, so React 19 does not hoist it and strip the marker. |
| Theme stylesheet | createCmsThemeCssRoute (Next) / createCmsThemeCssHandler (any) · cmsThemeCssUrl · <CmsThemeLink> |
Serves /{site}/cms-theme.css with the same selector and sanitising as themeCss; immutable when versioned, no-store for the editor's draft/live-preview. See Themes. |
| Media URLs and alt text | mediaUrl(value) · mediaAlt(value) |
— |
| Link and clone resolution | isLink · isClone |
Linked content resolves at delivery; clones are copies. |
| Cache tags | defaultCmsTags · siteTag/pageTag/layoutTag/themeTag (+ plural forms) · canonicalUrl |
createServerCmsClient (Next) attaches { next: { revalidate, tags } } automatically. |
| CSR data hooks | useCmsPage (@contenter/react/client) · useCmsPage (@contenter/vue) |
For headless SPAs. Server-side rendering should use the client directly. |
| Error containment | <CmsErrorBoundary> |
Wrap a slot so one bad component does not blank the page. |
Auth
| Capability | Surface | Configured how |
|---|---|---|
| API-key auth | createCmsClient({ apiKey }) → X-CMS-API-Key |
Server-side only. Never ship the key to a browser; the sanctioned browser path is your own same-origin draft route. |
See Credentials.
Live preview & visual editing
The runtime is @contenter/preview-core (framework-agnostic, DOM only). A binding
(@contenter/preview-react, @contenter/preview-vue) implements the PreviewHost seam and mounts
createPreviewRuntime. Outside edit mode the runtime is inert: nothing is installed, no listeners,
no attributes read.
| Capability | Surface | Configured how |
|---|---|---|
| Detect edit mode from the iframe URL | parsePreviewFlags(search) → PreviewFlags; useIsPreview(); useEditorMode() |
Names are single-sourced in PREVIEW_PARAM: editMode, cmsApiKey, cmsVersion, cmsSite, cmsLocale, cmsPage, cmsLayout, cmsComponent, cmsThemeVersion, cmsThemeEditor, cmsReload. |
| Gate the preview route | isCmsPreviewAuthorized(flags, expectedKey) (cms-protocol, re-exported from /next and /nuxt) |
Fails closed in production when a key is configured. Answer with 404, not 403, so the route's existence is not advertised. |
| Mount the runtime | <CmsPreviewProvider> / <CmsProvider> (React) · <CmsPreviewProvider> (Vue) |
CmsProvider for the slotted/SSR model, CmsPreviewProvider for the SPA model that loads the draft itself. |
| Origin allowlisting | originAllowlist?: string[] · isAllowedOrigin?: (origin) => boolean |
⚠️ Defaults to fail-open with a one-time console warning. Pass the editor origin(s) in production — matching is exact string equality, no wildcards. This is the single most important thing to configure. |
| Content-gated handshake | automatic (IFRAME_READY posted once content is paintable) |
The editor waits PREVIEW_READY_TIMEOUT_MS (8 s); the storefront's own deadline is 3 s. Not configurable. |
| Which draft to load | selectDraftTarget(flags, fallbackSlug) · mergeDraftSlots({ layout, page, component }) · describeDraftTarget |
Precedence componentId > layoutId > pageId > pathname; page slots win over layout slots on merge. All four providers share this one decision. |
| Click-to-select a component | cmsEditable(cmsNode) on the component root |
Emits data-cms-component-id, data-cms-slot-id, data-cms-component-type. Your job as component author — the renderer never wraps or stamps. |
| Inline-editable field | editableProps(fieldPath, fieldType, { linkPath?, allowedTypes?, multiple? }) |
Emits data-cms-field-path, data-cms-field-type (+ optional link/allowed-types/multiple). Permitted types: text, textarea, media, product, category, url, select. richtext is banned — the commit path reads textContent. |
| Slot annotation | automatic — <CmsContentSlot> stamps data-cms-slot-id/-slot-type |
— |
| Inline editing on/off + commit mode | inlineCommit?: 'blur' | 'live'; editor overrides via SET_INLINE_EDITING ({ enabled, commitMode? }) |
Storefront sets the default; the editor's three-state "Editing in the preview" menu (Off / send as I type / send when I finish) wins when it has an opinion. commitMode is re-read per keystroke, so a switch lands on an already-open field. Omitted commitMode means "no opinion" — your default stands. commitDebounceMs defaults to 300 and is not reachable from PreviewOptions. All three of inlineCommit, mute and affordanceLabels are read once at mount, by value. |
| Caret survival during live commit | automatic — setActiveEdit(id) + identity preservation in cmsSlotOverlay.applySlots |
The edited component's object is reused so React skips the subtree. |
| Navigation muting | mute?: 'navigation' | 'all' | 'off' — default 'navigation' |
Capture-phase preventDefault+stopImmediatePropagation so next/link's React handler never runs. Covers anchors, form submits, and patches history.pushState/replaceState. Held clicks are reported as NAVIGATION_INTERCEPTED and released only on an allow response; unanswered requests expire after 30 s and are discarded, not performed. |
| Custom navigation handling | PreviewHost.onNavigate?(path, href) |
Return true to claim it (e.g. router push); otherwise location.assign. |
| Product picker | PreviewHost.onProductSearch?(request) |
Unwired ⇒ the editor's picker reports unsupported. |
| Category tree picker | PreviewHost.onCategoryTree?() |
Unwired ⇒ same. |
| Custom search picker | PreviewHost.onCustomSearch?(request) + P.customSearch(label, searchId) |
Return null for "I do not handle this searchId" (⇒ supported: false); throw for a real error (⇒ error). Per-searchId staleness is handled for you. |
| Theme editing | REQUEST_THEME / UPDATE_THEME_VARIABLES / UPDATE_THEME_TARGET / RESET_THEME_VARIABLES handled by preview-core's theme controller |
Automatic. One <style id="cms-theme-overrides"> node; reset() removes it. |
| Theme token manifest | PreviewHost.getThemeTokenManifest?() → ThemeTokenManifest |
Unwired ⇒ the empty { site, groups: [], fallback: true }. This is how the editor learns which tokens exist and their labels/groups. |
| No-override baseline | automatic: the runtime measures each token with the CMS overrides silenced and returns ThemeToken.baselineValue / currentValue. Extend the silenced set with PreviewHost.getThemeBaselineExclusions?() |
Answers "what would this token be if I removed my override" — impossible to compute, because you cannot subtract from the cascade. Defaults cover an SDK-native storefront (#cms-theme-overrides, style[data-cms-theme], and any stylesheet <link> to /cms-theme.css); declare your own persisted <link> only if it is served from another path. The editor prefers baselineValue over defaultValue. |
Base-theme class on <body> |
automatic — the theme controller stamps the active base_theme and restores the SSR class on teardown |
Without it a scoped .theme-x{…} override rule matches nothing on a site whose SSR emitted no base theme, which is the theme editor's normal starting state for an unpublished theme. |
| Theme-editor scope | cmsThemeEditor=true ⇒ EditScope: 'theme' |
Selection, inline edit and affordances never start in theme scope. |
| Editor affordance labels | affordanceLabels?: AffordanceLabels |
Localise the in-preview hint chips. |
| Diagnostics | previewStatus (report/count/read/subscribe/reset) · describePreviewFailure(status) · <CmsPreviewDiagnostics> |
The panel appears after 5 s of an unresolved preview. It never reveals the API key, its length, or whether one is configured. Two faults are reported after a successful handshake and so are exempt from the "nothing is wrong" early return: layoutUnresolved and decorationFailed. |
| Live store seam | CmsLiveStore (setSlots, …) · createLiveStore · cmsSlotOverlay |
Implement CmsLiveStore to plug your own state container in. applySlots is synchronous by contract — it is the caret guard's critical section. |
Message names and payloads: protocol reference. DOM attribute names are
single-sourced in CMS_DATA_ATTR (cms-protocol/src/dom-contract.ts).
Route factories
Everything a storefront used to hand-roll. The HTTP half is neutral (@contenter/cms-client, Web
Request/Response); the Next wrappers bind it to the App Router.
| Route | Neutral | Next | Notes |
|---|---|---|---|
| Editor preview page | — | createCmsEditorPreview({ cms, client, site, locale, defaultLayoutId, chrome?, content?, apiKey?, diagnostics? }) · cmsPreviewMetadata |
The whole route: gate, layout resolution (cmsLayout flag → the page's layout_id → defaultLayoutId, then verified via getLayout), component mode with no chrome, diagnostics. defaultLayoutId is required. |
| Draft content | createCmsDraftHandler({ client, authorize? }) |
createCmsDraftRoute |
The sanctioned browser path — keeps the API key server-side. Reads site/locale per request. |
| Component registry | createComponentRegistryHandler |
createComponentRegistryRoute({ definitions | registry, apiKey?, apiKeyHeader?, allowedOrigins?, maxAge?, onEmpty? }) |
Prefer definitions (plain data). A 'use client' registry yields opaque references; onEmpty defaults to a 503 rather than 200 {"components":{}}. |
| Revalidation webhook | createCmsRevalidateHandler |
createCmsRevalidateRoute({ secret?, onRevalidate?, maxItems? }) |
Site/locale travel inside the cms:* tag strings. |
| Page index proxy | createPageIndexHandler({ client, site, locale, defaultLimit?, maxLimit?, sortKey?, filter?, failOpen?, maxAge? }) |
createPageIndexRoute |
site/locale accept a function of the request for a multi-site storefront. Query category, tags (CSV), limit (clamped). Answers { pages }. |
| Listing hook | — | useCmsPageIndex(endpoint, options) (/client) |
Takes an endpoint, not a client — a browser client would need the key. { pages, error, isLoading, refetch }, AbortController-backed. |
Resilience
| Capability | Surface | Configured how |
|---|---|---|
| A backend outage costs a prerender, not the build | createResilientFetch({ fetch?, onUnusable?, onWarn?, answerStatuses? }) · describeFetchFailure · isControlFlowError |
answerStatuses defaults to [404] (an answer, not a failure). The warning is deduped per reason; onUnusable fires every time. |
| Next binding | createCmsFetch() · isNextControlFlowError (/next) |
Binds onUnusable: () => connection(). Pass to createCmsClient({ fetch }). Never catch a CMS read without re-throwing control-flow errors. |
SEO
| Capability | Surface | Configured how |
|---|---|---|
| Derive title/description/OG from CMS meta | deriveMeta(resolved, options) (neutral) |
— |
| Next metadata | cmsMetadata(resolved, { origin }) |
origin is what makes canonical and og:url absolute. It must be the same value your sitemap uses. |
| Vue/Nuxt head | cmsHead(resolved) (@contenter/vue/nuxt) |
— |
| Sitemap entries | buildSitemapEntries({ origin, pages, exclude?, extraPaths?, changeFrequency?, priority? }) (neutral) |
Pure over an array; never fetches. Throws on a blank or relative origin — a missing origin yields a 100%-wrong artifact that cannot self-heal at request time. Drops meta.robots containing noindex. |
| Next sitemap | createCmsSitemap({ client, site, locale, origin, excludeTemplates?, exclude?, extraPaths?, failOpen? }) |
locale accepts an array (reads run in parallel); site is a single string — a multi-site sitemap drops to buildSitemapEntries. failOpen defaults true because app/sitemap.ts cannot opt out of the static-generation bailout. |
| Exclude slug-addressed templates | excludeTemplates (default true) · isSlugAddressedTemplate(page) |
The discriminator is preview_slug — a template carries one because it has no URL of its own. Exact where a category/tags heuristic is not. |
| robots.txt | createCmsRobots({ origin, allowIndexing?, previewPath?, disallow?, sitemapPath? }) |
previewPath defaults to DEFAULT_PREVIEW_PATH, not a literal, because the path is tenant-configurable. allowIndexing: false emits Disallow: / and no sitemap reference. |
Component authoring
| Capability | Surface | Configured how |
|---|---|---|
| Declare a component's editor schema | P.{text,textarea,richtext,number,boolean,color,url,media,select,object,array,component,category,product,customSearch,ref,link} · defineComponentType (cms-protocol) |
Lives in cms-protocol because that package has no React and therefore can never become a client module. |
| Pair a component with its schema | defineCmsComponent({ component, definition, mapProps? }) (@contenter/react) · defineComponent (@contenter/vue) |
— |
| Publish the schemas | createComponentRegistryRoute({ definitions }) |
Keep definitions in a module with no 'use client'. See publishing the registry. |
| A ready-made component set | @contenter/react-components (11 components) · @contenter/react-components/definitions (their schemas) |
Two entry points on purpose: . is client-stamped, ./definitions is plain data for the registry route. |
Offline & test infrastructure
| Capability | Surface | Configured how |
|---|---|---|
| Boot with no backend | createFixtureFetch({ files? | load? }) · fixtureFileFor(pathname) · fixtureSlugKey(raw) |
Pass as createCmsClient({ fetch }). Prefer files (a generated barrel of static imports) over load — no IO, no process.cwd(), bundler-traceable. Substitutes only the HTTP hop: auth, URL construction, parsing, resolvePageTree, the slot renderer and the registry all run exactly as against a real cms-api. Multi-site: keys may be site/locale-prefixed (pages/<site>/<locale>/<slug>.json, layouts/<site>/<locale>/<name>.json, themes/<site>.json, page-index/<site>/<locale>.json); the flat names are the fallback, so a single-site set needs no prefixes. fixtureFileFor returns files (candidates, most specific first) — read that rather than file. |
| A deterministic commerce backend | @contenter/mock-commerce (. server, ./data fixtures) |
Products, search, categories, carts, orders. No customSearch handler — a searchId-keyed picker cannot be backed by it. |
What the SDK deliberately does not do
| Not provided | Why | What to do instead |
|---|---|---|
| Zero-annotation click-to-edit | Heuristic DOM anchoring (match a text node to a prop value) is ambiguous the moment two props share a value, and it fails silently. | Annotate with cmsEditable + editableProps. It is explicit, and it is a compile-time-visible contract. |
| Caching for your decorators | Only you know whether "same component type" implies "same data", and which of your framework's caches is right. | Wrap your decorator's reads in React cache() / your data cache. cacheKey gives you an opt-in per-pass dedupe (discarded when the pass returns, so nothing leaks across requests). |
A settings/siteFallbacks read |
There is no storefront-readable settings endpoint; the public surface is the five /storefront/* reads plus /health. |
Nothing — cms-api applies fallbacks server-side and reports the outcome as resolvedSite/resolvedLocale on the page bundle. A client-side fallback matrix is redundant against cms-api. |
| Commerce integration | Pickers resolve storefront-side by design; store mode and commerce data source are orthogonal. | Implement onProductSearch/onCategoryTree/onCustomSearch. |
| A per-site component registry | The registry is global; theme/variant scoping is a filter over your definitions. | Filter before you pass definitions — the route reads them per request. |
| Angular binding | Not built yet. | cms-client + preview-core directly. |
See also
Live-preview protocol reference
The contract between the CMS editor (parent window) and the storefront
(preview iframe). The SDK implements the storefront side; this reference is for
understanding it, debugging, or porting to another framework. All constants and
payload types live in @contenter/cms-protocol.
- Editor → storefront messages: constant map
IFRAME_MSG. - Storefront → editor messages: constant map
STOREFRONT_MSG. - Every message is
{ type, ...payload }. Correlate request/response bytype, and byrequestIdfor fan-out pairs (product search, theme tokens).
Preview URL flags
When the editor loads the storefront in its iframe it appends query params.
parsePreviewFlags(location.search) decodes them.
| Param | Meaning |
|---|---|
editMode=true |
Activation signal — enter preview mode. |
cmsApiKey |
Tenant CMS API key, echoed in the handshake. |
cmsSite |
Site code. |
cmsLocale |
Content locale. |
cmsVersion |
Version to render (live | draft | version id). |
cmsPage |
Full page entity id to render — the page preview's "what". |
cmsLayout |
Full layout entity id to render (also scopes editing to layout slots). |
cmsComponent |
Component Library entity id to render chrome-less. |
cmsThemeVersion |
Theme version to render (draft | live). |
cmsReload |
Cache-busting token bumped on editor-driven reloads. |
The path is not part of the addressing: every preview loads the storefront's
editor preview route (DEFAULT_PREVIEW_PATH = /cms-editor, overridable via
CMSSettings.preview_path) and the flags above say what to render. The one
exception is an entity with a preview_slug, which is previewed on that real
storefront path instead — with the same flags. The route must be gated on
cmsApiKey (isCmsPreviewAuthorized) since it renders unpublished content. See
live-preview.md.
Storefront reads it back with GET /storefront/page-by-id/{cmsPage} (SDK:
client.getPageById) or GET /storefront/component-by-id/{cmsComponent}
(client.getComponentById) — never cached, since it's the draft being edited.
Editor → storefront (IFRAME_MSG)
type |
Payload | Purpose |
|---|---|---|
UPDATE_SLOT |
slots: [{ slotId, components }] |
Push edited component tree → live re-render. Always concrete components: link_mode:'link' references are expanded to their live source by the editor before sending, mirroring what cms-api does for delivered pages — a storefront never needs link handling. |
HIGHLIGHT_COMPONENT |
componentId | null, slotId? |
Draw/clear the component selection ring. |
HIGHLIGHT_SLOT |
slotId | null |
Draw/clear the slot highlight. |
REQUEST_COMPONENT_TYPES |
— | Ask for the storefront's component-type registry. |
REQUEST_CATEGORY_TREE |
— | Ask for the category tree. |
REQUEST_PRODUCT_SEARCH |
requestId, site, locale, query, categoryId?, limit? |
Product autocomplete/search. |
NAVIGATION_RESPONSE |
requestId?, action: 'allow' |
Allow an intercepted in-preview navigation. |
REQUEST_THEME |
— | Ask for current theme variables + target selector. |
REQUEST_THEME_TOKENS |
requestId? |
Ask for the theme-token manifest. |
UPDATE_THEME_VARIABLES |
variables, mode?: 'merge'|'replace' |
Live CSS-var patch ('' value = remove). |
UPDATE_THEME_TARGET |
site, base_theme? |
Live-swap the CSS selector overrides scope to. |
RESET_THEME_VARIABLES |
— | Drop overrides, revert to SSR baseline. |
Storefront → editor (STOREFRONT_MSG)
type |
Payload | Purpose |
|---|---|---|
IFRAME_READY |
apiKey? |
Handshake — listener mounted. Triggers the editor to fan out REQUEST_*. |
COMPONENT_TYPES |
componentTypes: CMSComponentTypeDefinition[] |
The registry the storefront can render. |
NAVIGATION_INTERCEPTED |
href, path, requestId? |
User clicked an in-preview link. |
CATEGORY_TREE_RESPONSE |
categories?, error? |
Reply to REQUEST_CATEGORY_TREE. |
PRODUCT_SEARCH_RESPONSE |
requestId, site, locale, query, products, error? |
Reply to REQUEST_PRODUCT_SEARCH. |
THEME_RESPONSE |
site, variables, target, version |
Reply to REQUEST_THEME. |
THEME_TOKENS_RESPONSE |
site, manifest, requestId? |
Reply to REQUEST_THEME_TOKENS. |
INLINE_EDIT_COMMIT |
componentId, slotId, fieldPath, fieldType, value |
Inline text edit committed. |
INLINE_EDIT_REQUEST |
componentId, slotId, fieldPath, fieldType, allowedTypes?, multiple?, currentValue? |
Open the editor's media/product/category picker. |
COMPONENT_SELECTED |
componentId, slotId |
Preview click → mirror selection in the sidebar (empty = deselect). |
Sequences
Handshake + initial sync
storefront: IFRAME_READY { apiKey }
editor: (validates apiKey) → REQUEST_COMPONENT_TYPES, REQUEST_CATEGORY_TREE, REQUEST_THEME, REQUEST_THEME_TOKENS
storefront: COMPONENT_TYPES, CATEGORY_TREE_RESPONSE, THEME_RESPONSE, THEME_TOKENS_RESPONSE
The editor re-sends its full state on every IFRAME_READY, so handlers must be
idempotent.
Live edit loopback (inline text)
storefront: INLINE_EDIT_COMMIT { componentId, slotId, fieldPath, fieldType, value }
editor: writes value at fieldPath, re-broadcasts →
editor: UPDATE_SLOT { slots: [{ slotId, components }] }
storefront: re-renders the slot
The editor is the source of truth; the storefront never mutates content directly.
Product search (with stale-drop)
editor: REQUEST_PRODUCT_SEARCH { requestId: 'r7', query: 'sho' }
storefront: PRODUCT_SEARCH_RESPONSE { requestId: 'r7', products: [...] }
requestId is echoed unchanged; the storefront drops a response if a newer
request superseded it, and always returns products (empty on error).
Theme live-preview
editor: UPDATE_THEME_VARIABLES { variables: { '--brand': '#f60' }, mode: 'merge' }
storefront: applies to <style id="cms-theme-overrides"> (one canonical node)
editor: UPDATE_THEME_TARGET { site, base_theme } // recompute selector
editor: RESET_THEME_VARIABLES // revert to SSR baseline
Navigation
storefront: NAVIGATION_INTERCEPTED { href, path, requestId }
editor: NAVIGATION_RESPONSE { requestId, action: 'allow' }
storefront: navigates (SPA route via onNavigate, else full load; fail-open ~2s)
Security
- Editor posts use
targetOrigin: '*'. The storefront runtime validates inboundevent.originagainst an allowlist and checksevent.source === window.parent; replies target the captured parent origin. See live preview → security. - Inline-edit values are read via
textContent(neverinnerHTML). - Theme values are sanitized (var name
^--[\w-]+$;<,>,{,}stripped).
DOM data-attribute contract
The renderer stamps these so the preview can map DOM ↔ CMS (CMS_DATA_ATTR):
| Attribute | On | Value |
|---|---|---|
data-cms-component-id |
every component root | component id |
data-cms-slot-id |
component root / slot container | top-level editable slot id |
data-cms-component-type |
component root (optional) | component type |
data-cms-field-path |
element bound to one prop | dot-path into raw props |
data-cms-field-type |
same element | the field's editor type |
cmsEditable() and editableProps() from @contenter/react emit these.