Skip to content

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.

  • Node.js 20 or later.
  • A Plenary instance you can sign in to, with a site (this example uses the site key default and locale en-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, a blocks field with key body, and a preview URL.
  • A public API key for the site.
  1. Go to Content Management → Content and click New model.
  2. Set Name (singular) to Page, Name (plural) to Pages, Key to page, and Kind to Collection.
  3. On the Fields tab, add two fields:
    • Title, key title, type Text, Required on.
    • Body, key body, type Blocks.
  4. 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 as https://www.example.com/preview/{{slug}}.
    • Turn on Open entries in Page Builder.
  5. Click Save model.

The model can also be created from YAML; see Models as Code.

  1. Go to Access Management → API Keys and create a key.
  2. Choose Public (“Read-only view of published content”), give it a name, and select your site.
  3. 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.

Terminal window
mkdir page-builder-site && cd page-builder-site

The 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.ts
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:

Terminal window
npm install
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
PLENARY_BASE_URL=https://your-instance.plenarycms.io
PLENARY_SITE_KEY=default
PLENARY_API_KEY=pln_pub_your_public_key
PLENARY_LOCALE=en-us
PLENARY_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
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.

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);
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
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>
);
}

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.

lib/blocks.ts
/**
* 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:

  • visibleWhen shows Button Label and Button URL only while Show Button is on.
  • backgroundImage is an image prop, so the renderer hands the component a resolved { url, alt, ... } object.
  • features is a list of objects. Its sub-fields go under settings.item_settings.fields, the same shape a content model’s list field uses.
  • styles picks the Style-tab panels. Feature Grid has no typography panel, 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.

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
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.

The public route. / renders the entry with slug home, and /about renders the entry with slug about.

app/[[...slug]]/page.tsx
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
"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.

The route the model’s Preview URL points at.

app/preview/[slug]/page.tsx
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.

Terminal window
npm run dev

Open http://localhost:3000. Until a home page is published, you see a 404.

To check the production build:

Terminal window
npm run typecheck
npm run build

Both routes are dynamic, so the build does not contact your instance.

  1. Go to Content Management → Content, open Pages, and click New Page. Because Open entries in Page Builder is on, the Page Builder opens.
  2. On the Data tab, set Title to Home and the slug to home, then click Save Changes. The canvas loads http://localhost:3000/preview/home and the status changes from Waiting for preview to Preview connected.
  3. On the Blocks tab, find Hero and Feature Grid in the palette under Custom · Marketing. Drag Hero onto the canvas.
  4. 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.
  5. Drag Feature Grid below the Hero. Click Add feature to add items.
  6. 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.
  7. Click Save Changes, then publish: use the save button’s menu and choose Save and Publish.
  8. 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.

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.