Next.jsMedium

What is the draftMode API in Next.js?

Draft Mode lets editors preview unpublished CMS content on statically generated pages. A Route Handler calls (await draftMode()).enable(), which sets a bypass cookie; while it is present, pages render at request time and fetch draft content. (await draftMode()).isEnabled tells pages which content to load.

Flow

  1. The CMS preview button opens /api/draft?secret=...&slug=/blog/post.
  2. The Route Handler validates the secret and that the slug exists.
  3. It calls (await draftMode()).enable() and redirects to the slug.
  4. Pages check isEnabled and fetch drafts (for example with a preview API token).
  5. A "Exit preview" link hits a handler that calls disable().

Caching behavior

  • With Draft Mode on, routes render dynamically per request.
  • With Cache Components, all "use cache" functions re-execute on every request and results are not saved, so drafts are always fresh with no code changes.
  • You can read isEnabled inside a "use cache" scope, but other runtime APIs remain off-limits there.
  • enable() and disable() work only in Route Handlers and Server Functions.

Security

  • Validate a secret token so random visitors cannot enable it.
  • Validate the redirect target to avoid open redirects.
  • The cookie is __prerender_bypass; it is httpOnly and specific to each build.

Pages Router

Draft Mode replaced the older Preview Mode: res.setDraftMode({ enable: true }) in an API route and context.draftMode in getStaticProps.

Code example

tsx
1// app/api/draft/route.ts
2import { draftMode } from "next/headers";
3import { redirect } from "next/navigation";
4import { getPostBySlug } from "@/lib/cms";
5
6export async function GET(request: Request) {
7 const { searchParams } = new URL(request.url);
8 const secret = searchParams.get("secret");
9 const slug = searchParams.get("slug") ?? "";
10
11 if (secret !== process.env.CMS_PREVIEW_SECRET) return new Response("Invalid token", { status: 401 });
12 const post = await getPostBySlug(slug, { preview: true });
13 if (!post) return new Response("Invalid slug", { status: 404 });
14
15 (await draftMode()).enable();
16 redirect(`/blog/${post.slug}`); // only internal, validated paths
17}
18
19// app/blog/[slug]/page.tsx
20// import { draftMode } from "next/headers";
21// const { isEnabled } = await draftMode();
22// const post = await getPostBySlug(slug, { preview: isEnabled });
23
24// app/api/draft/disable/route.ts
25// export async function GET() { (await draftMode()).disable(); redirect("/"); }

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