Draft Mode cho phép biên tập viên xem trước bản nháp từ CMS trên trang vốn được render tĩnh (SSG/ISR) — tức là bỏ qua cache, fetch nội dung chưa publish.
Cơ chế: một Route Handler gọi draftMode().enable(), Next.js đặt một cookie ký; khi cookie có mặt, các trang chuyển từ static sang dynamic rendering để luôn lấy data mới.
// app/api/draft/route.ts
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export async function GET(request: Request) {
const slug = new URL(request.url).searchParams.get('slug')
// ... verify secret token từ CMS
(await draftMode()).enable()
redirect(`/posts/${slug}`)
}Trong page, đọc (await draftMode()).isEnabled để quyết định fetch bản draft hay published.
Lưu ý quan trọng: luôn xác thực một secret token trước khi enable() — nếu không, ai cũng bật được draft mode và buộc trang chạy dynamic (mất lợi ích cache, lộ nội dung chưa publish). Tắt bằng draftMode().disable().
Draft Mode lets editors preview unpublished CMS drafts on pages that are normally statically rendered (SSG/ISR) — i.e. bypass the cache and fetch unpublished content.
Mechanism: a Route Handler calls draftMode().enable(), and Next.js sets a signed cookie; while the cookie is present, pages switch from static to dynamic rendering so they always fetch fresh data.
// app/api/draft/route.ts
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export async function GET(request: Request) {
const slug = new URL(request.url).searchParams.get('slug')
// ... verify secret token from CMS
(await draftMode()).enable()
redirect(`/posts/${slug}`)
}In the page, read (await draftMode()).isEnabled to choose between draft and published fetches.
Important: always verify a secret token before enable() — otherwise anyone can turn on draft mode and force pages to render dynamically (losing cache benefits, exposing unpublished content). Disable with draftMode().disable().