Skip to content

NEXT.JS 15 APP ROUTER DRAFT MODE

Next.js 15 Draft Mode: Secure Previews for Static Pages

How to implement Next.js 15 Draft Mode in the App Router: async API changes, secure preview Route Handlers, bypass cookie contracts, and exit routes.

Next.js 15 Draft Mode switches statically prerendered routes to on-demand server rendering for authenticated previewers using a signed bypass cookie. It allows headless CMS editors to preview unpublished drafts, staged marketing copy, and pending design changes in real time without triggering a full production site rebuild.

In Next.js 15, draftMode() became an asynchronous API alongside cookies() and headers(). We audited the updated handshake on next@15.5.20 in our test suite (check:draft-mode-contract), covering secret token verification, the __prerender_bypass cookie contract, open-redirect defenses, and data-layer bypass mechanics.

Key takeaways

  • In Next.js 15, draftMode() returns a Promise: always write await draftMode().
  • Enabling draft mode sets a secure, signed __prerender_bypass cookie that instructs the server to render the route dynamically.
  • Draft Mode bypasses the Full Route Cache, but queries wrapped in unstable_cache() or fetch({ cache: 'force-cache' }) still require manual draft checks.
  • Always validate the preview secret and sanitize the target redirection path to prevent open-redirect vulnerabilities.
  • Provide a dedicated exit Route Handler so content creators can easily return to published views.

What Draft Mode does in Next.js 15 App Router

Modern developer blogs, e-commerce stores, and marketing sites rely heavily on Static Site Generation (SSG) for performance. Static routes serve precompiled HTML directly from edge CDN caches.

However, content editors editing articles in Contentful, Sanity, or Strapi need to view draft content on the actual production website layout before hitting "Publish". Rebuilding the entire static site for a typo check is impractical.

Draft Mode Request Flow
CMS Preview Request
      │ (with secret token + target slug)
      ▼
┌──────────────────────────────────────────────┐
│ Route Handler: /api/draft                    │
│ 1. Validate secret token                     │
│ 2. (await draftMode()).enable()              │
│ 3. Set __prerender_bypass cookie             │
│ 4. Redirect (307) to target slug             │
└──────────────────────┬───────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────┐
│ Target Page: /blog/upcoming-post             │
│ 1. Inspect __prerender_bypass cookie         │
│ 2. Bypass Full Route Cache                   │
│ 3. Fetch draft content from CMS              │
│ 4. Render live preview HTML                  │
└──────────────────────────────────────────────┘

When Draft Mode is active, Next.js treats the requested route as a dynamic route for that specific browser session, bypassing the static HTML cache while leaving public visitors reading the cached version.

Next.js 15 unified all dynamic request APIs around asynchronous Promises. The draftMode function imported from next/headers must now be awaited:

Next.js 15 async draftMode syntax
import { draftMode } from "next/headers";

// Next.js 15: Await the draftMode call
const draft = await draftMode();

if (draft.isEnabled) {
  // Render draft banner or preview controls
}

When you call draft.enable(), Next.js sets a cookie with specific security properties:

  • Name: __prerender_bypass
  • Value: A high-entropy, cryptographically signed token generated using your deployment's internal secret.
  • Attributes: HttpOnly; Path=/; SameSite=None; Secure.

Because the cookie has SameSite=None and Secure, it functions smoothly inside <iframe> preview panes within headless CMS dashboards, while HttpOnly protects the token from client-side script inspection.

Building the secure preview Route Handler

To enable Draft Mode safely, create a Route Handler at app/api/draft/route.ts. The handler must authenticate the incoming request against a shared environment secret and guard against open-redirect phishing attacks.

app/api/draft/route.ts
import { draftMode } from "next/headers";
import { redirect } from "next/navigation";

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

  // 1. Authenticate the caller against your CMS secret
  if (secret !== process.env.DRAFT_PREVIEW_SECRET) {
    return new Response("Invalid preview secret token", { status: 401 });
  }

  // 2. Prevent open redirect vulnerabilities
  // Ensure the target is a root-relative path and does not escape with // or backslashes
  if (!slug || !slug.startsWith("/") || slug.startsWith("//") || slug.includes("\\")) {
    return new Response("Invalid redirect slug", { status: 400 });
  }

  // 3. Enable Draft Mode in Next.js 15
  const draft = await draftMode();
  draft.enable();

  // 4. Redirect to the target article or page (temporary 307 redirect)
  redirect(slug);
}

In your headless CMS preview URL configuration, point your preview button to: https://yourdomain.com/api/draft?secret=YOUR_SECRET&slug=/blog/draft-post-slug

Reading draftMode inside Server Components

