Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 72 ยท Rendering Strategies

Draft Mode and Headless CMS Previews

Use Next.js Draft Mode to preview unpublished CMS content on a statically generated site: enable and disable routes, the bypass cookie, secrets and safe redirects.

Static pages are fast because they are built once and served to everyone. That is also the problem for an editor who has just typed a new article in a CMS (a content management system, such as a headless CMS that only stores content and offers an API). The article is still a draft: it must not appear on the live site, yet the editor wants to see exactly how it will look before pressing publish. A statically generated page cannot show data that did not exist at build time.

Draft Mode is the Next.js answer. It lets one visitor, the editor, switch on a special mode in their own browser. While the mode is on, the pages for that browser skip the static cache and render at request time, so they can fetch draft content. Everyone else keeps getting the fast static pages. This lesson explains the cookie behind it, the two route handlers you write, how pages use the flag, and how to keep the preview URL safe. Next.js cannot run here, so the real code is read-only and the runnable stand-ins model the cookie flow and the page decision in Node.js.

How a preview works

Editor clicks Preview The CMS opens your enable URL.
Cookie is set Only this browser gets the bypass cookie.
Pages render live Static cache is skipped for that browser.
Disable A second route clears the cookie.

Visitors never see drafts.

1 / 2

What Draft Mode really is

When Draft Mode is enabled, Next.js sets a cookie (named __prerender_bypass) in the editor's browser. Next.js looks for that cookie on every request. If it is present, the request bypasses the static HTML and the data cache for pages that read the draft flag, so the page is rendered fresh on the server. If the cookie is absent, nothing changes: the response is the normal cached page.

The cookie value is a random string that Next.js generates when the app is built, so it cannot be guessed. It is a session cookie, so it ends when the browser closes, unless you disable the mode earlier.

Reading the flag is done with draftMode() from next/headers. In Next.js 15 and later it is an async function, like cookies() and headers() (see Cookies and Headers and Dynamic APIs):

TypeScript
import { draftMode } from "next/headers";

const { isEnabled } = await draftMode(); // true only for browsers with the cookie

Next.js still prerenders the page for normal visitors at build time and revalidates it as usual; the draft branch only runs for requests that carry the cookie.

Step 1: the enable route

Create a Route Handler that the CMS opens. It must check a secret first. Without a secret, anyone could turn on Draft Mode and read unpublished content.

TypeScript
// app/api/draft/enable/route.ts (read-only)
import { draftMode } from "next/headers";
import { redirect } from "next/navigation";
import { getPostBySlug } from "@/lib/cms";

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const secret = searchParams.get("secret");
  const slug = searchParams.get("slug");

  if (secret !== process.env.DRAFT_SECRET || !slug) {
    return new Response("Invalid token", { status: 401 });
  }

  // Check the post exists in the CMS, using a draft-capable token.
  const post = await getPostBySlug(slug, { draft: true });
  if (!post) {
    return new Response("Post not found", { status: 404 });
  }

  (await draftMode()).enable();
  redirect(`/blog/${post.slug}`);
}

Three safety rules are visible here:

  1. Compare a secret that only the CMS and your server know (DRAFT_SECRET, stored in an environment variable, see Environment Variables).
  2. Never redirect to a URL taken from the request. Take a slug, look it up, and build the path yourself. Otherwise an attacker can send an editor a link that turns on Draft Mode and then redirects to a malicious site (an open redirect).
  3. Check the content exists, so a typo gives a clear 404 and not a blank page.

Most headless CMS products (Contentful, Sanity, Strapi, WordPress and others) let you configure a preview URL template such as https://example.com/api/draft/enable?secret=...&slug={entry.slug}, and show a "Preview" button that opens it.

The second rule deserves a demonstration. The stand-in below compares a redirect that copies a URL from the request (unsafe) with one that builds the path from a slug that must look like a slug (safe). Try the attacker's input and see where each one sends the editor.

Node.js Open redirect versus a path you build yourself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Step 2: the disable route

The editor needs a way out, otherwise they would keep seeing drafts until the browser closes.

TypeScript
// app/api/draft/disable/route.ts (read-only)
import { draftMode } from "next/headers";
import { redirect } from "next/navigation";

export async function GET() {
  (await draftMode()).disable();
  redirect("/");
}

A common touch is a small banner on every page, shown only while the mode is on, with a link to this route:

