Configure Preview Routes
Preview routes in Next.js
To implement preview mode:
- In your Next.js project, configure the
DRUPAL_PREVIEW_SECRETin your.env.localfile. This is the same secret used when creating your Next.js site on Drupal.
.env.local
# Required for Preview ModeDRUPAL_PREVIEW_SECRET=secret- Set the
previewSecreton theDrupalClient.
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, }, })- 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()}