Configure Preview Routes

Preview routes in Next.js


To implement preview mode:

  1. In your Next.js project, configure the DRUPAL_PREVIEW_SECRET in your .env.local file. This is the same secret used when creating your Next.js site on Drupal.

.env.local

# Required for Preview Mode
DRUPAL_PREVIEW_SECRET=secret
  1. Set the previewSecret on the DrupalClient.

lib/drupal.ts

import { DrupalClient } from "next-drupal"
export const drupal = new DrupalClient(
process.env.NEXT_PUBLIC_DRUPAL_BASE_URL,
{
frontPage: "/home",
previewSecret: process.env.DRUPAL_PREVIEW_SECRET,
auth: {
clientId: process.env.DRUPAL_CLIENT_ID,
clientSecret: process.env.DRUPAL_CLIENT_SECRET,
},
}
)
  1. Implement preview mode using two API routes.

If you're using the Basic Starter, preview routes are already created for you.

pages/api/preview.ts

import { NextApiRequest, NextApiResponse } from "next"
import { drupal } from "lib/drupal"
export default async function handler(
request: NextApiRequest,
response: NextApiResponse
) {
return await drupal.preview(request, response)
}

pages/api/exit-preview.ts

import { NextApiResponse } from "next"
export default function exit(_, response: NextApiResponse) {
response.clearPreviewData()
response.writeHead(307, { Location: "/" })
response.end()
}