Page Builder Site
This example builds a small marketing site whose pages editors compose in the Page Builder. It has two custom blocks (Hero and Feature Grid) with typed props and design tokens, a catch-all route that renders any page by slug, and a preview route that lets the console show unsaved drafts live. Every file is shown in full.
Prerequisites
Section titled “Prerequisites”- Node.js 20 or later.
- A Plenary instance you can sign in to, with a site (this example uses the site key
defaultand localeen-us; use yours). - These packages, at the versions this example was built and tested with:
| Package | Version |
|---|---|
next |
16.4 |
react, react-dom |
19 |
@plenary/client, @plenary/core, @plenary/react |
1.0.x |
typescript |
5.9 |
What you will set up in the console:
- A model with key
page, ablocksfield with keybody, and a preview URL. - A public API key for the site.
Set up Plenary
Section titled “Set up Plenary”Create the page model
Section titled “Create the page model”- Go to Content Management → Content and click New model.
- Set Name (singular) to
Page, Name (plural) toPages, Key topage, and Kind to Collection. - On the Fields tab, add two fields:
- Title, key
title, type Text, Required on. - Body, key
body, type Blocks.
- Title, key
- On the Settings tab, in Metadata:
- Set Title field to Title.
- Turn on Show preview.
- Set Preview URL to
http://localhost:3000/preview/{{slug}}while you develop. Change it to your deployed site’s URL later, such ashttps://www.example.com/preview/{{slug}}. - Turn on Open entries in Page Builder.
- Click Save model.
The model can also be created from YAML; see Models as Code.
Create a public API key
Section titled “Create a public API key”- Go to Access Management → API Keys and create a key.
- Choose Public (“Read-only view of published content”), give it a name, and select your site.
- Copy the key when it is shown. See API Keys.
A public key reads only published entries. That is all this site needs: the preview receives drafts from the console, not from the API.
Create the project
Section titled “Create the project”mkdir page-builder-site && cd page-builder-siteThe project has this layout:
page-builder-site/├── .env.local├── next.config.ts├── package.json├── tsconfig.json├── app/│ ├── globals.css│ ├── layout.tsx│ ├── [[...slug]]/page.tsx│ └── preview/[slug]/page.tsx├── components/│ ├── PageBridge.tsx│ └── blocks/│ ├── FeatureGrid.tsx│ └── Hero.tsx└── lib/ ├── blocks.ts └── plenary.tspackage.json
Section titled “package.json”{ "name": "plenary-page-builder-site", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "typecheck": "tsc --noEmit" }, "dependencies": { "@plenary/client": "^1.0.2", "@plenary/core": "^1.0.2", "@plenary/react": "^1.0.2", "next": "^16.4.0", "react": "^19.3.0", "react-dom": "^19.3.0" }, "devDependencies": { "@types/node": "^22", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "typescript": "^5.9.3" }}Then install:
npm installtsconfig.json
Section titled “tsconfig.json”{ "compilerOptions": { "target": "ES2022", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": false, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", "incremental": true, "plugins": [{ "name": "next" }], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"], "exclude": ["node_modules"]}Next.js generates next-env.d.ts on the first next dev or next build.
.env.local
Section titled “.env.local”PLENARY_BASE_URL=https://your-instance.plenarycms.ioPLENARY_SITE_KEY=defaultPLENARY_API_KEY=pln_pub_your_public_keyPLENARY_LOCALE=en-usPLENARY_EDITOR_ORIGINS=https://your-instance.plenarycms.io| Variable | Value |
|---|---|
PLENARY_BASE_URL |
Your instance’s origin, with no path. The API is under /api/v1 and the console under /cms on this origin. |
PLENARY_SITE_KEY |
The site whose pages this app serves. |
PLENARY_API_KEY |
The public API key you created. |
PLENARY_LOCALE |
The locale to read. |
PLENARY_EDITOR_ORIGINS |
Comma-separated console origins allowed to drive the preview: your instance’s origin. Add http://localhost:* if you also run a console locally. See Editor origins. |
next.config.ts
Section titled “next.config.ts”import type { NextConfig } from "next";
const nextConfig: NextConfig = { // Plenary hands out media URLs as instance-relative paths (/media/{id}/{file}). // Proxy them to the instance so images resolve on this site's origin. async rewrites() { return [{ source: "/media/:path*", destination: `${process.env.PLENARY_BASE_URL}/media/:path*` }]; },};
export default nextConfig;The rewrite matters for both the published pages and the preview: image URLs from Plenary look like /media/556a8e94-.../original.png, and without it they would 404 on your site’s origin.
Connect to Plenary
Section titled “Connect to Plenary”lib/plenary.ts
Section titled “lib/plenary.ts”import { createClient } from "@plenary/client";
/** The Plenary content client. Server-side only: it carries your API key. */export const plenary = createClient({ baseUrl: process.env.PLENARY_BASE_URL!, siteKey: process.env.PLENARY_SITE_KEY ?? "default", apiKey: process.env.PLENARY_API_KEY!, locale: process.env.PLENARY_LOCALE ?? "en-us",});
/** The model whose entries are pages. */export const PAGE_MODEL = "page";
/** The key of the page model's `blocks` field: the region the Page Builder edits. */export const PAGE_REGION = "body";
/** Console origins allowed to drive the live preview. Never "*". */export const EDITOR_ORIGINS = (process.env.PLENARY_EDITOR_ORIGINS ?? "") .split(",") .map((origin) => origin.trim()) .filter(Boolean);Build the blocks
Section titled “Build the blocks”components/blocks/Hero.tsx
Section titled “components/blocks/Hero.tsx”import type { ResolvedMedia } from "@plenary/react";
export interface HeroProps { heading?: string; subheading?: string; align?: "left" | "center"; showButton?: boolean; buttonLabel?: string; buttonUrl?: string; /** The renderer resolves an `image` prop to `{ url, alt, ... }`. `url` is "" when unresolved. */ backgroundImage?: ResolvedMedia | null;}
export function Hero({ heading = "", subheading, align = "center", showButton, buttonLabel, buttonUrl, backgroundImage,}: HeroProps) { const image = backgroundImage?.url || null; return ( <section className={`hero hero--${align}`} style={image ? { backgroundImage: `url("${image}")` } : undefined} > <h1>{heading}</h1> {subheading ? <p className="hero__lede">{subheading}</p> : null} {showButton && buttonLabel ? ( <a className="button" href={buttonUrl || "#"}> {buttonLabel} </a> ) : null} </section> );}The component is plain React. Every prop is optional with a fallback, because stored props are passed through exactly as saved and the renderer does not apply registration defaults. It renders a single root element, so the Style tab’s panels have somewhere to apply.
components/blocks/FeatureGrid.tsx
Section titled “components/blocks/FeatureGrid.tsx”export interface Feature { title?: string; body?: string;}
export interface FeatureGridProps { heading?: string; /** A select prop stores the option's string value. */ columns?: "2" | "3" | "4"; features?: Feature[];}
export function FeatureGrid({ heading, columns = "3", features = [] }: FeatureGridProps) { return ( <section className="features"> {heading ? <h2>{heading}</h2> : null} <ul className="features__grid" style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}> {features.map((feature, i) => ( <li key={i} className="features__item"> <h3>{feature.title}</h3> {feature.body ? <p>{feature.body}</p> : null} </li> ))} </ul> </section> );}lib/blocks.ts
Section titled “lib/blocks.ts”This module registers the two blocks and the design tokens. Importing it is what makes the renderer resolve hero and feature_grid nodes, and what puts the blocks in the console’s palette.
/** * Registers this site's custom blocks and design tokens. Import it from every * server route that renders a page AND from the client module that mounts * <PlenaryBridge> (components/PageBridge.tsx): Next.js has separate server and * client module graphs, and each needs its own registrations. */import { register, registerTheme } from "@plenary/react";import { Hero } from "@/components/blocks/Hero";import { FeatureGrid } from "@/components/blocks/FeatureGrid";
// Each token must exist as a CSS custom property in app/globals.css.registerTheme({ colors: [ { name: "brand", value: "#2563eb", label: "Brand" }, { name: "ink", value: "#0f172a", label: "Ink" }, { name: "surface", value: "#f1f5f9", label: "Surface" }, ], fonts: [ { name: "font-body", value: "system-ui, sans-serif", label: "Body" }, { name: "font-display", value: "Georgia, serif", label: "Display" }, ],});
register(Hero, { key: "hero", label: "Hero", category: "Marketing", icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 10h10M9 14h6"/></svg>', props: [ { key: "heading", type: "text", required: true, defaultValue: "Your headline here" }, { key: "subheading", type: "text", ui: { control: "textarea" } }, { key: "align", type: "select", defaultValue: "center", settings: { options: [ { value: "left", label: "Left" }, { value: "center", label: "Center" }, ], }, }, { key: "showButton", type: "boolean", ui: { label: "Show Button" } }, { key: "buttonLabel", type: "text", ui: { label: "Button Label" }, visibleWhen: { prop: "showButton", equals: true }, }, { key: "buttonUrl", type: "url", ui: { label: "Button URL" }, visibleWhen: { prop: "showButton", equals: true }, }, { key: "backgroundImage", type: "image", ui: { show_alt_caption: false } }, ], styles: ["size", "background", "typography", "css"],});
register(FeatureGrid, { key: "feature_grid", label: "Feature Grid", category: "Marketing", props: [ { key: "heading", type: "text" }, { key: "columns", type: "select", defaultValue: "3", settings: { options: [ { value: "2", label: "2" }, { value: "3", label: "3" }, { value: "4", label: "4" }, ], }, }, { key: "features", type: "list", settings: { item_type: "object", sortable: true, item_settings: { fields: [ { key: "title", name: "Title", type: "text", required: true }, { key: "body", name: "Body", type: "text", ui: { control: "textarea" } }, ], }, }, ui: { add_label: "Add feature", collapsible_items: true }, }, ], styles: ["size", "background", "css"],});What the registrations demonstrate:
visibleWhenshows Button Label and Button URL only while Show Button is on.backgroundImageis animageprop, so the renderer hands the component a resolved{ url, alt, ... }object.featuresis a list of objects. Its sub-fields go undersettings.item_settings.fields, the same shape a content model’s list field uses.stylespicks the Style-tab panels. Feature Grid has notypographypanel, so editors cannot change its fonts.- Both blocks appear in the palette under Custom · Marketing.
The full prop options are in the Page Builder guide.
Build the pages
Section titled “Build the pages”app/globals.css
Section titled “app/globals.css”/* Design tokens. Names match registerTheme() in lib/blocks.ts. */:root { --brand: #2563eb; --ink: #0f172a; --surface: #f1f5f9; --font-body: system-ui, sans-serif; --font-display: Georgia, serif;}
* { box-sizing: border-box; }body { margin: 0; font-family: var(--font-body); color: var(--ink); }.site-header, .site-footer { padding: 16px 24px; background: var(--surface); }.site-header a { color: var(--ink); font-weight: 700; text-decoration: none; }
/* Fixed min-heights only: viewport units (vh, svh, dvh) grow forever in the Page Builder. */.hero { display: flex; flex-direction: column; gap: 16px; min-height: 480px; justify-content: center; padding: 64px 24px; background: var(--surface) center / cover no-repeat;}.hero--center { align-items: center; text-align: center; }.hero--left { align-items: flex-start; }.hero h1 { margin: 0; font-family: var(--font-display); font-size: 48px; }.hero__lede { margin: 0; max-width: 640px; font-size: 20px; }.button { padding: 12px 20px; border-radius: 6px; background: var(--brand); color: #fff; text-decoration: none; }
.features { padding: 64px 24px; }.features h2 { margin: 0 0 24px; font-family: var(--font-display); }.features__grid { display: grid; gap: 24px; margin: 0; padding: 0; list-style: none; }.features__item { padding: 24px; border-radius: 8px; background: var(--surface); }.features__item h3 { margin: 0 0 8px; }.features__item p { margin: 0; }.empty { padding: 64px 24px; text-align: center; }The hero uses min-height: 480px, not 100vh. Inside the Page Builder the preview frame is sized to the page, so viewport units grow without limit. See Live Preview.
app/layout.tsx
Section titled “app/layout.tsx”import type { ReactNode } from "react";import "./globals.css";
export default function RootLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> <body> <header className="site-header"> <a href="/">Acme</a> </header> <main>{children}</main> <footer className="site-footer">© Acme</footer> </body> </html> );}The header and footer sit outside the bridge, so they appear around the page on the canvas exactly as on the live site.
app/[[…slug]]/page.tsx
Section titled “app/[[…slug]]/page.tsx”The public route. / renders the entry with slug home, and /about renders the entry with slug about.
import type { Metadata } from "next";import { notFound } from "next/navigation";import { PlenaryNotFoundError } from "@plenary/client";import type { PlenaryDocument } from "@plenary/core";import { PlenaryPage } from "@plenary/react";import { plenary, PAGE_MODEL, PAGE_REGION } from "@/lib/plenary";// Registers the custom blocks for the server render.import "@/lib/blocks";
// Render on every request. See /examples/revalidation/ to cache pages instead.export const dynamic = "force-dynamic";
type PageData = Record<string, PlenaryDocument | undefined>;type Params = Promise<{ slug?: string[] }>;
/** "/" is the entry with slug "home"; "/about" is "about". Deeper paths 404. */function slugFrom(segments: string[] | undefined): string | null { if (!segments || segments.length === 0) return "home"; return segments.length === 1 ? segments[0] : null;}
async function loadPage(segments: string[] | undefined) { const slug = slugFrom(segments); if (!slug) notFound(); try { return await plenary.getEntry<PageData>(PAGE_MODEL, slug); } catch (err) { if (err instanceof PlenaryNotFoundError) notFound(); throw err; }}
export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> { const entry = await loadPage((await params).slug); return { title: entry.title ?? undefined };}
export default async function Page({ params }: { params: Params }) { const entry = await loadPage((await params).slug); const document = entry.data[PAGE_REGION]; if (!document) return null; return <PlenaryPage document={document} client={plenary} />;}PlenaryPage is an async Server Component. It looks up every image in the document with the client, then renders each block with its registered component. Unpublished and missing pages return 404, because a public key reads only published entries.
components/PageBridge.tsx
Section titled “components/PageBridge.tsx”"use client";
import type { ReactNode } from "react";import { PlenaryBridge } from "@plenary/react/bridge";// Registers the custom blocks in the client module graph, where the bridge renders.import "@/lib/blocks";
export function PageBridge({ region, editorOrigins, children,}: { region: string; editorOrigins: string[]; children: ReactNode;}) { return ( <PlenaryBridge region={region} editorOrigins={editorOrigins}> {children} </PlenaryBridge> );}PlenaryBridge runs in the browser, and Next.js gives client components their own copy of the component registry. Without the @/lib/blocks import here, the canvas would show “Unknown component” for Hero and Feature Grid, and neither would appear in the palette.
app/preview/[slug]/page.tsx
Section titled “app/preview/[slug]/page.tsx”The route the model’s Preview URL points at.
import type { Metadata } from "next";import { PlenaryNotFoundError } from "@plenary/client";import type { PlenaryDocument } from "@plenary/core";import { PlenaryPage } from "@plenary/react";import { PageBridge } from "@/components/PageBridge";import { plenary, PAGE_MODEL, PAGE_REGION, EDITOR_ORIGINS } from "@/lib/plenary";// Registers the custom blocks for the server render of the fallback content.import "@/lib/blocks";
export const dynamic = "force-dynamic";export const metadata: Metadata = { robots: { index: false, follow: false } };
type PageData = Record<string, PlenaryDocument | undefined>;
/** * The Page Builder's preview target. The console frames this URL and pushes * the unsaved draft to <PlenaryBridge> over postMessage, so the route only has * to mount the bridge. The published copy is shown until the console connects. */export default async function PreviewPage({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params;
let published: PlenaryDocument | undefined; try { const entry = await plenary.getEntry<PageData>(PAGE_MODEL, slug); published = entry.data[PAGE_REGION]; } catch (err) { // A page that has never been published is not readable with a public key. // The bridge still renders the draft once the console connects. if (!(err instanceof PlenaryNotFoundError)) throw err; }
return ( <PageBridge region={PAGE_REGION} editorOrigins={EDITOR_ORIGINS}> {published ? <PlenaryPage document={published} client={plenary} /> : <p className="empty">Not published yet.</p>} </PageBridge> );}The static preview segment takes precedence over the catch-all route, so a page with the slug preview cannot be served at /preview. Pick another path if you need that slug.
Run it
Section titled “Run it”npm run devOpen http://localhost:3000. Until a home page is published, you see a 404.
To check the production build:
npm run typechecknpm run buildBoth routes are dynamic, so the build does not contact your instance.
Build a page in the console
Section titled “Build a page in the console”- Go to Content Management → Content, open Pages, and click New Page. Because Open entries in Page Builder is on, the Page Builder opens.
- On the Data tab, set Title to
Homeand the slug tohome, then click Save Changes. The canvas loadshttp://localhost:3000/preview/homeand the status changes from Waiting for preview to Preview connected. - On the Blocks tab, find Hero and Feature Grid in the palette under Custom · Marketing. Drag Hero onto the canvas.
- With the Hero selected, edit Heading on the Properties tab. Turn on Show Button and the Button Label and Button URL inputs appear. The canvas updates as you type.
- Drag Feature Grid below the Hero. Click Add feature to add items.
- On the Style tab, set the Hero’s text color to the Ink token. Switch the toolbar to Mobile 390 and change its padding; that change applies only at 640px and below.
- Click Save Changes, then publish: use the save button’s menu and choose Save and Publish.
- Open
http://localhost:3000. The published page renders with your blocks and styles.
When you deploy, set the model’s Preview URL to your deployed preview route and make sure your instance’s origin is in PLENARY_EDITOR_ORIGINS.
What the stored page looks like
Section titled “What the stored page looks like”After step 7, the API returns the body field as a document like this (ids shortened):
{ "version": 1, "root": [ { "id": "3f0c2b9e", "component": "hero", "props": { "heading": "Ship pages faster", "subheading": "Built with Plenary blocks.", "align": "center", "showButton": true, "buttonLabel": "Get started", "buttonUrl": "/about", "style": { "color": "var(--ink)" }, "styleMobile": { "paddingTop": "32px" } } }, { "id": "8d2e4c1a", "component": "feature_grid", "props": { "heading": "Why it works", "columns": "3", "features": [ { "title": "Fast", "body": "Rendered on your site." }, { "title": "Typed", "body": "Props from code." }, { "title": "Live", "body": "Preview drafts." } ] } } ]}And PlenaryPage renders it as:
<style data-plenary-styles="">[data-plenary-id="3f0c2b9e"] > * { color: var(--ink) !important; }@media (max-width: 640px) { [data-plenary-id="3f0c2b9e"] > * { padding-top: 32px !important; } }</style><div data-plenary-id="3f0c2b9e" style="display:contents"> <section class="hero hero--center"> <h1>Ship pages faster</h1> <p class="hero__lede">Built with Plenary blocks.</p> <a class="button" href="/about">Get started</a> </section></div><section class="features"> <h2>Why it works</h2> <ul class="features__grid" style="grid-template-columns:repeat(3, minmax(0, 1fr))"> <li class="features__item"><h3>Fast</h3><p>Rendered on your site.</p></li> <li class="features__item"><h3>Typed</h3><p>Props from code.</p></li> <li class="features__item"><h3>Live</h3><p>Preview drafts.</p></li> </ul></section>Only the styled Hero gets a data-plenary-id wrapper; the unstyled Feature Grid renders bare.
Next steps
Section titled “Next steps”- Cache pages and refresh them on publish: Instant Revalidation.
- Add more block types, slots, and reference props: Page Builder guide.
- Understand the preview connection: Live Preview.
- Look up every SDK export: @plenary/react and @plenary/core.