focusreactive

payload plugin html preview

by focusreactive
payload-plugins
Publishing workflow
v3
^3.90.0
MIT

Overview

Summary generated from the README

Adds a live preview to the edit view of chosen collections. The CMS asks your site's own render endpoint for the page, including unsaved edits, and shows it in a sandboxed, proxied frame. Works with Astro, Eleventy, Nunjucks and similar stacks. Requires Payload 3.90 or later, the guard plugin, and a config wrapped in withAccessPolicy.

Features

  • Previews saved documents and unsaved form edits rendered by the site's real templates
  • Click-to-edit through data attributes that open the matching row, tab or field in the admin
  • Opens clicked documents from other collections in a drawer without losing unsaved edits
  • Focusing a field in the admin scrolls the preview to its block and highlights it
  • Sandboxed preview in an opaque origin, fetching only from allowed site origins via signed asset tokens
  • Preview capability granted per role through the access policy

Use cases

  • Give editors live preview on an Eleventy or Nunjucks site that cannot subscribe to Payload form data
  • Preview Astro pages rendered on demand, with click-to-edit on blocks and cards
  • Let editors check unsaved changes against real site templates without exposing the admin session

From the author

Live preview and click-to-edit for Payload CMS on any frontend that renders HTML, static sites and template engines included, no framework required

Installation

npm i @focus-reactive/payload-plugin-html-preview

37

Stars

5

Forks

33

Open Issues

Today

Last Updated

451

Weekly Downloads

v2.0.1

npm Version

177.2 KB

Unpacked Size

1

Dependencies

Repository stars

37+22 since Sep 7

Show data
Repository stars by day (UTC)
DateStars
Dec 6, 202637
Dec 5, 202637
Dec 4, 202637
Dec 3, 202637
Dec 2, 202637
Dec 1, 202636
Nov 30, 202635
Nov 29, 202635
Nov 28, 202634
Nov 27, 202634
Nov 26, 202634
Nov 25, 202634
Nov 24, 202634
Nov 23, 202634
Nov 22, 202634
Nov 21, 202634
Nov 20, 202633
Nov 19, 202632
Nov 18, 202632
Nov 17, 202632
Nov 16, 202632
Nov 15, 202632
Nov 14, 202632
Nov 13, 202632
Nov 12, 202632
Nov 11, 202632
Nov 10, 202632
Nov 9, 202631
Nov 8, 202631
Nov 7, 202631
Nov 6, 202631
Nov 5, 202631
Nov 4, 202630
Nov 3, 202630
Nov 2, 202630
Nov 1, 202630
Oct 31, 202630
Oct 30, 202630
Oct 29, 202630
Oct 28, 202630
Oct 27, 202630
Oct 26, 202630
Oct 25, 202630
Oct 24, 202629
Oct 23, 202629
Oct 22, 202629
Oct 21, 202629
Oct 20, 202629
Oct 19, 202629
Oct 18, 202629
Oct 17, 202627
Oct 16, 202626
Oct 15, 202626
Oct 14, 202626
Oct 13, 202625
Oct 12, 202625
Oct 11, 202625
Oct 10, 202625
Oct 9, 202625
Oct 8, 202625
Oct 7, 202625
Oct 6, 202624
Oct 5, 202624
Oct 4, 202624
Oct 3, 202623
Oct 2, 202622
Oct 1, 202622
Sep 30, 202620
Sep 29, 202620
Sep 28, 202620
Sep 27, 202620
Sep 26, 202619
Sep 25, 202618
Sep 24, 202618
Sep 23, 202618
Sep 22, 202618
Sep 21, 202618
Sep 20, 202618
Sep 19, 202618
Sep 18, 202618
Sep 17, 202618
Sep 16, 202618
Sep 15, 202618
Sep 14, 202618
Sep 13, 202617
Sep 12, 202617
Sep 11, 202617
Sep 10, 202616
Sep 9, 202616
Sep 8, 202616
Sep 7, 202615

Shared by 15 plugins in focusreactive/payload-plugins.

npm weekly downloads

