npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

payload-canvas

v0.6.13

Published

Payload Canvas: a visual drag-and-drop website builder for Payload CMS 3. Nested layout blocks, Tailwind styling, sections, templates, live AI editing over MCP, and the React renderer for your site.

Readme

Payload Canvas

A visual page builder for Payload CMS 3. It adds a full-screen builder to the collections you choose. Editors drag blocks onto a live canvas, nest them without limit, and style them with Tailwind classes. AI agents can build and edit the same pages over MCP, and an open editor shows each AI change as it happens.

The npm package is payload-canvas.

  • Works in any Payload 3.90+ app on Next.js 16 and React 19.
  • The layout is one JSON field per document. Nothing changes in your other fields.
  • The site renders the layout with payload-canvas/react (React Server Components), or with your own renderer.
  • Save, drafts, autosave, versions and access control stay Payload's own.
  • Several people (and AI agents) can edit one page at the same time. See Multiplayer editing.

One package holds everything: the Payload plugin and admin editor (payload-canvas), and the React renderer and canvas runtime for your site (payload-canvas/react). See Entry points.

Quick start. Add the builder to an existing Payload app with the install guide (about ten minutes). Or create a new project from the starter app:

npx create-payload-canvas my-website

The starter also has a calmer Payload admin: a sidebar in groups with icons, a neutral look in light and dark mode, list cells that show values by field type (a check mark, option chips, short dates, "3 links", a rich text excerpt) instead of raw code, array rows named by their content, and a dashboard with quick actions, recent edits, open comments, form messages, site checks, broken links (a 404 log and links to missing pages), unused media, scheduled publishes and optional Plausible or Umami numbers. Each part is plain code in src/admin/ of the starter. The CLI asks which parts to keep (see Features).

Contents

  1. Requirements
  2. Install
  3. The builder view
  4. Inline editing
  5. Plugin options
  6. Rendering the layout on your site
  7. Server components in the canvas
  8. Custom blocks
  9. Using existing Payload blocks
  10. Form builder
  11. Sections
  12. Styling
  1. Animations
  2. Theme
  3. Templates and binding
  4. References and Used in
  1. Localization
  2. AI assistant
  3. AI editing over MCP
  4. Multiplayer editing
  1. Production and Docker
  2. Deploying
  3. Troubleshooting
  4. Limits

Requirements

  • payload, @payloadcms/ui, @payloadcms/richtext-lexical 3.90 or later (Payload 3 only, not the Payload 4 canary)
  • next 16.3 or later, react and react-dom 19.2 or later
  • tailwindcss 4.3 or later (the plugin compiles your Tailwind entry CSS)
  • Node.js 20.9 or later
  • Any Payload database adapter. Postgres and SQLite store the layout as jsonb/JSON.

You do not need transpilePackages or a sass install. The package ships compiled JavaScript. The admin styles are .scss files, and Next compiles them with the sass that @payloadcms/next already installs, the same way it compiles Payload's own admin styles.

Peer dependencies:

| Package | Range | Needed for | |---|---|---| | payload, @payloadcms/ui, @payloadcms/richtext-lexical | ^3.90.0 | everything | | next | ^16.3.0 | everything | | react, react-dom | ^19.2.0 | everything | | tailwindcss | ^4.3.0 | the CSS compile on save and in the canvas | | @anthropic-ai/sdk | >=0.131.0, optional | only the /ai/anthropic adapter | | payload-mcp-toolkit | >=0.9.0, optional | only builderMcpTools() (/mcp) | | zod | ^3.25 \|\| ^4, optional | only builderMcpTools() (/mcp) |

Install

These steps start from a blank Payload app with Postgres:

npx create-payload-app@latest -n my-site -t blank --db postgres --use-pnpm

They were tested step by step on such an app with Payload 3.90.2, Next.js 16.3.3, React 19.2.6, Tailwind 4.3.3, TypeScript 5.7 and pnpm 10, in next dev and in next build + next start. An existing Payload app works the same way: skip what you already have.

1. Add the package

pnpm add payload-canvas tailwindcss @tailwindcss/postcss postcss

With npm: npm install payload-canvas tailwindcss @tailwindcss/postcss postcss.

2. Add a collection with pages

Any collection works. This one uses drafts, so the editor gets Save Draft and Publish.

// src/collections/Pages.ts
import type { CollectionConfig } from 'payload'

export const Pages: CollectionConfig = {
  slug: 'pages',
  admin: { useAsTitle: 'title' },
  access: {
    // Signed-in users see drafts. Visitors see published pages only.
    read: ({ req }) => (req.user ? true : { _status: { equals: 'published' } }),
  },
  versions: { drafts: true },
  fields: [
    { name: 'title', type: 'text', required: true },
    { name: 'slug', type: 'text', required: true, unique: true, index: true },
  ],
}

3. Make one block list

The plugin, the site and the canvas must use the same block list. Put it in its own file. Import blocks from payload-canvas/blocks: that entry has no server code, so client components can import it too.

// src/builder.ts
import { defaultBlocks } from 'payload-canvas/blocks'

export const blocks = defaultBlocks({ mediaCollection: 'media', linkCollections: ['pages'] })

4. Add the Tailwind entry CSS

This file is your site's CSS. The plugin also compiles each page's classes from it. The variables on :root are defaults: the plugin's Theme global overrides them, so editors can change the colors, fonts and radius in the admin. See Theme.

/* src/app/(frontend)/globals.css */
@import "tailwindcss";

/* Defaults. The Theme global (admin > Theme) overrides them. */
:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.145 0 0);
  --primary: oklch(0.55 0.2 260);
  --primary-foreground: oklch(0.985 0 0);
  --secondary: oklch(0.97 0 0);
  --secondary-foreground: oklch(0.205 0 0);
  --muted: oklch(0.97 0 0);
  --muted-foreground: oklch(0.556 0 0);
  --accent: oklch(0.97 0 0);
  --accent-foreground: oklch(0.205 0 0);
  --border: oklch(0.922 0 0);
  --radius: 0.625rem;
}

@theme {
  --font-sans: ui-sans-serif, system-ui, sans-serif; /* the theme's body font replaces it */
  --font-heading: var(--font-sans);                   /* `font-heading`; the theme's heading font replaces it */
}