Enabling Draft Mode only tells Next.js to bypass the HTML route cache. If your data fetching logic wraps CMS requests in unstable_cache() or fetch({ cache: 'force-cache' }), Next.js will still return cached database entries.

Check (await draftMode()).isEnabled when querying your data store:

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

interface PageProps {
  params: Promise<{ slug: string }>;
}

export default async function BlogPostPage({ params }: PageProps) {
  const { slug } = await params;
  const { isEnabled: isDraft } = await draftMode();

  // Pass isDraft flag to your CMS client
  // If isDraft is true, query preview APIs without caching; otherwise pull published data
  const post = await getPostBySlug(slug, { preview: isDraft });

  if (!post) {
    notFound();
  }

  return (
    <article className="prose mx-auto py-8">
      {isDraft && (
        <div className="mb-6 rounded border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">
          ⚠️ Viewing unpublished draft preview.{" "}
          <a href="/api/disable-draft" className="underline font-semibold ml-2">
            Exit Preview
          </a>
        </div>
      )}
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  );
}

Building the preview exit handler

Editors need a clean way to exit preview mode without manually clearing browser cookies. Create a route handler at app/api/disable-draft/route.ts:

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

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

  // Sanitize destination
  const safeDestination = redirectPath.startsWith("/") && !redirectPath.startsWith("//")
    ? redirectPath
    : "/";

  const draft = await draftMode();
  draft.disable();

  redirect(safeDestination);
}

Calling draft.disable() clears the __prerender_bypass cookie by setting maxAge: 0, instantly reverting the session to standard statically cached rendering.

Best practices

  • 1. Use a cryptographically random secret. Set DRAFT_PREVIEW_SECRET in your environment variables to a high-entropy string (e.g. 32 random hex bytes) generated via openssl rand -hex 32.
  • 2. Always validate redirect paths. Restrict incoming slug parameters strictly to internal root-relative routes to prevent open-redirect exploits.
  • 3. Render a visible preview banner. When draftMode().isEnabled is true, display a fixed header indicating that preview mode is active, complete with an "Exit Preview" link.
  • 4. Ensure CMS client bypasses cache. When in draft mode, instruct your API client or ORM to include draft records and pass cache: 'no-store' or next: { revalidate: 0 }.
  • 5. Keep secrets out of client bundles. Enforce that preview token verification happens strictly within server-only boundaries using import 'server-only'.

Common mistakes

  • Forgetting to await draftMode() in Next.js 15. In Next.js 15, draftMode() is an async Promise. Forgetting await accesses undefined properties and breaks runtime execution.
  • Assuming Draft Mode disables fetch caching. Draft Mode bypasses route prerendering, but does not alter hardcoded cache: 'force-cache' fetch configurations unless your code explicitly branches on isEnabled.
  • Missing SameSite=None in iframe environments. If you customize cookies or use custom proxies that strip SameSite=None, headless CMS iframe previews will fail to authenticate.
  • Using 308 Permanent Redirect instead of 307. Route Handlers must use temporary redirects (307) for draft entry so browsers do not cache the preview redirection target.

Conclusion

Next.js 15 Draft Mode delivers an optimal compromise between static site performance and live CMS editorial workflows. By establishing a secure preview Route Handler, checking await draftMode().isEnabled at the data boundary, and providing a clean exit route, your application stays blazing fast for public visitors while giving content creators instant, authentic previews.

Frequently asked questions

What is Draft Mode in Next.js 15?
Draft Mode is a built-in feature that temporarily switches statically generated pages into dynamically rendered pages for authenticated previewers, such as CMS content editors reviewing unpublished drafts before publication.
Why is draftMode() asynchronous in Next.js 15?
In Next.js 15, dynamic runtime request APIs (including cookies, headers, and draftMode) were transitioned to asynchronous Promises to align with React Server Components streaming architecture and prevent synchronous request boundary race conditions.
How does Next.js remember that Draft Mode is active?
Calling (await draftMode()).enable() sets a secure, HttpOnly, SameSite=None cookie named __prerender_bypass containing a cryptographically signed token. Subsequent page requests presenting this cookie bypass the Full Route Cache.
Does Draft Mode bypass the Data Cache automatically?
No. Draft Mode bypasses the Full Route Cache (HTML and RSC payload). If your underlying fetch() calls or database queries use cache: 'force-cache' or unstable_cache without checking draftMode.isEnabled, your page will still serve cached database results.
How do I exit Draft Mode?
Create an exit route handler calling (await draftMode()).disable(). This clears the __prerender_bypass cookie and returns the client to standard statically cached rendering.

Muhammad Kashif

Founder and editor of Devventa, covering AI coding assistants, Next.js and the modern AI development stack.