80−294 since Oct 1

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 202680
Dec 5, 202627
Dec 4, 202619
Dec 3, 202638
Dec 2, 202651
Dec 1, 202649
Nov 30, 202649
Nov 29, 202649
Nov 28, 202647
Nov 27, 202653
Nov 26, 202648
Nov 25, 202648
Nov 24, 202650
Nov 23, 202649
Nov 22, 202662
Nov 21, 202697
Nov 20, 2026171
Nov 19, 2026206
Nov 18, 2026247
Nov 17, 2026249
Nov 16, 2026261
Nov 15, 2026304
Nov 14, 2026375
Nov 13, 2026396
Nov 12, 2026371
Nov 11, 2026344
Nov 10, 2026343
Nov 9, 2026334
Nov 8, 2026311
Nov 7, 2026247
Nov 6, 2026336
Nov 5, 2026475
Nov 4, 2026577
Nov 3, 2026577
Nov 2, 2026586
Nov 1, 2026552
Oct 31, 2026526
Oct 30, 2026339
Oct 29, 2026173
Oct 28, 202643
Oct 27, 2026259
Oct 26, 2026278
Oct 25, 2026353
Oct 24, 2026494
Oct 23, 2026490
Oct 22, 2026498
Oct 21, 2026591
Oct 20, 2026423
Oct 19, 2026484
Oct 18, 2026502
Oct 17, 2026364
Oct 16, 2026379
Oct 15, 2026382
Oct 14, 2026369
Oct 13, 2026338
Oct 12, 2026255
Oct 11, 2026178
Oct 10, 2026177
Oct 9, 2026179
Oct 8, 2026230
Oct 7, 2026524
Oct 6, 2026502
Oct 5, 2026493
Oct 4, 2026475
Oct 3, 2026453
Oct 2, 2026436
Oct 1, 2026374

Each point is npm's rolling 7-day download count.

Health Score

74/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1177993877-payload-plugin-html-preview.svg)](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-html-preview)
HTML
<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-html-preview"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-html-preview.svg" alt="Payload Directory"></a>
Updated Dec 5, 2026Created Mar 10, 2026Published Dec 4, 2026

README

@focus-reactive/payload-plugin-html-preview

Live preview and click-to-edit for Payload CMS on any frontend that renders HTML: a static site generator, a template engine, a PHP app. No React, no client SDK on the site.

Payload's own live preview expects the frontend to subscribe to form data and re-render itself, which a Nunjucks, Liquid or Eleventy page cannot do. This plugin works the other way round: the CMS asks your site to render the document with its own templates and shows that page in the admin's preview, proxied through the CMS and sandboxed so it never runs as the CMS.

The plugin is built on @focus-reactive/payload-plugin-guard. Your project's access policy file decides who may see previews.

Requirements: Payload ^3.90.0, @focus-reactive/payload-plugin-guard, and a config wrapped in withAccessPolicy.

Features

  • Preview of saved and unsaved edits: the page is rendered by your site's real templates, so every change shows correctly: reordered blocks, hidden rows, conditionals, formatted dates.
  • Click-to-edit: click a section or card in the preview and the admin opens it: switches to the right tab (including tabs inside blocks), expands collapsed rows, scrolls to the field.
  • Other documents in a drawer: a click on something that lives in another collection (the header on a settings document, a FAQ entry, an author) opens that document in Payload's drawer, over the page and without losing unsaved edits.
  • Form to preview: focusing a field in the admin scrolls the preview to its block and highlights it.
  • Nothing on the site but attributes: the preview scripts are injected by the CMS; the site prints data-payload-* attributes in preview renders only.
  • Isolated from the admin: the preview runs in a sandbox with an opaque origin, so a script in the site's HTML, or in content an editor stored, cannot act with the session of the person looking at it.

AI Integration Prompt

Copy and paste this prompt into your AI assistant (Cursor, Claude, etc.) to add the plugin to an existing Payload project.

I want to add live preview with click-to-edit to my Payload CMS v3 project using
@focus-reactive/payload-plugin-html-preview. My site renders HTML with its own templates.
Follow these steps in order, and stop to ask me where a step says so.