@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --color-primary: var(--primary);
  --color-primary-foreground: var(--primary-foreground);
  --color-secondary: var(--secondary);
  --color-secondary-foreground: var(--secondary-foreground);
  --color-muted: var(--muted);
  --color-muted-foreground: var(--muted-foreground);
  --color-accent: var(--accent);
  --color-accent-foreground: var(--accent-foreground);
  --color-border: var(--border);
  --radius-sm: calc(var(--radius) - 4px);
  --radius-md: calc(var(--radius) - 2px);
  --radius-lg: var(--radius);
  --radius-xl: calc(var(--radius) + 4px);
}
// postcss.config.mjs
export default {
  plugins: { '@tailwindcss/postcss': {} },
}

The site layout imports this file in step 7. The blank template has src/app/(frontend)/styles.css with a dark style for its welcome page, and its rules fight Tailwind's. Delete the file and the import './styles.css' line in src/app/(frontend)/page.tsx. Step 7 replaces the layout that imports it too.

5. Add the plugin

// src/payload.config.ts
import { websiteBuilder } from 'payload-canvas'
import { blocks } from './builder'
import { Pages } from './collections/Pages'

export default buildConfig({
  collections: [Users, Media, Pages],
  // ...
  plugins: [
    // other plugins first
    websiteBuilder({
      collections: { pages: { url: (doc) => `/${doc.slug}` } },
      blocks,
      css: { entry: 'src/app/(frontend)/globals.css' },
    }),
  ],
})

Keep websiteBuilder last in plugins. See Troubleshooting.

Then regenerate the import map and the types:

pnpm payload generate:importmap
pnpm payload generate:types

6. Add the canvas route

The editor shows the page in an iframe. The iframe loads a route in your app, so the canvas uses your real block components and your CSS. Give the route its own root layout, without your site header and footer, and import your site's CSS in it.

// src/app/(builder-canvas)/layout.tsx
import { ThemeStyle } from 'payload-canvas/react/server'
import config from '@payload-config'
import { getPayload } from 'payload'
import type { ReactNode } from 'react'

// Your site's CSS: it holds every class Tailwind found in your files.
import '../(frontend)/globals.css'

export default function CanvasLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      {/* The same body classes as your site layout. */}
      <body className="font-sans antialiased">
        {/* The Theme global's variables and fonts (React moves them into the head). `live` reloads
            them after a theme save. Not in a <head> element: `live` adds a client component, and
            Next's metadata then fails to hydrate on some loads. */}
        <ThemeStyle payload={getPayload({ config })} live />
        {children}
      </body>
    </html>
  )
}

The page is a server component that imports the server action, and passes it to a small client component that renders BuilderCanvas:

// src/app/(builder-canvas)/builder-canvas/page.tsx (a server component: no 'use client')
import { builderCanvas } from './actions'
import { CanvasClient } from './CanvasClient'

export default function CanvasPage() {
  return <CanvasClient server={builderCanvas} />
}
// src/app/(builder-canvas)/builder-canvas/CanvasClient.tsx
'use client'

import { BuilderCanvas, type BuilderCanvasProps } from 'payload-canvas/react/canvas'
import { blocks } from '@/builder'

export function CanvasClient({ server }: { server: BuilderCanvasProps['server'] }) {
  return <BuilderCanvas blocks={blocks} server={server} />
}

Keep the page a server component. The server action returns React Server Component output that holds client components: yours inside server-rendered blocks (an image, a carousel), and the builder's own (slot outlets, the page frame's layout). Next registers them in the route's client manifest only when a server component of the route imports the action. When a 'use client' page imports it, they are missing, and the canvas shows "Could not find the module … in the React Client Manifest". Client-only props (plugins, components, resolveLink) belong in CanvasClient.

// src/app/(builder-canvas)/builder-canvas/actions.ts
'use server'

import config from '@payload-config'
import { createCanvasServer, type CanvasServerRequest } from 'payload-canvas/react/server'
import { blocks } from '@/builder'

const canvas = createCanvasServer({ config, blocks })

export async function builderCanvas(request: CanvasServerRequest) {
  return canvas(request)
}

The server action renders the blocks the canvas cannot render itself: server components that load data. It is optional. Without it, those blocks show "Name: no preview in the editor". See Server components in the canvas.

How the canvas gets its CSS, in this order:

  1. Your site's CSS. Tailwind puts every class it finds in your files into it, so your components' own classes work on the canvas as on the site. Blocks do not have to list them in classes.
  2. The theme (ThemeStyle). Its :root:root rule wins over the :root defaults in your CSS.
  3. The CSS for the classes in the layout and in each block's classes. The canvas compiles it in the browser (about 4 ms per new class) from the same entry file as the save hook, and puts it after your CSS. On the site, the generated CSS also comes after your CSS, so the canvas shows the same result. This CSS also holds Preflight and your base styles a second time. Both copies come from the same entry file, so they are identical and change nothing.

The generated CSS styles only block elements, so it never changes the order of your own classes. Every rule in it matches only elements with the class builder-css, and RenderLayout adds that class to the className of every block with classes. Example: a header layout uses flex, and your component has flex md:grid. Your component's element has no builder-css, so the generated flex does not reach it, and your site's CSS makes it grid from md up. A block's element has all its classes in the generated CSS, which is in Tailwind's order and comes last. The rules use :where(.builder-css), which adds no specificity.

Earlier versions told you to leave your site's CSS out of the canvas, because the canvas compiles the full CSS for the layout's classes itself. That missed the classes your components use themselves. If you skip the import, the canvas still works, but only the classes in the layout and in each block's classes have CSS.

The same page also renders the library's section thumbnails: the editor loads it hidden, with ?mode=thumbnail, when the Sections tab needs pictures. Nothing to add for that. A thumbnail copies the page's stylesheets into the picture, and it waits for server blocks before it takes the picture.

The default path is /builder-canvas. Change it with the canvasPath option. If your app has a single root app/layout.tsx, move the site into a route group first, so the canvas can have its own root layout. Payload's templates already use (frontend) and (payload) groups.

7. Render pages on the site

The site layout imports your CSS and renders the Theme global's variables and fonts in the <head>. Replace the blank template's layout with this one:

// src/app/(frontend)/layout.tsx
import { ThemeStyle } from 'payload-canvas/react/server'
import config from '@payload-config'
import { getPayload } from 'payload'
import type { ReactNode } from 'react'

import './globals.css'

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head>
        {/* The promise, not the instance: the read stays inside ThemeStyle's <Suspense> (Cache Components). */}
        <ThemeStyle payload={getPayload({ config })} />
      </head>
      <body className="font-sans antialiased">{children}</body>
    </html>
  )
}

The page route loads a page by its slug and renders its layout:

// src/app/(frontend)/[slug]/page.tsx
import type { GeneratedCss } from 'payload-canvas'
import { normalizeLayout } from 'payload-canvas/core'
import { RenderLayout } from 'payload-canvas/react'
import { loadLayoutData } from 'payload-canvas/react/server'
import config from '@payload-config'
import { draftMode } from 'next/headers'
import { notFound } from 'next/navigation'
import { getPayload } from 'payload'

import { blocks } from '@/builder'

type Props = { params: Promise<{ slug: string }> }

export default async function Page({ params }: Props) {
  const { slug } = await params
  const { isEnabled: draft } = await draftMode()
  const payload = await getPayload({ config })
  const { docs } = await payload.find({ collection: 'pages', where: { slug: { equals: slug } }, limit: 1, draft })
  const page = docs[0]
  if (!page) notFound()

  const layout = await loadLayoutData(normalizeLayout(page.layout), blocks, payload, { draft })
  return <RenderLayout layout={layout} blocks={blocks} css={(page.layoutCss as GeneratedCss | null)?.css} />
}

page.layout and page.layoutCss exist in payload-types.ts after generate:types (step 5). The draft flag shows drafts only in Next's draft mode, so the site shows the published version.

8. Add the standalone tracing lines

Skip this step if you do not use output: 'standalone'. On every save, the plugin compiles Tailwind classes. The compile reads your CSS entry and Tailwind's CSS files from disk, so Next's file tracer cannot see them. List them in next.config.ts:

const nextConfig: NextConfig = {
  output: 'standalone',
  outputFileTracingIncludes: {
    '/*': [
      './src/app/\\(frontend\\)/globals.css',
      './node_modules/tailwindcss/package.json',
      './node_modules/tailwindcss/*.css',
      // If the entry imports payload-canvas/forms/widths.css:
      './node_modules/payload-canvas/package.json',
      './node_modules/payload-canvas/dist/forms/*.css',
      // Add every package your CSS entry imports, e.g. './node_modules/tw-animate-css/dist/*.css'
    ],
  },
}

Escape ( and ) in route group names: the paths are globs. tracingIncludes(entry) from payload-canvas/css returns these globs for the starter's packages.

9. Turn off Next's compression

In next.config.ts, set compress: false and let your reverse proxy compress responses (see Deploying). Next's built-in gzip adds one listener to the gzip stream for each backpressure event while it streams a large HTML page. The admin and builder pages are large. In production this logs MaxListenersExceededWarning: 11 drain listeners added to [Gzip] many times. The listeners are freed when the response ends, so this is only noise, but it hides real warnings.

const nextConfig: NextConfig = {
  compress: false,
}

10. Run it

pnpm dev
  1. Open http://localhost:3000/admin and create the first user.
  2. Create a page with a title and a slug, for example about.
  3. Click the Builder tab (or Open builder on the layout field). The builder opens full screen. Click or drag blocks from the Blocks tab. Double-click text on the canvas to edit it in place, or edit it in the right panel. Style the selected block in Styles.
  4. Click Publish changes in the top bar and open http://localhost:3000/about.

In development, Payload's Postgres adapter pushes the new tables and columns on pnpm dev. Before your first production deploy, create a migration and commit it:

pnpm payload migrate:create

Run it in production with pnpm payload migrate, or with prodMigrations in postgresAdapter. Never run payload migrate on a development database that uses push. See Production and Docker.

The builder view

The builder is a full-screen admin view at /admin/builder/<collection>/<id>. It has no Payload nav and no document header: one top bar holds everything.

How editors open it:

  • the document's Builder tab (a link to the view),
  • the Open builder button on the layout field in the normal Edit view (a new document must be saved first). The field also shows "3 sections · 24 blocks" and the list of sections,
  • the old tab URL /admin/collections/<collection>/<id>/builder, which redirects to the view,
  • with editor.openInBuilder: true, a click on a saved document in the collection list.

Open documents in the builder. websiteBuilder({ editor: { openInBuilder: true } }) (default false) makes the builder the document's main view. Opening a saved document goes straight to /admin/builder/<collection>/<id>. Payload's form stays for new documents until their first save, in drawers, for users who cannot save, for documents in the trash, and with ?form=1 in the URL. The builder's All fields menu item opens the form with ?form=1. The form then stays for that document until a full page load, or until you open the builder for it again. The builder's back arrow goes to the collection list. A collection that sets its own admin.components.views.edit.default keeps it. The option registers payload-canvas/client#DocumentEditView, so run pnpm payload generate:importmap after you turn it on.

The top bar, left to right:

  • Back to the document's Edit view (to the collection list with openInBuilder), the admin icon (to the dashboard), and Collection › Title. Click the title to rename the document: Enter or leaving the field saves it (as a draft when the collection has drafts). Escape cancels.
  • The status: Draft (never published), Published, or Changed (published, with newer draft changes). Hover it for the last change, the creation date, the last publish and the number of versions (opens the Versions drawer).
  • Undo and redo, the canvas width and the active breakpoint. Fluid (the default) fills the space between the sidebars, so the breakpoint follows the free width. Desktop (1280 px), tablet, mobile and a custom width are fixed widths. In a template: the sample document the canvas previews.
  • The people on the page, and the save state: Saving… while changes are on their way, then Saved · 12:04.
  • Preview opens the draft preview (the collection's admin.livePreview.url, else admin.preview), or the public page (the plugin's url option), in a new tab.
  • Page settings opens the document's own edit form in a Payload drawer: title, slug, SEO, and for a template its collection and sample document. The top bar updates after each save.
  • The AI assistant (with the ai option), the keyboard shortcuts, and Publish changes. Its menu has Unpublish, Revert to published (drops all draft changes, after a confirmation), Versions and API (Payload's own screens, in a drawer over the builder), All fields (Payload's edit form) and a link to the live page. In the Versions drawer, open a version to compare it, then Restore as draft: every open editor gets the restored layout, and the site keeps the published version until you publish.

The left sidebar has three tabs: Layers (the block tree), Blocks and Sections (only when there are sections to insert or a place to save them). Each fills the sidebar. Alt+1, Alt+2 and Alt+3 (⌥1, ⌥2, ⌥3 on a Mac) open them, and the browser keeps the last tab. As in Webflow, adding a block or section from Blocks or Sections opens Layers: a click shows the new block there, selected; a drag opens Layers when it starts, so you can drop on the canvas or anywhere in the tree (an empty tree too).

The sidebars resize: drag the edge, or focus it with Tab and use the arrow keys (Shift for larger steps). A double-click or Enter resets the default size. The sizes are kept in the browser.

