Skip to main content

草稿模式

当你的页面从无头 CMS 获取数据时,静态渲染非常有用。但是,当你在无头 CMS 上编写草稿并希望立即在页面上查看草稿时,这并不理想。你希望 Next.js 在请求时而不是构建时渲染这些页面,并获取草稿内容而不是已发布的内容。你希望 Next.js 仅针对这种特定情况切换到 动态渲染

¥Static rendering is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to view the draft immediately on your page. You’d want Next.js to render these pages at request time instead of build time and fetch the draft content instead of the published content. You’d want Next.js to switch to dynamic rendering only for this specific case.

Next.js 有一个名为草稿模式的功能可以解决这个问题。以下是有关如何使用它的说明。

¥Next.js has a feature called Draft Mode which solves this problem. Here are instructions on how to use it.

步骤 1:创建并访问路由处理程序

¥Step 1: Create and access the Route Handler

首先,创建一个 路由处理程序。它可以有任何名称 - 例如 app/api/draft/route.ts

¥First, create a Route Handler. It can have any name - e.g. app/api/draft/route.ts

然后,从 next/headers 导入 draftMode 并调用 enable() 方法。

¥Then, import draftMode from next/headers and call the enable() method.

// route handler enabling draft mode
import { draftMode } from 'next/headers'

export async function GET(request: Request) {
draftMode().enable()
return new Response('Draft mode is enabled')
}
// route handler enabling draft mode
import { draftMode } from 'next/headers'

export async function GET(request) {
draftMode().enable()
return new Response('Draft mode is enabled')
}

这将设置一个 cookie 以启用草稿模式。包含此 cookie 的后续请求将触发草稿模式,更改静态生成页面的行为(稍后会详细介绍)。

¥This will set a cookie to enable draft mode. Subsequent requests containing this cookie will trigger Draft Mode changing the behavior for statically generated pages (more on this later).

你可以通过访问 /api/draft 并查看浏览器的开发者工具来手动测试这一点。请注意 Set-Cookie 响应标头以及名为 __prerender_bypass 的 cookie。

¥You can test this manually by visiting /api/draft and looking at your browser’s developer tools. Notice the Set-Cookie response header with a cookie named __prerender_bypass.

从 Headless CMS 安全地访问它

¥Securely accessing it from your Headless CMS

在实践中,你希望从无头 CMS 安全地调用此路由处理程序。具体步骤将根据你使用的无头 CMS 的不同而有所不同,但以下是你可以采取的一些常见步骤。

¥In practice, you’d want to call this Route Handler securely from your headless CMS. The specific steps will vary depending on which headless CMS you’re using, but here are some common steps you could take.

这些步骤假设你使用的无头 CMS 支持设置自定义草稿 URL。如果没有,你仍然可以使用此方法来保护草稿 URL,但你需要手动构建和访问草稿 URL。

¥These steps assume that the headless CMS you’re using supports setting custom draft URLs. If it doesn’t, you can still use this method to secure your draft URLs, but you’ll need to construct and access the draft URL manually.

首先,你应该使用你选择的令牌生成器创建一个秘密令牌字符串。这个秘密只有你的 Next.js 应用和无头 CMS 知道。此密钥可防止无权访问你的 CMS 的人员访问草稿 URL。

¥First, you should create a secret token string using a token generator of your choice. This secret will only be known by your Next.js app and your headless CMS. This secret prevents people who don’t have access to your CMS from accessing draft URLs.

其次,如果你的无头 CMS 支持设置自定义草稿 URL,请指定以下内容作为草稿 URL。这假设你的路由处理程序位于 app/api/draft/route.ts

¥Second, if your headless CMS supports setting custom draft URLs, specify the following as the draft URL. This assumes that your Route Handler is located at app/api/draft/route.ts

https://<your-site>/api/draft?secret=<token>&slug=<path>
  • <your-site> 应该是你的部署域。

    ¥<your-site> should be your deployment domain.

  • <token> 应替换为你生成的秘密令牌。

    ¥<token> should be replaced with the secret token you generated.

  • <path> 应该是你要查看的页面的路径。如果你想查看 /posts/foo,那么你应该使用 &slug=/posts/foo

    ¥<path> should be the path for the page that you want to view. If you want to view /posts/foo, then you should use &slug=/posts/foo.

