Skip to content
Mutual Team

Using Craft CMS Live Preview with Next.js

Note: This article was last updated on April 21, 2021 and may contain outdated information.

Craft CMS includes a built-in Live Preview feature that enables real-time editing previews. While this works seamlessly with Twig templates, integrating it with a decoupled Next.js frontend requires additional configuration steps.

Step One: The Preview API

Create pages/api/preview.js to handle requests from Craft CMS:

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 validates the preview token and URI, then activates Next.js Preview Mode with a 60-second timeout before redirecting to the requested page.

Step Two: Update Page Queries

Modify getStaticProps to access preview context:

export const getStaticProps = async ({ params, preview, previewData }) => {
  // Access preview boolean and previewData object
}

Append the preview token to your GraphQL API URL. For Apollo Client:

const apolloClient = (previewToken) => {
  const uri = `${process.env.NEXT_PUBLIC_CRAFT_GRAPHQL_URL}${
    previewToken ? `?token=${previewToken}` : ``
  }`
  // Rest of Apollo configuration
}

Then pass the token when querying:

const previewToken = preview ? previewData.token : undefined
const { data } = await apolloClient(previewToken).query({...})

Step Three: Configure Craft CMS

In Craft’s section settings, locate “Preview Targets” and add a new entry with:

  • Label: “Next.js Frontend”
  • URL Format: https://www.website.com/api?uri=blog/{slug}

Important Notes

This approach relies on Vercel hosting and may not function locally due to HTTPS/iframe cookie restrictions. The GraphQL integration method varies by setup, so customization is necessary for each project.