TSX
// app/layout.tsx (read-only)
import { draftMode } from "next/headers";
import Link from "next/link";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const { isEnabled } = await draftMode();
  return (
    <html lang="en">
      <body>
        {isEnabled && (
          <div role="status">
            Draft mode is on. <Link href="/api/draft/disable" prefetch={false}>Exit</Link>
          </div>
        )}
        {children}
      </body>
    </html>
  );
}

Notice prefetch={false} on the exit link. Prefetching would call the route in the background, and the mode would switch off by itself.

Step 3: fetch drafts when the flag is on

The page decides what to fetch. The CMS client usually takes a different token or URL for drafts and returns both published and unpublished entries.

TSX
// app/blog/[slug]/page.tsx (read-only)
import { draftMode } from "next/headers";
import { notFound } from "next/navigation";
import { getPostBySlug } from "@/lib/cms";

export async function generateStaticParams() {
  const posts = await getAllPublishedSlugs();
  return posts.map((slug) => ({ slug }));
}

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const { isEnabled } = await draftMode();

  const post = await getPostBySlug(slug, { draft: isEnabled });
  if (!post) notFound();

  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </article>
  );
}

For a normal visitor the page is served from the static cache built from published content. For the editor the same URL fetches the draft version, because the cookie is present. A brand-new post that has no static page yet also works, because requests for unknown slugs are rendered on demand while the cookie is present (as long as dynamicParams is not set to false, see Static Generation).

The stand-in below models the decision. A "request" is an object with cookies, the page logic chooses between a cached published copy and a fresh draft, and the route handlers set and clear the cookie. It uses the real cookie rules (a Set-Cookie header on the way out, a Cookie header on the way in) in a few lines.

Node.js Model the draft cookie and the page decision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Rows 1 and 6 show the key difference for the same URL: the visitor gets the cached published text and the editor gets the draft. Row 2 and 5 show that an unpublished post is a 404 for the public and visible to the editor.

Draft Mode compared with other ideas

  • Revalidation (Revalidation) updates the live cached page after publishing, for everyone. Draft Mode shows unpublished content to one person before publishing. A CMS setup usually uses both: Draft Mode while editing, a webhook that calls revalidateTag after publishing.
  • Fully dynamic pages would always fetch fresh content but lose caching for all visitors. Draft Mode keeps the cache for everyone except the editor.
  • Authentication (Authentication Basics) protects content per user account. Draft Mode is only a rendering switch behind a shared secret; it does not identify the editor. Do not put private information behind it.

Pitfalls

  • The cookie must reach your site. If the preview opens in an iframe inside the CMS, the browser may refuse to send third-party cookies, and Draft Mode silently fails. Open the preview in a new tab instead. In production over HTTPS Next.js sets the cookie with SameSite=None; Secure so embedding can work, but browsers keep tightening third-party cookie rules, so test your CMS.
  • Caching in front of your app. A CDN must not cache pages for requests that carry the __prerender_bypass cookie. Most platforms for Next.js handle this; with a custom CDN configure it yourself.
  • Data fetching must read the flag. fetch and database calls are not magically uncached. Your CMS client has to switch to the draft token or the draft API when isEnabled is true.
  • Secrets stay server-side. The draft token for the CMS is a server environment variable. Never expose it with NEXT_PUBLIC_.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Draft Mode change for a visitor without the bypass cookie?

    Draft Mode is per browser. Only requests that carry the bypass cookie skip the static cache.
  2. 2. Why must the enable route check a secret?

    The enable URL is the gate to unpublished content. A shared secret known only to the CMS and your server prevents strangers from using it.
  3. 3. How should the enable route choose the redirect target?

    Copying a URL from the request creates an open redirect. Build the path yourself from data you checked.
  4. 4. Why does the exit link use prefetch={false}?

    next/link prefetches visible links. A prefetch of the disable route would run it, which clears the cookie without the editor clicking.

Summary

  • Draft Mode lets one browser see unpublished content on an otherwise static site by setting a bypass cookie.
  • Write an enable route that checks a secret and a slug, calls (await draftMode()).enable() and redirects to a path you build yourself.
  • Write a disable route that calls .disable(), and show a banner with a non-prefetched link while the mode is on.
  • Pages read const { isEnabled } = await draftMode() and ask the CMS for draft content when it is true.
  • Combine it with revalidation after publish, and keep the CMS draft token on the server.

Next: Edge and Node.js Runtimes