payload-live-preview
Skill0 starsChanged 13 days agoMITView on GitHub
Server-side live preview for Payload CMS 3 + Next.js App Router, matching the official website template - draft mode, autosave, preview route with secret and auth check, RefreshRouteOnSave listener, localized preview URLs, and cache bypass. Use when adding live preview or a preview button to any collection, when preview shows a blank iframe, published instead of draft content, the wrong language, or does not update while typing.
- Reads credentials
In this repository20 other files it gives its agents.
- AGENTS.mdAGENTS.md
- agent-guardrailsSkill
- creative-frontendSkill
- figma-handoffSkill
- payload-admin-brandingSkill
- payload-auth-rbacSkill
- payload-bookings-paymentsSkill
- payload-bootstrapSkill
- payload-deploy-vercelSkill
- payload-forms-crmSkill
- payload-integrationsSkill
- payload-legal-trustSkill
- payload-localizationSkill
- payload-mcpSkill
- payload-mediaSkill
- payload-performanceSkill
- payload-project-kickoffSkill
- payload-seo-geoSkill
- payload-testingSkill
- project-architectureSkill
The file
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 3 are distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 11
Use the server-side pattern from the official website template.
- Distinctive: line 19
When the editor switches locale in the admin, Payload recomputes the preview URL with the new locale, so the iframe follows the editing …
- Distinctive: line 82
Keep the prefix map in sync with the frontend routes.
- Very specific: line 86
Keep the template's src/app/(frontend)/next/preview/route.ts unchanged.
- Very specific: line 90
Call payload.auth({ req, headers: req.headers }) and return 403 when there is no user.
- Very specific: line 91
Call (await draftMode()).enable() and redirect(path).
- Very specific: line 93
If the project does not have it (Payload added to an existing app), copy preview/route.ts and exit-preview/route.ts from …
- Distinctive: line 97
Every previewable page follows this shape.
- Very specific: line 138
Read draftMode() inside the query function and pass draft to payload.find.
- Very specific: line 139
Never wrap draft queries in unstable_cache or 'use cache'.
- Very specific: line 169
Use the revalidateOnPublish hook factory and a per-collection targets function from the payload-performance skill.
- Very specific: line 173
If next.config.ts sets X-Frame-Options: DENY or a CSP frame-ancestors 'none', change it to frame-ancestors 'self'.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Payload live preview
Use the server-side pattern from the official website template. Client-only preview (useLivePreview merging data in the browser) breaks with Server Components, relationships, rich text, and locales, so do not use it.
How it works
- The admin opens an iframe at
/next/preview?path=/<locale>/posts/<slug>&previewSecret=.... - The preview route checks the secret and the logged-in Payload user, enables Next.js draft mode, and redirects to the path.
- The page sees draft mode, queries Payload with
draft: true, and renders the latest draft. LivePreviewListener(wrappingRefreshRouteOnSave) callsrouter.refresh()every time autosave writes a draft, so the iframe re-renders on the server.- When the editor switches locale in the admin, Payload recomputes the preview URL with the new locale, so the iframe follows the editing language.
Step 1: Collection config
For each collection with a public page (pages, posts, legal-pages, services):
admin: {
livePreview: {
url: ({ data, locale }) =>
generatePreviewPath({ collection: 'posts', slug: data?.slug, locale: locale?.code }),
},
preview: (data, { locale }) =>
generatePreviewPath({ collection: 'posts', slug: data?.slug as string, locale }),
},
versions: {
drafts: {
autosave: { interval: 100 }, // required for live updates while typing
schedulePublish: true,
},
maxPerDoc: 50,
},Omit locale when the site is not localized. Read access must allow drafts for logged-in users and published docs for everyone (authenticatedOrPublished in the template).
Step 2: Preview path helper
src/utilities/generatePreviewPath.ts:
import type { CollectionSlug, PayloadRequest } from 'payload'
const collectionPrefixMap: Partial<Record<CollectionSlug, string>> = {
pages: '',
posts: '/posts',
'legal-pages': '/legal',
services: '/services',
}
type Props = {
collection: keyof typeof collectionPrefixMap
slug: string | null | undefined
locale?: string
req?: PayloadRequest // accepted so the template's existing call sites keep compiling
}
export const generatePreviewPath = ({ collection, slug, locale }: Props): string | null => {
if (slug === undefined || slug === null) return null
const localePrefix = locale ? `/${locale}` : ''
const isHome = collection === 'pages' && slug === 'home'
const docPath = isHome ? '' : `${collectionPrefixMap[collection]}/${encodeURIComponent(slug)}`
const params = new URLSearchParams({
path: `${localePrefix}${docPath}` || '/',
previewSecret: process.env.PREVIEW_SECRET || '',
})
return `/next/preview?${params.toString()}`
}Keep the prefix map in sync with the frontend routes. A wrong prefix is the most common cause of a 404 inside the preview iframe.
Step 3: Preview and exit routes
Keep the template's src/app/(frontend)/next/preview/route.ts unchanged. It must:
- Return 403 when
previewSecret !== process.env.PREVIEW_SECRET. - Reject paths that do not start with
/. - Call
payload.auth({ req, headers: req.headers })and return 403 when there is no user. - Call
(await draftMode()).enable()andredirect(path).
If the project does not have it (Payload added to an existing app), copy preview/route.ts and exit-preview/route.ts from templates/website/src/app/(frontend)/next/ on the 3.x branch.
Step 4: The page
Every previewable page follows this shape. Full localized example: references/localized-page.md.
import { draftMode } from 'next/headers'
import { notFound } from 'next/navigation'
import { cache } from 'react'
import { LivePreviewListener } from '@/components/LivePreviewListener'
import { getPayloadClient } from '@/lib/payload'
export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const { isEnabled: draft } = await draftMode()
const post = await queryPostBySlug(decodeURIComponent(slug))
if (!post) return notFound()
return (
<article>
{draft && <LivePreviewListener />}
{/* render post */}
</article>
)
}
const queryPostBySlug = cache(async (slug: string) => {
const { isEnabled: draft } = await draftMode()
const payload = await getPayloadClient()
const result = await payload.find({
collection: 'posts',
draft,
overrideAccess: draft,
limit: 1,
pagination: false,
where: { slug: { equals: slug } },
})
return result.docs[0] ?? null
})Rules:
- Read
draftMode()inside the query function and passdrafttopayload.find. - Never wrap draft queries in
unstable_cacheor'use cache'. Draft mode already makes the route dynamic; a cache layer would serve stale or published content. - Pass
localetopayload.findon localized sites. - Fetch relationships at a
depththat the page needs, so the preview matches production.
Step 5: The listener
src/components/LivePreviewListener.tsx (from the template):
'use client'
import { RefreshRouteOnSave as PayloadLivePreview } from '@payloadcms/live-preview-react'
import { useRouter } from 'next/navigation'
import { getClientSideURL } from '@/utilities/getURL'
export function LivePreviewListener() {
const router = useRouter()
return <PayloadLivePreview refresh={router.refresh} serverURL={getClientSideURL()} />
}getClientSideURL must return window.location.origin in the browser. A hardcoded production URL breaks preview on preview deployments and localhost.
Step 6: Revalidate only on publish
Autosave writes a draft every 100 ms of typing, and live preview reads drafts dynamically, so drafts never need revalidation. Every revalidation on Vercel is a metered ISR write, so the hooks must be exact:
- Revalidate only when a document is published, unpublished, renamed, or deleted. Draft-only saves revalidate nothing.
- Revalidate exactly the routes that render the document: its detail path for each locale, the listings that show it, and the home page only if it is featured there. Never revalidate the layout and never expire a tag shared by all content.
- Use the
revalidateOnPublishhook factory and a per-collection targets function from thepayload-performanceskill. A worked example for localized posts is in references/localized-page.md.
Step 7: Headers and hosting
- If
next.config.tssetsX-Frame-Options: DENYor a CSPframe-ancestors 'none', change it toframe-ancestors 'self'. The admin and frontend share one origin, so'self'is enough. - Vercel Deployment Protection blocks the iframe on protected preview deployments. Test live preview on production or on an unprotected deployment.
PREVIEW_SECRETmust be set in every environment.
Diagnosis
| Symptom | Cause | Fix |
| Blank iframe, console shows "refused to frame" | X-Frame-Options or CSP | Step 7.1 |
| "You are not allowed to preview this page" | Missing PREVIEW_SECRET, or not logged in on this origin | Set the env var; log in to /admin on the same domain |
| 404 inside the iframe | Prefix map or locale prefix does not match routes | Fix collectionPrefixMap and the locale segment |
| Shows published content | Query lacks draft, or a cache wraps the query | Step 4 rules 1 and 2 |
| Does not update while typing | No autosave, no listener, or listener serverURL mismatch | Step 1 autosave; render LivePreviewListener when draft; Step 5 |
| Wrong language | url ignores locale, or the page does not pass locale to find | Steps 1, 2, 4 |
| Works locally, not on Vercel | Deployment Protection, missing env var | Step 7 |
Done when
- Every previewable collection has
livePreview.url,preview, and autosave drafts - Typing in a field updates the iframe within about a second, without a manual save
- Switching locale in the admin switches the iframe to the same locale
- The published page does not show unpublished draft changes
- Typing in the admin produces no
revalidatelog lines; publishing produces one line listing only that document's routes - The live preview test in the
payload-testingskill passes
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