## Rules you must follow

- Never write an access rule that admits every logged-in user: no `Boolean(req.user)`, no `() => true`,
  no `({ req }) => !!req.user`. A rule names a role, or it is `nobody`.
- Do not invent roles. Ask me which roles may see previews.
- Write every policy entry by hand in `src/access.policy.ts`, and grant each capability and each
  collection right explicitly to the roles I name. Nothing is open by default.
- When the boot or a request fails, fix the cause or ask me. Never use `anyone`, a looser gate,
  `overrideAccess` or a removed or disabled check to make an error go away.
- Do not add `overrideAccess: true` anywhere. In the `site` callback, read with `req` and
  `overrideAccess: false`.
- Do not remove the sandbox, and do not serve the preview from the admin's origin any other way.

## How it works

The admin's live preview frame loads `GET /api/html-preview/page/<collection>/<id>`. The plugin
checks that the caller holds the `preview` capability and may read the document, asks the site to
render it (the URL comes from the `site` callback), and returns the HTML with
`Content-Security-Policy: sandbox allow-scripts`. Unsaved edits go through
`POST /api/html-preview/render`, with the same checks. The page's files are fetched from the site
through `/api/html-preview/asset/<token>/...`, only from the origins in `siteOrigins`.
It declares one capability that the project grants in its access policy:
- `preview`: see the site's render of a document in the admin. The caller also needs read rights
  on the document.

## Step 1: install

pnpm add @focus-reactive/payload-plugin-html-preview @focus-reactive/payload-plugin-guard

Check that `payload` is 3.90 or later; if it is not, upgrade it first.

## Step 2: ask me about roles and the site

Look at the auth collection named in `admin.user` and the roles it has.
Ask me: "Which roles may see previews of pages?", "Which collections are pages of the site?" and
"At which origin does the site render a page on request, and how does it check the preview secret?"
Wait for my answers. Write the first answer as a gate in the policy file in step 3.

## Step 3: the access policy file

Open `src/access.policy.ts`, or create it if the project has none, following the guard README
(`defineAccessPolicy`, `gate`, `filter`, `nobody`, checked with `satisfies AccessPolicy<Config>`).
If you create it, every collection and global of the config needs an entry: move each existing
`access` of the project into the file, and ask me for every rule you cannot read from the code.
Add this entry for the plugin:

plugins: {
  "html-preview": { preview: <the gate from my first answer> },
},

## Step 4: register the plugin and wrap the config

// payload.config.ts
import { buildConfig } from 'payload'
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import { htmlPreviewPlugin } from '@focus-reactive/payload-plugin-html-preview'
import { accessPolicy } from './access.policy'

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    // ...the existing config
    plugins: [
      htmlPreviewPlugin({
        collections: ['pages'],
        siteOrigins: [process.env.SITE_URL ?? 'http://localhost:8080'],
        site: async ({ req, id }) => {
          const page = await req.payload.findByID({ collection: 'pages', id, req, overrideAccess: false })
          return {
            url: `${process.env.SITE_URL}/api/preview?slug=${encodeURIComponent(page.slug)}`,
            headers: { 'X-Preview-Secret': process.env.PREVIEW_SECRET ?? '' },
          }
        },
        access: accessPolicy.plugins['html-preview'],
      }),
    ],
  })
)

Run `payload generate:importmap`, then start the app.
A missing or wrong policy entry stops the boot with a list of what to fix.
Fix each item; never loosen a rule to make an error go away.

## Step 5: verify, and show me the output

With the app running, send each request and show me the status code.
Every one of them must be refused. If one succeeds, the policy is wrong: stop and tell me.

1. Anonymous preview, expect 401:
   curl -i http://localhost:3000/api/html-preview/page/pages/<page id>
2. The same request with the session cookie of a user whose role may not see previews, expect 403.
3. A file without a valid token, expect 404:
   curl -i http://localhost:3000/api/html-preview/asset/invalid/index.html