你的无头 CMS 可能允许你在草稿 URL 中包含一个变量,以便可以根据 CMS 的数据动态设置 <path>,如下所示:&slug=/posts/{entry.fields.slug}

¥Your headless CMS might allow you to include a variable in the draft URL so that <path> can be set dynamically based on the CMS’s data like so: &slug=/posts/{entry.fields.slug}

最后,在路由处理程序中:

¥Finally, in the Route Handler:

  • 检查密钥是否匹配以及 slug 参数是否存在(如果不存在,则请求应失败)。

    ¥Check that the secret matches and that the slug parameter exists (if not, the request should fail).

  • 调用 draftMode.enable() 设置 cookie。

    ¥Call draftMode.enable() to set the cookie.

  • 然后将浏览器重定向到 slug 指定的路径。

    ¥Then redirect the browser to the path specified by slug.

// route handler with secret and 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
draftMode().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)
}
// route handler with secret and slug
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'

export async function GET(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
draftMode().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 查看的路径。

¥If it succeeds, then the browser will be redirected to the path you want to view with the draft mode cookie.

步骤 2:更新页面

¥Step 2: Update page

下一步是更新你的页面以检查 draftMode().isEnabled 的值。

¥The next step is to update your page to check the value of draftMode().isEnabled.

如果你请求设置了 cookie 的页面,则将在请求时(而不是在构建时)获取数据。

¥If you request a page which has the cookie set, then data will be fetched at request time (instead of at build time).

此外,isEnabled 的值将是 true

¥Furthermore, the value of isEnabled will be true.

// page that fetches data
import { draftMode } from 'next/headers'

async function getData() {
const { isEnabled } = 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>
)
}
// page that fetches data
import { draftMode } from 'next/headers'

async function getData() {
const { isEnabled } = 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 或手动访问草稿路由处理程序(使用 secretslug),你现在应该能够看到草稿内容。如果你更新草稿而不发布,你应该能够查看该草稿。

¥That's it! If you access the draft Route Handler (with secret and slug) from your headless CMS or manually, you should now be able to see the draft content. And if you update your draft without publishing, you should be able to view the draft.

将其设置为无头 CMS 上的草稿 URL 或手动访问,你应该能够看到草稿。

¥Set this as the draft URL on your headless CMS or access manually, and you should be able to see the draft.

https://<your-site>/api/draft?secret=<token>&slug=<path>

更多细节

¥More Details

¥Clear the Draft Mode cookie

默认情况下,草稿模式会话在浏览器关闭时结束。

¥By default, the Draft Mode session ends when the browser is closed.

要手动清除草稿模式 cookie,请创建一个调用 draftMode().disable() 的路由处理程序:

¥To clear the Draft Mode cookie manually, create a Route Handler that calls draftMode().disable():

import { draftMode } from 'next/headers'

export async function GET(request: Request) {
draftMode().disable()
return new Response('Draft mode is disabled')
}
import { draftMode } from 'next/headers'

export async function GET(request) {
draftMode().disable()
return new Response('Draft mode is disabled')
}

然后,向 /api/disable-draft 发送请求以调用 Route Handler。如果使用 next/link 调用此路由,则必须传递 prefetch={false} 以防止在预取时意外删除 cookie。

¥Then, send a request to /api/disable-draft to invoke the Route Handler. If calling this route using next/link, you must pass prefetch={false} to prevent accidentally deleting the cookie on prefetch.

每个 next build 都是唯一的

¥Unique per next build

每次运行 next build 时都会生成一个新的旁路 cookie 值。

¥A new bypass cookie value will be generated each time you run next build.

这确保了旁路 cookie 无法被猜测。

¥This ensures that the bypass cookie can’t be guessed.

很高兴知道:要通过 HTTP 在本地测试草稿模式,你的浏览器需要允许第三方 cookie 和本地存储访问。

¥Good to know: To test Draft Mode locally over HTTP, your browser will need to allow third-party cookies and local storage access.