Using Craft CMS Live Preview with Next.js
Craft's Live Preview works out of the box with Twig. Wiring it up to a decoupled Next.js front end takes a few extra steps.
Step one: the preview API route
Create pages/api/preview.js to receive requests from Craft:
export default async (req, res) => {
if (req.query.token === null) {
return res.status(401).json({ message: 'No preview token' })
}
if (req.query.uri === null) {
return res.status(401).json({ message: 'No URI provided' })
}
res.setPreviewData(
{
token: req.query.token ?? null,
},
{
maxAge: 60,
}
)
res.redirect(`/${req.query.uri}`)
}
This checks the preview token and URI, enables Next.js Preview Mode for 60 seconds, then redirects to the requested page.
Step two: pass the token through your queries
Read preview context in getStaticProps:
export const getStaticProps = async ({ params, preview, previewData }) => {
// Access preview boolean and previewData object
}
Append the token to your Craft GraphQL URL. With Apollo Client:
const apolloClient = (previewToken) => {
const uri = `${process.env.NEXT_PUBLIC_CRAFT_GRAPHQL_URL}${
previewToken ? `?token=${previewToken}` : ``
}`
// Rest of Apollo configuration
}
Then pass it through at query time:
const previewToken = preview ? previewData.token : undefined
const { data } = await apolloClient(previewToken).query({...})
Step three: add a preview target in Craft
In the section settings, add a new Preview Target:
- Label: Next.js Frontend
- URL Format:
https://www.website.com/api?uri=blog/{slug}
Notes
We've only tested this on Vercel. Local previews tend to fail because the iframe cookies require HTTPS. The GraphQL piece will look different depending on your client — adapt as needed.
More from the blog
Protecting Craft CMS with Cloudflare
Why you should protect your Craft CMS site with Cloudflare, and how to set it up.
Craft CMS and PHP2Shell - how we dealt with it
How Mutual (a Craft CMS agency) handled the PHP2Shell vulnerability.
What's happened to my ChatGPT traffic?
You might have seen a drop in traffic from ChatGPT from this week. Here's what's happening...