Then, as a user who may see previews, open a page in the admin, switch on the live preview, check
that the page shows, edit a field and check that the preview follows, and click a marked section.
Also check that the preview response carries `Content-Security-Policy: sandbox allow-scripts`:
   curl -sI -H 'Cookie: <session cookie>' http://localhost:3000/api/html-preview/page/pages/<page id>

Installation

In the CMS:

pnpm add @focus-reactive/payload-plugin-html-preview @focus-reactive/payload-plugin-guard

On the site, only what its render endpoint needs:

StackInstall
Astroan adapter for on-demand rendering: npx astro add netlify (or node, vercel)
Eleventynpm install nunjucks: the function renders the templates without Eleventy
Nunjucksnothing new; express if the endpoint is a Node server

No script or SDK goes on the site: the CMS injects the preview's scripts into the page it renders.

Usage

1. Grant the capability in your access policy

// src/access.policy.ts
import { defineAccessPolicy, gate, type AccessPolicy } from "@focus-reactive/payload-plugin-guard";
import type { Config } from "./payload-types";

const isEditor = gate(({ req }) =>
  req.user?.collection === "users" && (req.user.roles ?? []).some((role) => ["admin", "editor"].includes(role))
);

export const accessPolicy = defineAccessPolicy({
  // ...collections, globals and jobs
  plugins: {
    "html-preview": { preview: isEditor },
  },
}) satisfies AccessPolicy<Config>;

The plugin owns no collections or globals, so this is its only entry.

2. Register the plugin and wrap the config

// payload.config.ts
import { withAccessPolicy } from "@focus-reactive/payload-plugin-guard";
import { htmlPreviewPlugin } from "@focus-reactive/payload-plugin-html-preview";
import { accessPolicy } from "./access.policy";

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    plugins: [
      htmlPreviewPlugin({
        collections: ["pages"],
        // The only origins the CMS fetches pages and their files from.
        siteOrigins: ["https://my-site.com"],
        // Where the site renders a document. `data` is the unsaved form data, or null for the saved document.
        site: async ({ req, id }) => {
          // Pass `req`, and keep access control on.
          const page = await req.payload.findByID({ collection: "pages", id, req, overrideAccess: false });
          return {
            url: `https://my-site.com/api/preview?slug=${encodeURIComponent(page.slug)}`,
            headers: { "X-Preview-Secret": process.env.PREVIEW_SECRET ?? "" },
          };
        },
        // Keeps the preview's scroll clear of a fixed header: a px length, or the header's selector.
        scrollOffset: ".header",
        access: accessPolicy.plugins["html-preview"],
      }),
    ],
  })
);

3. Regenerate the import map

pnpm payload generate:importmap

The plugin adds a component to the edit view of each listed collection.

4. Give the site a render endpoint

The plugin calls the url you return:

RequestThe site answers with
GET urlthe saved document's page
POST url with { "doc": { ... } } as JSONthe page rendered from that document: the editor's unsaved form data, read like a stored document (relationships populated, afterRead hooks run)

The origin of url must be in siteOrigins, and the site must answer directly: a redirect is not followed, and the preview shows an error instead. Relative urls in the page (css/app.css, img/logo.svg) are fetched from the same origin through the CMS. If the page lives in a subdirectory, return basePath: "nyc/" or send an X-Preview-Base: nyc/ header.

Check the secret in the endpoint: this is how pages that are not public in Payload get rendered.

The endpoint renders with the templates the site is built from, so what it takes depends on the stack:

StackEndpoint
Astroa page rendered on demand
Eleventya function that renders the site's Nunjucks templates
Nunjucks in a Gulp or Webpack build, or on a Node servera function or a route with the build's environment and filters
Astro

With on-demand rendering (output: "server" or prerender = false):

---
// src/pages/preview/[slug].astro
export const prerender = false;

if (Astro.request.headers.get("x-preview-secret") !== import.meta.env.PREVIEW_SECRET) {
  return new Response("Forbidden", { status: 401 });
}
const page =
  Astro.request.method === "POST"
    ? (await Astro.request.json()).doc
    : await getPage(Astro.params.slug); // your usual Payload query
---
<PageLayout page={page} preview />
Eleventy

