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 writeawait draftMode(). - Enabling draft mode sets a secure, signed
__prerender_bypasscookie that instructs the server to render the route dynamically. - Draft Mode bypasses the Full Route Cache, but queries wrapped in
unstable_cache()orfetch({ 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.
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.
The async draftMode API and cookie contract
Next.js 15 unified all dynamic request APIs around asynchronous Promises. The draftMode function imported from next/headers must now be awaited:
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.
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:
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:
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_SECRETin your environment variables to a high-entropy string (e.g. 32 random hex bytes) generated viaopenssl rand -hex 32. - 2. Always validate redirect paths. Restrict incoming
slugparameters strictly to internal root-relative routes to prevent open-redirect exploits. - 3. Render a visible preview banner. When
draftMode().isEnabledis 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'ornext: { 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. Forgettingawaitaccesses 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 onisEnabled. - 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?
Why is draftMode() asynchronous in Next.js 15?
How does Next.js remember that Draft Mode is active?
Does Draft Mode bypass the Data Cache automatically?
How do I exit Draft Mode?
Muhammad Kashif
Founder and editor of Devventa, covering AI coding assistants, Next.js and the modern AI development stack.





