Using Craft CMS Live Preview with Next.js

Learn how to integrate Craft CMS's Live Preview feature with a decoupled Next.js frontend for real-time editing previews.

M
Written by
Mutual
Published 21 Apr 2021
2 min read

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.

Further reading

Craft CMS
Craft CMS 5.10: Safer Deletes, Time Zones, and an Important Security Fix
4 min
Craft CMS
Why use Craft CMS instead of WordPress?
9 min
Analytics
Privacy-First Analytics, Built Into Your CMS
3 min

Let's get your site
where it should be

Emma Andrew

Start a conversation with Emma and Andrew

Emma, Operations Director · Andrew, Technical Director

hello@mutual.agency