The templates do not need Eleventy to render: a Nunjucks environment on _includes with the site's filters renders them the same. Keep the filters in a module that both .eleventy.js and the function import. On Netlify:

// netlify/functions/preview.mjs
import nunjucks from "nunjucks";
import filters from "../../src/filters.js"; // the object .eleventy.js registers

const env = nunjucks.configure("src/_includes", { autoescape: true });
for (const [name, filter] of Object.entries(filters)) env.addFilter(name, filter);

export default async (req) => {
  if (req.headers.get("x-preview-secret") !== process.env.PREVIEW_SECRET) {
    return new Response("Forbidden", { status: 401 });
  }
  const page =
    req.method === "POST"
      ? (await req.json()).doc
      : await getPage(new URL(req.url).searchParams.get("slug")); // your usual Payload query
  // The same data the template gets in the build.
  return new Response(env.render("layouts/page.njk", { page, preview: true }), {
    headers: { "Content-Type": "text/html; charset=utf-8" },
  });
};
# netlify.toml: the function reads the templates from disk, so they ship with it
[functions]
  included_files = ["src/_includes/**"]

Shortcodes and globals the templates use have to be registered on this environment too.

Nunjucks

A site built with Gulp or Webpack renders its pages with a Nunjucks environment the build sets up. The endpoint imports the same modules (that environment with its filters, and whatever turns Payload's response into the data each template gets) and renders one page. On a Node server it is a route:

app.all("/api/preview", express.json({ limit: "5mb" }), async (req, res) => {
  if (req.get("x-preview-secret") !== process.env.PREVIEW_SECRET) return res.sendStatus(401);
  const page = req.method === "POST" ? req.body.doc : await getPage(req.query.slug);
  res.send(env.render("page.njk", { page, preview: true }));
});

On a static host it is a function, like the Eleventy one above. Two things break it there:

  • Files read from disk (templates, settings, data files) have to ship with the function (included_files on Netlify, includeFiles on Vercel).
  • require with a computed path (require(`./settings/${name}`)) is invisible to the function bundler. Write require(path.join(dir, name)) and ship the directory as above.

A site that cannot render on request (a static host serving its build) can still have the preview of saved pages and click-to-edit: point site at the deployed page and set unsaved: false. Its build then has to print the attributes, which the public site would carry too.

5. Mark what can be clicked

Print the attributes only in preview renders: they name CMS fields and documents. The endpoints above render with preview: true and the build never sets it, so the public site carries none of them.

AttributeOpens
data-payload-id="<row id>"a row of the document: any array or blocks row, at any depth; every row has an id in Payload's API response
data-payload-doc="<collection>:<id>"another document, in a drawer
data-payload-field="<field>"with either of the above: a group or tab inside that row or document

Nunjucks, and Eleventy's Nunjucks templates:

<section class="hero" {% if preview %}data-payload-id="{{ hero.id }}"{% endif %}>
  {% for card in hero.cards %}
  <div class="card" {% if preview %}data-payload-id="{{ card.id }}"{% endif %}>…</div>
  {% endfor %}
</section>

<header {% if preview %}data-payload-doc="settings:{{ settings.id }}" data-payload-field="header"{% endif %}>…</header>

Astro, with preview passed down as a prop from the preview page (<PageLayout page={page} preview />):

---
const { hero, preview } = Astro.props;
---
<section data-payload-id={preview ? hero.id : undefined}>
  {hero.cards.map((card) => <div class="card" data-payload-id={preview ? card.id : undefined}>…</div>)}
</section>

Astro leaves out an attribute whose value is undefined, so the normal build prints nothing.

The innermost marked element wins, so a card inside a marked section opens the card. Form controls and in-page anchors inside marked elements keep working; other links do not navigate in the preview.

Access and capabilities

CapabilityLets a userAlso needs, on the document
previewsee the site's render of a document in the live preview, saved or with unsaved editsread

The capability says who may see previews at all. The document rights come from the policy entries you already wrote for the collection: a document the caller cannot read answers like a missing one (404), and the site is never asked to render it. A user without preview gets no live preview URL, so Payload shows no live preview button for them. A click on another document in the preview opens it in a drawer only for a user who may update that collection; for anyone else the click does nothing.

EndpointKindWhat it does
GET /api/html-preview/page/<collection>/<id>previewthe saved document's page; the admin's preview frame loads it
POST /api/html-preview/renderpreviewthe page rendered from { "collection", "id", "data" }, the editor's unsaved form data; not registered with unsaved: false
GET /api/html-preview/asset/<token>/<path>public, with a tokenone of the page's files, fetched from the site
GET /api/html-preview/frame/<file>publicthe plugin's own preview script and styles
GET /api/html-preview/capabilitieslogged-in admin user{ "preview": boolean } for that user
  • Anonymous callers get 401; users of another auth collection and users without the capability get 403.
  • The collection must be one of collections. The unsaved render takes application/json only, up to 2 MiB.
  • Errors carry a generic message; details go to the server log. Refusals (401 and 403) are logged at warn with the capability and the caller's kind.

How the preview is isolated

The page is your site's HTML, which can carry script: the site's own, or HTML an editor stored in a document and the site renders as is. The plugin keeps that script away from the admin's session:

  • The page and the unsaved render are served with Content-Security-Policy: sandbox allow-scripts, and the preview frame carries sandbox="allow-scripts". The page's scripts run, but in an opaque origin: they cannot read the admin's cookies or storage, call the CMS's API with the session, or reach the admin page around the frame. A page URL opened on its own in a tab is sandboxed the same way.
  • The page's files are served with Content-Security-Policy: sandbox, so an HTML or SVG file of the site opened through the CMS runs no script at all.
  • The frame's requests carry no session, so its files come through /api/html-preview/asset/<token>/.... The token is signed by the CMS when it renders a page for an entitled user, names the one site origin the files come from, and expires after an hour. A request without a valid token is answered with 404 and reaches nothing.
  • The CMS fetches only from siteOrigins, does not follow redirects, and does not pass the site's cookies on.
  • The preview talks to the admin only through postMessage: the ids of the clicked rows, the focused row and its scroll position. The admin accepts messages only from its own preview frame.

Options

OptionTypeDefaultWhat it does
collectionsCollectionSlug[]requiredCollections whose documents are pages of the site; each gets the preview and click-to-edit in its edit view
site(args) => SiteRequest | nullrequiredWhere the site renders a document. Called for every render of the preview; null shows nothing for that document
siteOriginsstring[]requiredThe origins site may point at, like https://my-site.com or http://localhost:8080. The CMS fetches pages and their files only from these
access{ preview: Gate }requiredaccessPolicy.plugins["html-preview"] from your policy file; there is no default
scrollOffsetstringnoneRoom for a fixed header when the preview scrolls to a block: '80px', or the header's selector ('.header'), measured at scroll time
depthnumber2How deep relationships in unsaved form data are populated before it is sent to the site. Match the depth the site reads a saved document with
unsavedbooleantrueSends the editor's unsaved edits to the site as they type. false for a site that only serves its build: the preview shows the saved page, click-to-edit still works

What site gets:

Argument
reqThe admin's request. Pass it to Payload queries with overrideAccess: false, so the preview shows only what the editor may read
collection, idThe document being edited; the plugin has already checked that the caller may read it
dataThe unsaved form data, read like a stored document as the caller (relationships populated, afterRead hooks run), or null for the saved document. With data the plugin POSTs to url, without it GETs

What it returns:

Field
urlThe address that answers with the page's HTML; its origin must be in siteOrigins
headersSent with the request; the preview secret goes here
bodyThe body of an unsaved render. Defaults to { "doc": <form data> } as JSON
basePathThe page's directory on the site (nyc/), which its relative urls resolve against. Defaults to the response's X-Preview-Base header, then the site root

Migrating from 1.x

2.0 moves the plugin onto @focus-reactive/payload-plugin-guard; Upgrading to the guard explains the model all the plugins share, with a complete example. Every access rule is now written by hand in your project's src/access.policy.ts, and nothing is open by default: an entry you leave out stops the boot, and a capability you do not grant is refused for everyone.

What changes

  • Payload and every @payloadcms/* package 3.90 or later, with the React and Next versions Payload 3.90 requires, Node 22.22 or later, and @focus-reactive/payload-plugin-guard installed next to the plugin.
  • access and siteOrigins are required options with no defaults. Before, every logged-in user of any auth collection could see a preview, and the plugin fetched whatever URL site returned.
  • The endpoints moved, and the admin uses the new ones without changes on your side:
    • GET /api/html-preview/<collection>/<id> is now GET /api/html-preview/page/<collection>/<id>.
    • POST /api/html-preview/<collection>/<id> with form data is now POST /api/html-preview/render with JSON.
    • GET /api/html-preview/<collection>/<id>/_/<path> is now GET /api/html-preview/asset/<token>/<path>.
    • GET /api/html-preview-frame/<file> is now GET /api/html-preview/frame/<file>. Update a rate limiter's exemption to the new asset path.
  • The preview needs read rights on the document; a document the caller cannot read is no longer passed to site.
  • The site's redirects are no longer followed, and only siteOrigins are fetched.
  • The preview runs sandboxed in an opaque origin, which changes what the site's own scripts can do there; see Good to know.

Steps

  1. Upgrade payload and every @payloadcms/* package to 3.90 or later, run the server on Node 22.22 or later, and install the guard: pnpm add @focus-reactive/payload-plugin-guard @focus-reactive/payload-plugin-html-preview.

  2. Add the plugin's entries to src/access.policy.ts, with gates for your own roles; if the project has no policy file yet, write it first as the guide describes.

    // src/access.policy.ts, inside defineAccessPolicy({ ... })
    plugins: {
      "html-preview": { preview: isEditor },
    },
    
    • preview: see the site's render of a document in the live preview, saved or with unsaved edits; the user also needs read access to the document.
  3. Pass access: accessPolicy.plugins["html-preview"] and siteOrigins (the origins site may point at) to htmlPreviewPlugin, read the document in site with req and overrideAccess: false, and export the config wrapped: export default withAccessPolicy(accessPolicy, buildConfig({ ... })).

  4. Database: no migration; the plugin owns no collection or global.

  5. Re-test: an anonymous GET /api/html-preview/page/<collection>/<id> answers 401 and one from a user without preview 403; then open the live preview as an editor, type in a field, click a block in the frame, and check that pages with many files still load through your rate limiter.

What it relies on

Click-to-edit drives the admin's DOM where Payload offers no API: rows are found by the ids Payload renders (sections-1-items-row-3), tabs are switched by their buttons (a tabs field keeps its active tab in local state), a drawer is found by its close button, and the preview frame by its id (live-preview-iframe). Rows are expanded through form state (SET_ROW_COLLAPSED), and a drawer opens on the right tab through the document's preferences. After upgrading Payload, click a nested card in the preview before shipping.

Not covered yet

  • Globals: a global cannot be a previewed page, and a click cannot open one: Payload's document drawer takes collections only.
  • Drafts and localization: unsaved form data is read without a locale and as a published document, and the admin's locale is not passed to site. A site with drafts or several locales renders what site returns for the saved document; check that it is the version you expect.
  • Links to other pages: the preview scrolls to anchors on the page, but does not follow links elsewhere.
  • The popup preview: Payload's "open in new window" shows the saved page; unsaved edits show only in the frame.

Good to know

  • Sandbox: the site's scripts run, but with an opaque origin. localStorage, sessionStorage and cookies are not available to them, so a script that needs them should be left out of preview renders or handle the error. An SVG sprite referenced from another file (<use href="icons.svg#logo">) does not load; inline the sprite in preview renders. Fonts load: the CMS sends them with Access-Control-Allow-Origin: *.
  • Analytics: the preview is a real render of your page, trackers included. Leave them out of preview renders, or every preview reload is a visit.
  • Rate limits: a page loads its files through the CMS (/api/html-preview/asset/<token>/…), often a hundred at a time; exempt that path from a rate limiter.
  • Links: the page's relative urls resolve against the CMS proxy; in-page anchors scroll, links to other pages are not followed.

License

MIT

Similar plugins