Implementing Live Preview in your app

While using Live Preview, the Admin panel emits a new window.postMessage event every time a change is made to the document. Your front-end application can listen for these events and re-render accordingly.

Wiring your front-end into Live Preview is easy. If your front-end application is built with React or Next.js, use the useLivePreview React hook that Payload provides. In the future, all other major frameworks like Vue, Svelte, etc will be officially supported. If you are using any of these frameworks today, you can still integrate with Live Preview yourself using the underlying tooling that Payload provides. See building your own hook for more information.

By default, all hooks accept the following args:

PathDescription
serverURL *The URL of your Payload server.
initialDataThe initial data of the document. The live data will be merged in as changes are made.
depthThe depth of the relationships to fetch. Defaults to 0.
apiRouteThe path of your API route as defined in routes.api. Defaults to /api.

* An asterisk denotes that a property is required.

And return the following values:

PathDescription
dataThe live data of the document, merged with the initial data.
isLoadingA boolean that indicates whether or not the document is loading.

React

If your front-end application is built with React or Next.js, you can use the useLivePreview hook that Payload provides.

First, install the @payloadcms/live-preview-react package:

npm install @payloadcms/live-preview-react

Then, use the useLivePreview hook in your React component:

'use client';
import { useLivePreview } from '@payloadcms/live-preview-react';
import { Page as PageType } from '@/payload-types'
// Fetch the page in a server component, pass it to the client component, then thread it through the hook
// The hook will take over from there and keep the preview in sync with the changes you make
// The `data` property will contain the live data of the document
export const PageClient: React.FC<{
page: {
title: string
}
}> = ({ page: initialPage }) => {
const { data } = useLivePreview<PageType>({
initialData: initialPage,
serverURL: PAYLOAD_SERVER_URL,
depth: 2,
})
return (
<h1>{data.title}</h1>
)
}

Building your own hook

No matter what front-end framework you are using, you can build your own hook using the same underlying tooling that Payload provides.

First, install the base @payloadcms/live-preview package:

npm install @payloadcms/live-preview

This package provides the following functions:

PathDescription
subscribeSubscribes to the Admin panel's window.postMessage events and calls the provided callback function.
unsubscribeUnsubscribes from the Admin panel's window.postMessage events.
readySends a window.postMessage event to the Admin panel to indicate that the front-end is ready to receive messages.

The subscribe function takes the following args:

PathDescription
callback *A callback function that is called with data every time a change is made to the document.
serverURL *The URL of your Payload server.
initialDataThe initial data of the document. The live data will be merged in as changes are made.
depthThe depth of the relationships to fetch. Defaults to 0.

With these functions, you can build your own hook using your front-end framework of choice:

import { subscribe, unsubscribe } from '@payloadcms/live-preview';
// To build your own hook, subscribe to Live Preview events using the`subscribe` function
// It handles everything from:
// 1. Listening to `window.postMessage` events
// 2. Merging initial data with active form state
// 3. Populating relationships and uploads
// 4. Calling the `onChange` callback with the result
// Your hook should also:
// 1. Tell the Admin panel when it is ready to receive messages
// 2. Handle the results of the `onChange` callback to update the UI
// 3. Unsubscribe from the `window.postMessage` events when it unmounts

Here is an example of what the same useLivePreview React hook from above looks like under the hood:

import { subscribe, unsubscribe, ready } from '@payloadcms/live-preview'
import { useCallback, useEffect, useState, useRef } from 'react'
export const useLivePreview = <T extends any>(props: {
depth?: number
initialData: T
serverURL: string
}): {
data: T
isLoading: boolean
} => {
const { depth = 0, initialData, serverURL } = props
const [data, setData] = useState<T>(initialData)
const [isLoading, setIsLoading] = useState<boolean>(true)
const hasSentReadyMessage = useRef<boolean>(false)
const onChange = useCallback((mergedData) => {
// When a change is made, the `onChange` callback will be called with the merged data
// Set this merged data into state so that React will re-render the UI
setData(mergedData)
setIsLoading(false)
}, [])
useEffect(() => {
// Listen for `window.postMessage` events from the Admin panel
// When a change is made, the `onChange` callback will be called with the merged data
const subscription = subscribe({
callback: onChange,
depth,
initialData,
serverURL,
})
// Once subscribed, send a `ready` message back up to the Admin panel
// This will indicate that the front-end is ready to receive messages
if (!hasSentReadyMessage.current) {
hasSentReadyMessage.current = true
ready({
serverURL
})
}
// When the component unmounts, unsubscribe from the `window.postMessage` events
return () => {
unsubscribe(subscription)
}
}, [serverURL, onChange, depth, initialData])
return {
data,
isLoading,
}
}

Example

For a working demonstration of this, check out the official Live Preview Example. There you will find examples of various front-end frameworks and how to integrate each one of them, including:

Troubleshooting

Relationships and/or uploads are not populating

If you are using relationships or uploads in your front-end application, and your front-end application runs on a different domain than your Payload server, you may need to configure CORS to allow requests to be made between the two domains. This includes sites that are running on a different port or subdomain. Similarly, if you are protecting resources behind user authentication, you may also need to configure CSRF to allow cookies to be sent between the two domains. For example:

// payload.config.ts
{
// ...
// If your site is running on a different domain than your Payload server,
// This will allows requests to be made between the two domains
cors: {
[
'http://localhost:3001' // Your front-end application
],
},
// If you are protecting resources behind user authentication,
// This will allow cookies to be sent between the two domains
csrf: {
[
'http://localhost:3001' // Your front-end application
],
},
}

Relationships and/or uploads disappear after editing a document

It is possible that either you are setting an improper depth in your initial request and/or your useLivePreview hook, or they're mismatched. Ensure that the depth parameter is set to the correct value, and that it matches exactly in both places. For example:

// Your initial request
const { docs } = await payload.find({
collection: 'pages',
depth: 1, // Ensure this is set to the proper depth for your application
where: {
slug: {
equals: 'home',
}
}
})
// Your hook
const { data } = useLivePreview<PageType>({
initialData: initialPage,
serverURL: PAYLOAD_SERVER_URL,
depth: 1, // Ensure this matches the depth of your initial request
})
Next

Access Control