Next.jsMedium

What is Preview Mode in the Pages Router?

Preview Mode was the Pages Router feature for showing unpublished CMS content on static pages: an API route called res.setPreviewData({...}), which set cookies that made getStaticProps run at request time with context.preview and context.previewData. It is deprecated in favor of Draft Mode (res.setDraftMode({ enable: true })), which works the same way without preview data.

How Preview Mode worked

  1. The CMS opened /api/preview?secret=...&slug=....
  2. The API route validated the secret and called res.setPreviewData({ token }).
  3. Two cookies (__prerender_bypass and __next_preview_data) were set.
  4. getStaticProps ran on every request with context.preview === true and the stored previewData, fetching drafts.
  5. res.clearPreviewData() exited preview.

Why it was replaced

previewData was limited by cookie size (about 2KB) and encouraged storing data in cookies. Draft Mode keeps only the bypass flag; your code fetches drafts with server-side credentials.

Draft Mode in the Pages Router

  • Enable: res.setDraftMode({ enable: true }) in an API route, then redirect.
  • In getStaticProps: context.draftMode is true.
  • Disable: res.setDraftMode({ enable: false }).

App Router

(await draftMode()).enable() from next/headers in a Route Handler, and (await draftMode()).isEnabled in pages. With Cache Components, cached functions re-run for drafts automatically.

Security

Always validate a secret and the redirect slug; otherwise anyone can force your pages into dynamic rendering or create open redirects.

Code example

tsx
1// pages/api/draft.ts (Pages Router, Draft Mode)
2import type { NextApiRequest, NextApiResponse } from "next";
3import { getPostBySlug } from "@/lib/cms";
4
5export default async function handler(req: NextApiRequest, res: NextApiResponse) {
6 if (req.query.secret !== process.env.CMS_PREVIEW_SECRET) {
7 return res.status(401).json({ message: "Invalid token" });
8 }
9 const post = await getPostBySlug(String(req.query.slug), { preview: true });
10 if (!post) return res.status(404).json({ message: "Invalid slug" });
11
12 res.setDraftMode({ enable: true }); // old API: res.setPreviewData({ token: "..." })
13 res.redirect(307, `/blog/${post.slug}`);
14}
15
16// pages/blog/[slug].tsx
17// export const getStaticProps: GetStaticProps = async ({ params, draftMode }) => {
18// const post = await getPostBySlug(String(params!.slug), { preview: draftMode });
19// return { props: { post } };
20// };

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app