The canvas frame resizes too. Drag the handle on its left or right edge: the frame stays centered and shows its width and breakpoint while you drag. Hold Shift to snap to the breakpoint and device widths. The new width is a custom width. Double-click a handle (or press Enter on it) to go back to the device you started from, or to fluid. The stage scrolls sideways only when the frame is wider than the stage, for example a fixed width at 100 % zoom.

Publishing. All editors of a document share one live session (see Multiplayer editing). The session saves the layout as a draft about a second after each change. Publish changes saves what is still unsaved, then publishes with Payload's Local API as the signed-in user, so access control, hooks and versions work as usual. Unpublish sets the document back to draft. Revert to published loads the published version into the session, so every open editor reloads the canvas, and saves it again. Every open editor sees the new status at once.

Save rules. Every save checks the layout. A broken layout (wrong shape, duplicate ids, unknown block types, wrong prop types) blocks every save. Unfinished blocks do not block drafts, autosave or live sessions: a missing required prop, a prop whose value does not match its builderFormat (for example a half-typed video URL), a value outside the field's limits (minLength, maxLength, min, max, minRows, maxRows, an email address without a valid form), a message from the field's own validate function, a block in a slot that refuses it, and a binding the prop cannot use. All of these can be true while someone is still typing. They block Publish only, and the problem list names the block ("Video: this YouTube link does not point to a video", "Product: SKU: use a SKU like ABC-123"). Click a problem to select the block. See Validation, hooks and access on block fields.

