草稿模式
草稿模式讓您可以在 Next.js 應用程式中預覽來自無頭 CMS 的草稿內容。這對於在建置時生成的靜態頁面很有用,因為它允許您切換到動態渲染並查看草稿變更,而無需重建整個網站。
本頁將逐步說明如何啟用和使用草稿模式。
步驟 1:建立路由處理器
建立一個路由處理器。它可以有任何名稱,例如 app/api/draft/route.ts
。
export async function GET(request: Request) {
return new Response('')
}
接著,導入draftMode
函式並呼叫 enable()
方法。
import { draftMode } from 'next/headers'
export async function GET(request: Request) {
const draft = await draftMode()
draft.enable()
return new Response('Draft mode is enabled')
}
這將設定一個Cookie來啟用草稿模式。後續包含此Cookie的請求將觸發草稿模式並更改靜態生成頁面的行為。
您可以透過訪問 /api/draft
並查看瀏覽器的開發者工具來手動測試。請注意帶有名為 __prerender_bypass
的 Cookie 的 Set-Cookie
回應標頭。
步驟 2:從您的無頭 CMS 存取路由處理程式
這些步驟假設您正在使用的無頭 CMS 支援設定自訂草稿網址。如果它不支援,您仍然可以使用此方法來保護您的草稿網址,但您需要手動建構和存取草稿網址。具體步驟將根據您使用的無頭 CMS 而有所不同。
要從您的無頭 CMS 安全地存取路由處理程式
- 使用您選擇的權杖產生器建立一個秘密權杖字串。此秘密只有您的 Next.js 應用程式和您的無頭 CMS 知道。
- 如果您的無頭 CMS 支援設定自訂草稿網址,請指定一個草稿網址(這假設您的路由處理程式位於
app/api/draft/route.ts
)。例如
https://<your-site>/api/draft?secret=<token>&slug=<path>
<your-site>
應為您的部署網域。<token>
應替換為您產生的秘密權杖。<path>
應為您要檢視的頁面的路徑。如果您要檢視/posts/one
,則應使用&slug=/posts/one
。您的無頭 CMS 可能允許您在草稿網址中包含一個變數,以便可以根據 CMS 的資料動態設定
<path>
,如下所示:&slug=/posts/{entry.fields.slug}
- 在您的路由處理程式中,檢查秘密是否匹配以及
slug
參數是否存在(如果不存在,請求應失敗),呼叫draftMode.enable()
來設定 Cookie。然後,將瀏覽器重新導向至slug
指定的路徑
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export async function GET(request: Request) {
// Parse query string parameters
const { searchParams } = new URL(request.url)
const secret = searchParams.get('secret')
const slug = searchParams.get('slug')
// Check the secret and next parameters
// This secret should only be known to this Route Handler and the CMS
if (secret !== 'MY_SECRET_TOKEN' || !slug) {
return new Response('Invalid token', { status: 401 })
}
// Fetch the headless CMS to check if the provided `slug` exists
// getPostBySlug would implement the required fetching logic to the headless CMS
const post = await getPostBySlug(slug)
// If the slug doesn't exist prevent draft mode from being enabled
if (!post) {
return new Response('Invalid slug', { status: 401 })
}
// Enable Draft Mode by setting the cookie
const draft = await draftMode()
draft.enable()
// Redirect to the path from the fetched post
// We don't redirect to searchParams.slug as that might lead to open redirect vulnerabilities
redirect(post.slug)
}
如果成功,則瀏覽器將被重新導向至您要使用草稿模式 Cookie 檢視的路徑。
步驟 3:預覽草稿內容
下一步是更新您的頁面以檢查 draftMode().isEnabled
的值。
如果您請求已設定 Cookie 的頁面,則資料將在請求時擷取(而不是在建置時)。
此外,isEnabled
的值將為 true
。
// page that fetches data
import { draftMode } from 'next/headers'
async function getData() {
const { isEnabled } = await draftMode()
const url = isEnabled
? 'https://draft.example.com'
: 'https://production.example.com'
const res = await fetch(url)
return res.json()
}
export default async function Page() {
const { title, desc } = await getData()
return (
<main>
<h1>{title}</h1>
<p>{desc}</p>
</main>
)
}
如果您從無頭 CMS 或使用網址手動存取草稿路由處理程式(包含 secret
和 slug
),您現在應該能夠看到草稿內容。而且,如果您更新草稿而不發佈,您應該能夠檢視草稿。
這有幫助嗎?