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
- The CMS preview button opens
/api/draft?secret=...&slug=/blog/post. - The Route Handler validates the secret and that the slug exists.
- It calls
(await draftMode()).enable()and redirects to the slug. - Pages check
isEnabledand fetch drafts (for example with a preview API token). - 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
isEnabledinside a"use cache"scope, but other runtime APIs remain off-limits there. enable()anddisable()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 ishttpOnlyand 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.ts2import { draftMode } from "next/headers";3import { redirect } from "next/navigation";4import { getPostBySlug } from "@/lib/cms";56export async function GET(request: Request) {7 const { searchParams } = new URL(request.url);8 const secret = searchParams.get("secret");9 const slug = searchParams.get("slug") ?? "";1011 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 });1415 (await draftMode()).enable();16 redirect(`/blog/${post.slug}`); // only internal, validated paths17}1819// app/blog/[slug]/page.tsx20// import { draftMode } from "next/headers";21// const { isEnabled } = await draftMode();22// const post = await getPostBySlug(slug, { preview: isEnabled });2324// app/api/draft/disable/route.ts25// 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.