Adding blocks on the canvas. Hover the canvas: a small + shows on the edge between two blocks next to the pointer (above or below in a column, left or right in a row), and in the middle of an empty container. Click it to open a picker with the blocks and sections that fit there (slot rules apply). Type to search, use the arrow keys and Enter, or click. The new block goes in exactly that place and is selected. The + hides while you drag and while you edit text on the canvas. It does not show next to a small block (under 48 px along the list and under 160 px across, at 100 % zoom), and it never covers more than a fifth of a block: the parent gets the + instead. It also hides over the controls of interactive blocks (a carousel's arrows, a tab).

Interactive blocks on the canvas. Select a block inside a closed accordion item, a hidden tab, another slide or a closed popup, on the canvas or in Layers: the canvas opens the item, the tab or the popup, or moves to the slide, and scrolls the block into view. Arrows, dots, tab buttons and popup triggers work as on the site: a click on them selects nothing. Outlines of blocks inside a container that hides its overflow (a carousel's viewport) are cut at the container's edge.

Drag and drop. Drag a block by its row in the outline, by the grip on the selected block's bar, or from the Blocks and Sections tabs. Slot rules apply: a slot that refuses the block is never a target. Escape cancels the drag. One drop is one undo step, and collaborators see the move at once. There are two styles:

  • Drop line ('indicator', the default). A line or a box shows where the block lands. Blocks move when you drop.
  • Smooth ('smooth'). The block lifts and follows the pointer. The other blocks and the outline rows slide out of the way, so a gap shows where the block lands. In a grid, blocks move into the next cell. On drop, the block slides into the gap. On cancel, it slides back.

Set the default with websiteBuilder({ editor: { dragMode: 'smooth' } }). Each user can change it with the grip button in the canvas status bar, next to the zoom. The choice stays in that browser. When the system asks for less motion (prefers-reduced-motion: reduce), the editor always uses the drop line. Both styles use the same drop rules, so the same drop gives the same result. Smooth mode moves blocks with CSS transforms only and never changes the layout before the drop.

Drop outlines. While you drag, a thin dashed line marks every container on the canvas that takes the block, by the same slot rules. The container the block would drop into gets a stronger line, and its name when a drop line shows. The lines are drawn over the canvas, so the page never moves. Turn them off in the same grip menu (Outline where blocks can drop), or set the default with websiteBuilder({ editor: { dropOutlines: false } }).

Access. The view sends signed-out visitors to the login page and back. Users without admin access go to Payload's "unauthorized" page. A document that does not exist, or a collection without the builder, shows "not found". A user who can read but not update the document gets the normal Edit view.

Content mode for clients

Content mode lets a site owner's client change text, images and links without breaking the design. Webflow's Editor and Elementor's role manager work the same way.

websiteBuilder({
  editor: {
    // Users with the "editor" role get content mode. Everyone else keeps full rights.
    canEditDesign: ({ user }) => user?.role !== 'editor',
  },
})

The default is true for everyone, so nothing changes until you set it. A function that throws counts as false. The starter adds a Role field (Admin or Editor) to its users and uses it here.

In content mode, editors can:

  • change text, textarea, rich text, upload (image and video), email and link props in the inspector,
  • edit text on the canvas,
  • in a block marked Editors can add, remove and reorder its items: duplicate, delete and reorder its direct children (FAQ items, team cards). They cannot restyle them.

They cannot add, move, duplicate or delete other blocks, and they see no Blocks or Sections tab, no + buttons, no drag and drop, no Styles, Motion or Advanced tab, no classes, section variants, visibility conditions, bindings or page regions. Design props (selects, checkboxes, numbers, relationships, heading levels) are hidden too. The top bar shows Content mode.

Users with design rights get Preview as client (the eye icon) in the top bar. It shows the editor as clients see it. Turn it off to edit the design again.

Which props are content. The field type decides: text, textarea, richText, upload, email and link groups (linkField()) are content. A group, row or array is content when every field inside it is. Everything else is design. Override it per field with admin.custom.builderContent:

{ name: 'anchor', type: 'text', admin: { custom: { builderContent: false } } }, // a setting, not text
{ name: 'badge', type: 'select', options: ['New', 'Sale'], admin: { custom: { builderContent: true } } },

Mark a list. Select the block that holds the items, open the Advanced tab and turn on Editors can add, remove and reorder its items. It is stored as editableItems: true on the block. A new item must be a copy of an item already there.

The server enforces it. Every write checks the change against the layout before it: the live editor's commits, the operations endpoint, the MCP tools, the AI assistant, editable class renames, and saves through REST, GraphQL or the Edit view. A design change from a user in content mode is refused with a 403 and a message such as In content mode you can change only text, images and links. "Hero" cannot be moved. The editable classes collection and the theme global are design too: content mode cannot create, update or delete them. Payload's Restore of a version is checked the same way: a version with another design is refused with This version has a different design, so only a designer can restore it., and a version that differs only in content restores. (Payload's Restore button shows its own generic error; the API response carries the message.) Publishing, unpublishing and Revert to published stay allowed: they never bring back a design that is not already published.

Inline editing

Text and images edit in place on the canvas, in every block: the default blocks, your own components, and existing Payload components adopted with fromPayloadComponents. You do not need to change your components.

Text

  • Hover text that can be edited: the cursor turns into a text cursor and a faint dashed outline shows.
  • Double-click the text, or select the block and press Enter. Type. Escape ends editing. In a one-line text field, Enter ends it too. In a textarea, Enter adds a line break and Ctrl+Enter ends editing.
  • Rich text opens a small Lexical editor with a toolbar (paragraph and heading types, lists, bold, italic, links). Ctrl+K adds a link.
  • One editing session is one undo step. Collaborators see the typing live.
  • A prop bound to document data, and a prop the user may not change (field access), stay closed: the editor says why.

How the canvas finds the text. After a block renders, the canvas compares the block's props with the text of its elements:

  • It looks at text, textarea and richText fields, also inside groups, array rows (headingLines.0.text, cards.2.heading) and hasMany text fields (tags.1). A field with no value counts as its defaultValue, as your component renders it.
  • An element matches a prop when its text equals the prop's value. Runs of whitespace count as one space. Rich text matches without any whitespace, because paragraphs have no separator in the DOM.
  • The smallest element with that text wins. A value split across elements (an accent word in a <span>) maps to the element around both parts. Icons and empty decoration inside the element stay out of the editing.
  • Rich text maps to its container (the <div> around the paragraphs), never to one paragraph, so the editor can add paragraphs.
  • The canvas does not guess. Nothing is marked when one value shows in two visible elements, when two props have the same text, or when one element matches two props.
  • Blocks rendered on the server (Server components in the canvas) map the same way. When editing ends, the value is saved and the server renders the block again.

Limits. The text on screen must equal the prop. These cases stay in the inspector:

  • Text your component changes in JavaScript: .toUpperCase(), truncation, a heading split into words, markup such as *accent* that becomes a <span>. (CSS text-transform: uppercase is fine: the DOM text is unchanged.)
  • A prop shown inside a sentence with other text in the same element (<p>Call us on {phone}</p>).
  • The same text twice on the block (a marquee that repeats its items).

Mark the element yourself when the automatic mapping cannot find it. editableText(mode, path) returns the attribute in the canvas and nothing on the site. A mark always wins over the automatic mapping.

import { editableText, type PayloadBlockProps } from 'payload-canvas/react'

export function Hero({ heading, builder }: PayloadBlockProps<HeroBlock>) {
  // The site shows "*Your* day" with an accent span. The mark tells the canvas which prop it is.
  return <h1 {...editableText(builder.mode, 'heading')}>{heading}</h1>
}

Put the mark on the element that holds the text and nothing else.

Images

Every image that shows an upload prop can be replaced on the canvas:

  • Hover the image: a Replace chip shows inside its top right corner (above a small image, and lower down when the selected block's action bar sits in that corner). It uses the part of the image that shows, so an image cut off by a carousel or a card gets the chip on its visible part. Text over an image (a hero heading) wins: hover a free part of the image.
  • Double-click the image, or click the chip, to open the media popover:
    • Choose from library: Payload's list drawer for the field's upload collection.
    • Upload a file: a file picker. The file goes to the upload collection with its name as alt text.
    • Generate image: the AI image action. Shown when ai.images is set up. See Image generation.
    • Remove: empties the field. Not shown for required fields.
    • Alt text: saved in the block's own alt prop when it has one next to the upload (alt, altText, <field>Alt). Otherwise it is saved on the media document, so it changes everywhere that file is used.
  • Drag an image file from your computer onto an image on the canvas to upload it and replace the image.
  • When several uploads lie under the pointer (a video and its poster, a background under a photo), the popover has a list to pick one.
  • Every replace is one undo step, and collaborators see it at once. Alt text saved on the media document is not part of the undo history.

How the canvas finds the images. It reads the URLs of <img> (also srcset and <picture> sources), <video> (the file and the poster), inline background-image styles and, for uploads still not found, CSS backgrounds from classes. It compares them with every URL of the block's media documents: the file, the thumbnail and each image size. next/image URLs (/_next/image?url=…) count as the image they wrap. Uploads in array rows (photos.3.image) and hasMany uploads (gallery.2) work too.

Limits. An image whose URL is not one of the block's uploads cannot be replaced on the canvas (an image from page data, a fixed file in /public). An empty upload field has no URL to match: mark its placeholder. Images inside rich text are edited in the inspector.

Mark the element yourself with editableImage(mode, path). The default Image block marks its image and its empty placeholder this way:

import { editableImage } from 'payload-canvas/react'

{photo ? <img {...editableImage(builder.mode, 'photo')} src={photo.url} alt="" /> : <div {...editableImage(builder.mode, 'photo')}>Add a photo</div>}

Plugin options

websiteBuilder({
  collections: {
    pages: { field: 'layout', url: (doc) => `/${doc.slug}` },
    posts: { templates: true, url: (doc) => `/blog/${doc.slug}` },
  },
  blocks,                      // default: defaultBlocks()
  listCollections: ['testimonials', 'team'], // more collections for the collection list block
  sections,                    // ready-made sections for the library and AI tools
  savedSections: { slug: 'builder-sections' }, // sections people save; `false` turns it off
  css: {
    entry: 'src/app/(frontend)/globals.css',
    plugins: { '@tailwindcss/typography': typography },
  },
  canvasPath: '/builder-canvas',
  templates: { slug: 'builder-templates', admin: { group: 'Design' } },
  live: { heartbeatMs: 15000 },
  ai: { adapter: openRouterAdapter({ apiKey: process.env.OPENROUTER_API_KEY }) }, // the AI assistant
  theme: { admin: { group: 'Settings' } }, // the Theme global; `false` leaves it out
  editor: { dragMode: 'smooth', openInBuilder: true }, // drag and drop style; open saved documents in the builder
  references: { usedIn: ['media'], protectDelete: ['media'] }, // "Used in" lists; `false` turns them off
  forms: true,                 // the form builder for @payloadcms/plugin-form-builder
})

| Option | Type | What it does | |---|---|---| | collections | Record<slug, { field?, url?, templates? }> | The collections that get the builder. Required. | | collections[slug].field | string | Name of the builder's field. Default layout. Its type decides the storage. A Payload blocks field of the collection: the builder edits that field itself, the one source of truth (see Using existing Payload blocks). Otherwise the builder's JSON layout: the generated CSS goes in <field>Css, and a json field with this name (also inside rows, collapsibles or unnamed tabs) is reused and moved to the top level. | | collections[slug].url | (doc) => string | The frontend path of a document. AI tools use it for preview links. The collection list block uses it for links. | | collections[slug].templates | boolean | Documents render through templates. See Templates. | | collections[slug].legacyFields | string[] | Top-level fields the builder replaced but the collection still has (the old blocks field after migrateBlocksField). Publish in the builder keeps their published value, so only the builder content goes live. See Using existing Payload blocks, step 7. | | collections[slug].regions | { name, label?, fields, panel?, sections? }[] | Fixed parts of the page that show ordinary document fields outside the layout (a header made of the title and an image). The builder shows and edits the whole page. Left out: the layout alone. panel: true: the right panel edits the region's fields itself, and shows them when no block is selected (the form builder's settings use it). sections: [{ label, fields }] puts a panel region's fields under headings that open and close (the first starts open); a group field in no section gets a section of its own. See Whole-page editing. | | collections[slug].sections | false | The editor of this collection offers no sections: no Sections tab and no "Save as section…". The forms option sets it. | | collections[slug].localization | 'props' \| false | With Payload localization on: 'props' (the default) translates localized props in one shared layout; false keeps one set of values. See Localization. | | blocks | BlockDefinition[] | The blocks editors can use. Default defaultBlocks(). | | listCollections | string[] | More collections the collection list block can show, after the collections with a url. Use it for data collections without pages of their own, such as testimonials or team members. Their items have no $url. Each slug must be a collection of the config. Pass the same list to builderMcpTools. | | sections | SectionDefinition[] | Ready-made sections. See Sections. | | savedSections | { slug?, access?, admin?, hooks? } \| false | The collection for sections people save in the editor. Default slug builder-sections; default access: every signed-in user. false turns it off. See Saved sections. | | css.entry | string | Your Tailwind entry CSS, absolute or relative to process.cwd(). Required, also when the builder edits a Payload blocks field: the canvas compiles Tailwind against it, and the editor reads its breakpoints and theme from it. Without it the app does not start, and the error says what to pass. | | css.plugins | Record<id, plugin> | Tailwind plugins by the id your CSS uses in @plugin "<id>". Pass the imported module, so Next bundles it. Every @plugin line of the entry needs one. At startup the plugin compiles the entry once and logs an error that names each missing plugin. Until you add it, /api/builder/canvas-css and /api/builder/style-tokens answer 500 with the same message, and the editor shows it. | | canvasPath | string | The canvas route. Default /builder-canvas. | | templates.slug | string | Slug of the templates collection. Default builder-templates. | | templates.hooks | CollectionConfig['hooks'] | Hooks for the templates collection, for example to revalidate pages. | | templates.admin | CollectionConfig['admin'] | Merged into the templates collection's admin options, for example group or hidden. | | live.heartbeatMs | number | Interval of the keep-alive message on the live event stream. Default 10 s. | | multiplayer | boolean | Deprecated, no effect. Several people can always edit a layout at once, and Payload's document lock stays on for the other fields. See Multiplayer editing. | | ai | AiOptions | Turns on the AI assistant in the editor. See AI assistant. | | theme | ThemeOptions \| false | The Theme global. On by default. false leaves it out. See Theme. | | editor.dragMode | 'indicator' \| 'smooth' | The default drag and drop style. indicator (the default) shows a drop line; smooth lifts the block and moves the other blocks out of the way. Each user can change it in the editor. See The builder view. | | editor.dropOutlines | boolean | Thin outlines of every container that takes the dragged block, while you drag. Default true. Each user can change it in the editor. See The builder view. | | editor.canEditDesign | ({ req, user }) => boolean \| Promise<boolean> | Who may change the design. Users for whom it returns false get content mode: text, images and links only. Default: everyone. See Content mode for clients. | | editor.openInBuilder | boolean | Opening a saved document goes straight to the builder instead of Payload's form. Default false. Run generate:importmap after you turn it on. See The builder view. | | css.fontFamilies | (payload) => Record<name, family> | Font families set at runtime some other way than the Theme global, for the Styles panel's Font list. Its names win over the theme's. | | references | { field?, usedIn?, protectDelete?, maxListed? } \| false | Which media and documents each layout uses: "Used in" lists and delete protection. On by default. false turns it off. See References and Used in. | | forms | { collection? } \| boolean | The form builder for the forms of @payloadcms/plugin-form-builder (add that plugin first). Default slug forms. See Form builder. | | comments | { slug?, access?, admin?, hooks? } \| boolean | Comments on blocks in the builder, stored in a builder-comments collection. On by default. false turns it off. See Comments on the canvas. |

For each listed collection the plugin adds:

  • the layout field (json) with the editor as its field component,
  • a hidden <field>Css field that stores { hash, css },
  • a hidden virtual rich text field, when a block has a rich text prop,
  • a hidden builderRefs relationship field that lists the media and documents the layout uses (see References and Used in),
  • the Builder document tab, a link to the full-screen view (/admin/builder/<slug>/<id>; the plugin adds this root view once for all collections),
  • a beforeChange hook that validates the layout and compiles its CSS, takes the layout from the live session while one is open, and rejects a save from an out-of-date form (see Multiplayer editing),
  • a beforeOperation and an afterChange hook for the live session and Payload's document lock.

It also adds these endpoints (signed-in users only):

| Endpoint | Use | |---|---| | GET /api/builder/canvas-css | The stylesheets the canvas compiles from. | | GET /api/builder/style-tokens | Theme tokens and class names for the Styles panel. | | GET /api/builder/live/:collection/:id/events | Server-Sent Events stream of one document's live session. | | POST /api/builder/live/:collection/:id/commit | Applies one batch of operations to the live session (editors). | | POST /api/builder/live/:collection/:id/awareness | Sends your selection and pointer to the other editors. | | POST /api/builder/live/:collection/:id/operations | Applies operations to the live session and returns the new layout (scripts and integrations). | | GET /api/builder/live/:collection/:id/meta | What the builder's top bar shows: title, status, dates, versions count, preview links. | | POST /api/builder/live/:collection/:id/publish | Saves the live session, then publishes the document. | | POST /api/builder/live/:collection/:id/unpublish | Sets the document back to draft. | | POST /api/builder/live/:collection/:id/revert | Drops the draft changes: the live session and the draft get the published version. | | POST /api/builder/live/:collection/:id/restore | Body { versionId }. Restores an older version: the live session and the draft get its layout. With drafts it becomes the draft. | | POST /api/builder/live/:collection/:id/validate | Body { block }. Runs the validate functions of the block's props and returns { problems: [{ propPath, message }] }. The inspector calls it while someone edits. | | POST /api/builder/ai/chat | The AI assistant (only with the ai option). Streams Server-Sent Events. | | GET /api/builder/theme | The theme as { css, fontsHref } (with the theme on). It uses the global's read access, so it is public by default. |

Entry points

| Import | Use it in | Holds | |---|---|---| | payload-canvas | payload.config.ts (server) | websiteBuilder, defineBlock, defaultBlocks, fromPayloadBlocks, migrateBlocksField, formSubmissionConditions, types | | payload-canvas/forms | anywhere | form display conditions (withFormConditions, hiddenFormFields, describeConditions), field settings (withFormFieldSettings, withStoredWidth), answer checks (formAnswerProblem, fileProblem, filesProblem), the extra field types (moreFormFields), the email fields (withFormEmailFields) and merge tags (mergeTags, formEmailMessage), formFieldType, formFieldSlug, FORM_SETTINGS_REGION, forms on pages (formBlocks, formBlockMode, formBlockFields, formDataFromBlock, formBlockFromDoc, withSavedFormFields). See Form builder. | | payload-canvas/blocks | anywhere | defaultBlocks, defineBlock, linkField, fromPayloadBlocks, prepareBlocks, listCollectionsOf, BUILDER_CSS_CLASS, withBuilderCssClass | | payload-canvas/blocks/client | your site's own client components | filterHref and its types. No block definitions, so it adds almost nothing to the browser's JavaScript. New in 0.6.11. | | payload-canvas/core | anywhere | layout types, normalizeLayout, validateLayout, applyOperations, tree helpers, convertPayloadBlocksLayout, toPayloadBlock, fieldReferences, rowLabel | | payload-canvas/css | server | compileClasses, getStyleTokens, tracingIncludes | | payload-canvas/theme | anywhere | themeCss, themeVariables, themeOutput, deriveColors, googleFontsHref, themeConfigOf, theme types | | payload-canvas/theme-client | Payload import map, or your own fields | ThemeColorField, ThemeFontField, ThemeSliderField | | payload-canvas/mcp | server | builderMcpTools | | payload-canvas/ai | server | the AiAdapter type and helpers for writing an adapter | | payload-canvas/ai/openrouter, /ai/cloudflare-gateway, /ai/cloudflare-workers-ai, /ai/openai-compatible, /ai/anthropic, /ai/fake | payload.config.ts (server) | one AI adapter each. See Adapters. | | payload-canvas/ai/images/openrouter, /ai/images/openai, /ai/images/cloudflare-workers-ai, /ai/images/fake | payload.config.ts (server) | one image adapter each. See Image generation. | | payload-canvas/live | server | the live sessions and endpoints | | payload-canvas/client | Payload import map only | admin client components (layout field, Builder tab, DocumentEditView for openInBuilder, ArrayRowLabel) | | payload-canvas/rsc | Payload import map only | admin server components (the builder view, the tab redirect) | | payload-canvas/react | your site and the canvas (server and client) | RenderLayout, defaultComponents, fromPayloadComponent(s), withPageData, withLinkComponent, lazyBlock, renderOnServer, editableText, editableImage, useCanvasMode, useCanvasReveal, REVEAL_EVENT, CANVAS_CONTROL_ATTRIBUTE, builtinComponents, link helpers, ThemeLive, types | | payload-canvas/react/server | server only | loadLayoutData, loadTemplate, loadTheme, ThemeStyle, createCanvasServer (they call Payload's Local API) | | payload-canvas/react/canvas | client only | BuilderCanvas, the runtime for the editor's iframe | | payload-canvas/protocol, /css-browser | used by payload-canvas/react | the editor–canvas message types, the in-browser CSS compiler. You do not import them yourself. |

Every entry point is ESM with .d.ts types. Client components keep their 'use client' directive in the build.

Rendering the layout on your site

RenderLayout is a React Server Component. It walks the layout and renders each block with its component. It comes from payload-canvas/react. The helpers that call Payload (loadLayoutData, loadTemplate, ThemeStyle, createCanvasServer) come from payload-canvas/react/server, and the editor's canvas (BuilderCanvas) comes from payload-canvas/react/canvas. See Entry points. The full page route is in Install, step 7, the canvas route in step 6, and the theme in Theme.

| Prop | Type | What it does | |---|---|---| | layout | Layout | The layout, usually after loadLayoutData. | | blocks | BlockDefinition[] | The same list as the plugin. | | css | string \| null | The generated CSS from <field>Css. Rendered in a <style> tag. | | components | Record<type, Component> | Your components, merged over the defaults. | | resolveLink | (link) => string \| null | Turns links into an href. Default: the URL, or /<slug> for a loaded document. | | context | { collection, doc } | The document a template renders. See Templates. | | pageData | Record<string, unknown> | Data the page loads once for its blocks. See Page data. | | linkComponent | client component | Renders the links of the button, link and menu blocks on the site. Default: a plain <a>. Pass next/link for client-side navigation and prefetching. It must be a client component (the menu is one and gets it as a prop). Your own components get it as linkComponent when you mark them with withLinkComponent(Component). The canvas keeps plain links. | | priorityImages | number | How many images of the first section load first (fetchpriority="high", not lazy), in page order. Default 1, usually the hero image. An image whose Load first is switched off keeps lazy loading. Videos do not count: their Load first is only what the editor sets. Give layouts further down the page (a footer) 0. |

import Link from 'next/link'

<RenderLayout layout={layout} blocks={blocks} components={components} linkComponent={Link} />

The interactive blocks (menu, carousel, popup, tabs, accordion, filter link) load their JavaScript only on pages that render them: their components load with next/dynamic. Do the same for a heavy client block of your own, in a 'use client' module:

'use client'
import dynamic from 'next/dynamic'
import { lazyBlock } from 'payload-canvas/react'

export const FormBlock = lazyBlock(dynamic(() => import('./Form').then((m) => m.FormBlock)))

lazyBlock gives the block its own Suspense boundary on the canvas, where it can mount after the page.

loadLayoutData(layout, blocks, payload, options) (from payload-canvas/react/server) loads the documents that upload and relationship props point to, in one find per collection. Options: draft, context, resolveLink.

Write a resolveLink when your collections have different routes. Pass the same function to RenderLayout and to BuilderCanvas:

import type { ResolveLink } from 'payload-canvas/react'

export const resolveLink: ResolveLink = (link) => {
  if (link.type !== 'reference') return link.url?.trim() || null
  // The loaded document after loadLayoutData, or still an ID.
  const doc = link.reference?.value as { slug?: string } | null | undefined
  if (!doc?.slug) return null
  return link.reference?.relationTo === 'posts' ? `/blog/${doc.slug}` : `/${doc.slug}`
}

Custom components

Every block component gets the same props:

type BlockComponentProps = {
  block: Block                      // the stored block
  props: Record<string, unknown>    // props after data loading and link resolution
  className?: string
  slots: Record<string, ReactNode>  // rendered children per slot
  attributes: Record<string, string>                 // spread on the root element
  partAttributes: Record<string, Record<string, string>> // by slot or part name: spread on its element
  mode: 'site' | 'canvas'
}
  • Spread attributes on the root element. In the canvas it holds data-block-id, which the editor needs to select and measure the block.
  • Spread partAttributes[slot] on the element that holds a slot's children. For a part (a slot with styles: true, or a name in parts) it also carries the part's className (see Classes on inner elements), so join it with any className you set on that element. Components written for 0.2 that read slotAttributes still work: it is the same object.
  • Props are plain data. A component can be a client component ('use client').
  • Use one components map for the site and the canvas, in a file without server code:
// src/components/blocks.ts
import type { BlockComponents } from 'payload-canvas/react'
import { PricingTable } from './PricingTable'

export const components: BlockComponents = { pricingTable: PricingTable }
<RenderLayout layout={layout} blocks={blocks} components={components} resolveLink={resolveLink} css={css} />
<BuilderCanvas blocks={blocks} components={components} resolveLink={resolveLink} />

BuilderCanvas takes the same blocks, components and resolveLink as RenderLayout. It also takes plugins (your Tailwind plugins map, see Styling) and server (a server action made with createCanvasServer, see Server components in the canvas).

Cache Components

With Next's Cache Components (cacheComponents: true in next.config), a route fails to build when a component reads data outside <Suspense> and outside 'use cache'. The plugin's server parts work with it:

  • ThemeStyle reads the Theme global inside its own <Suspense> boundary (fallback: nothing). It works as it is, in the <head> too, and the theme streams in with the dynamic part of the page. Pass payload={getPayload({ config })} (the promise), not an instance you awaited in the layout: a layout that awaits getPayload connects to the database outside any boundary, and the route fails. To put it in the static shell, render it inside your own cached component. The plugin clears the theme's cache tag (theme.cacheTag, default the slug theme-settings) after each theme save:

    // src/components/SiteTheme.tsx
    import config from '@payload-config'
    import { cacheTag } from 'next/cache'
    import { getPayload } from 'payload'
    import { DEFAULT_THEME_SLUG } from 'payload-canvas'
    import { ThemeStyle } from 'payload-canvas/react/server'
    
    export async function SiteTheme() {
      'use cache'
      cacheTag(DEFAULT_THEME_SLUG)
      const payload = await getPayload({ config })
      return <ThemeStyle payload={payload} />
    }

    Put <SiteTheme /> in the root layout's <head>. In the canvas layout, keep <ThemeStyle payload={getPayload({ config })} live /> uncached, so the editor sees each save at once.

  • loadLayoutData, loadTemplate and compilePageCss are functions that read Payload. Call them inside your own 'use cache' function (with cacheTag and a revalidate hook on the collection) or in a component under <Suspense>. Draft mode and searchParams (collection list filters and pages) are request data: read them under <Suspense>, not in a cached function.

  • The canvas route only renders BuilderCanvas (a client component). Its server action runs per request, so it needs nothing.

  • The admin. Payload's admin layout reads the session on every request. Add export const instant = false to src/app/(payload)/layout.tsx, so the admin stays a request-time route.

Server components in the canvas

Some block components load their own data: a model grid that calls payload.find, a review carousel, a blog listing, a FAQ from a collection. They are async server components, and they import Payload and your config. The canvas iframe is a client page, so it cannot import them. The canvas sends these blocks to a server action in the canvas route instead. The action renders them with your site's components and sends back the result as React Server Component output. Client components inside it (a carousel, a popup) work in the canvas as on the site. You do not change your components.

You keep two component maps:

  • The client-safe map (components): for the canvas. It must not import server code.
  • The server map: the client-safe map plus the server components. The site and the server action use it.

1. Make the server map in a file that only server code imports:

// src/components/blocks.server.ts
import { fromPayloadComponents } from 'payload-canvas/react'
import { blocks } from '@/builder'
import { ModelGridLeaf } from '@/blocks/leaves/modelGrid/component'
import { components } from './blocks'

export const serverComponents = {
  ...components,
  ...fromPayloadComponents({ modelGrid: ModelGridLeaf }, blocks),
}

2. Give it to the server action (see step 6 of Install):

const canvas = createCanvasServer({ config, blocks, components: serverComponents, resolveLink })

3. Render the site with it: <RenderLayout components={serverComponents} … />.

The canvas renders a block on the server when:

  • the block type has no component in the canvas's components (the default blocks always have one),
  • its component is an async function, or
  • its component is marked: renderOnServer(Component), or fromPayloadComponent(Component, { render: 'server' }).

createCanvasServer options:

| Option | What it does | |---|---| | config | Your Payload config. Required. | | blocks | The block definitions. Default: the plugin's blocks. | | components | The server map. | | resolveLink | The same link resolver as the site. | | pageData | ({ payload, user, document, context, locale }) => data: the page data. locale is the language the editor shows (null without localization); load your data in it. See below. | | frame | ({ doc, layout, region, … }) => ReactNode: the page around the layout, for collections with regions. See Whole-page editing. | | frameDepth | The depth of the document frame gets. Default 1. |

How it works in the editor:

  • The first render shows a gray box with the block's name. Then the server output shows.
  • After a change to the block (its props, its classes or its children), the canvas asks again 250 ms after the last change, and at the latest after 1 s. The changes of several blocks go in one request, because Next runs server actions one at a time. The old output stays on the screen until the new one is ready. It dims only when the answer takes longer than 300 ms.
  • The canvas keeps the results by the block's content, so undo shows the earlier output at once. A block that did not change never asks again while the editor is open. Animation settings are not part of the content: the canvas puts them on the output itself, so the Motion tab never asks the server. When the editor saves a document (an image's alt text), the server blocks on screen ask again and keep their output meanwhile. Data that changes somewhere else (a new post) shows when you open the editor again.
  • The data loads as on the site (loadLayoutData): the latest drafts, uploads and relationships one level deep, and the user's access for collection lists. In a template, bindings use the sample document.
  • Only signed-in users of the admin collection get an answer.
  • When a component fails, that block shows "Name: the preview failed" with the error. The other blocks are not affected.
  • Selecting, dragging, the outline and the inspector work as for every block. The editor puts the block id on the first element of the output.
  • Text and images edit on the canvas as in other blocks ([Inline editing]