Draft Mode

Preview CMS changes without breaking cache.

Next.js3 min readConcept 63 of 66

Bypassing the Cache Securely

Next.js heavily caches pages for performance (SSG). But content editors need a way to preview unpublished drafts from a Headless CMS (like Sanity or Contentful) *before* publishing.

**Draft Mode** solves this by setting a secure, signed cookie on the editor's browser. When Next.js detects this cookie, it temporarily bypasses the Full Route Cache and Data Cache, rendering the page dynamically.

Performance Isolation

You don't want to disable caching for everyone just because one editor is previewing a post.

Draft Mode ensures that the 99.9% of regular visitors continue to get the blazing fast, cached, statically generated version of the site, while the 0.1% (the editors) get dynamic, real-time draft data.

Enabling Draft Mode

First, create a Route Handler to enable it. This should be secured with a secret token.

typescript

// 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);

if (searchParams.get('secret') !== process.env.MY_SECRET) {

return new Response('Invalid token', { status: 401 });

}

draftMode().enable(); // Sets the signed cookie

redirect('/post/my-new-post');

}

Then, in your Server Component, check if it's enabled:

typescript

// app/post/[slug]/page.tsx

import { draftMode } from 'next/headers';

export default async function Page({ params }) {

const { isEnabled } = draftMode();

// Fetch draft data if enabled, otherwise fetch live cached data

const post = await fetchCMS(params.slug, { draft: isEnabled });

return <article>{post.title}</article>;

}

Cache Isolation Simulator

Watch how the Edge Network routes requests differently based on the presence of the Draft Mode cookie.

Initializing...
Visitor
GET /post
Editor
Cookie: __prerender
CDN
Edge Cache
CACHE HIT!
Node
Origin Server
Headless CMS

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1How does Draft Mode affect caching for regular visitors on your site?

Remember this

  • Draft Mode allows previewing headless CMS drafts without sacrificing SSG performance.
  • It uses a signed cookie to bypass the Full Route Cache and Data Cache.
  • Always secure your /api/draft route with a secret token to prevent cache-bypassing attacks.
  • Access it via import { draftMode } from 'next/headers'; in Server Components.

Done with this concept?

Mark it complete to track your progress. No login needed.