Unverified Commit 8e47c2ef authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix draft mode rendering with Cache Components (#100728)

PR #77141 made `'use cache'` bypass cache-handler reads and cache
persistence when draft mode is enabled. Later changes, including #98005,
made cached navigations reuse the static RDC. The additional
postponed-state lookup for self-hosted RSC navigations and Server
Actions did not check draft mode, so those renders could reuse published
values.

Draft mode HTML page loads already bypassed the response cache. Both
document and navigation responses could still generate an embedded
runtime prefetch with Partial Prefetching. Its final prerender expected
RDC entries that draft mode deliberately did not save, which caused
unexpected cache miss warnings.

This change skips the additional postponed-state lookup for draft mode
requests and disables cached-navigation rendering for their document and
navigation responses. Server Actions that enable draft mode discard the
published RDC before the subsequent render.

Dedicated runtime-prefetch requests still use their existing renderer.
PR #98533 proposes disabling client-initiated prefetches in draft mode.
That work remains separate and may continue in a replacement PR.

The tests cover fresh draft mode documents and navigations, actions that
enable and disable draft mode, and form submissions without JavaScript.

Fixes #100680
Closes #100685
Closes #100697
parent 1bccd951
...@@ -1496,14 +1496,12 @@ export function createAppPageEntrypoint({ ...@@ -1496,14 +1496,12 @@ export function createAppPageEntrypoint({
let hasFullyStaticCacheEntry = false let hasFullyStaticCacheEntry = false
if ( if (
// If this is a dynamic RSC request or a server action request, we should // Dynamic RSC and Server Action requests reuse the static render's
// use the postponed data from the static render (if available). This // postponed state when RDC for Navigations is enabled. Its RDC
// ensures that we can utilize the resume data cache (RDC) from the static // keeps cache values consistent with the static render. Draft mode
// render to ensure that the data is consistent between the static and // requests must generate fresh values without this published RDC.
// dynamic renders (for navigations) or when re-rendering after a server
// action.
// Only enable RDC for Navigations if the feature is enabled.
supportsRDCForNavigations && supportsRDCForNavigations &&
!isDraftMode &&
process.env.NEXT_RUNTIME !== 'edge' && process.env.NEXT_RUNTIME !== 'edge' &&
!isMinimalMode && !isMinimalMode &&
incrementalCache && incrementalCache &&
......
...@@ -1477,6 +1477,7 @@ async function executeActionAndPrepareForRender< ...@@ -1477,6 +1477,7 @@ async function executeActionAndPrepareForRender<
skipPageRendering: boolean skipPageRendering: boolean
}> { }> {
requestStore.phase = 'action' requestStore.phase = 'action'
const wasDraftModeEnabled = requestStore.draftMode.isEnabled
let skipPageRendering = shouldSkipPageRendering let skipPageRendering = shouldSkipPageRendering
if (args.length > SERVER_ACTION_ARGS_LIMIT) { if (args.length > SERVER_ACTION_ARGS_LIMIT) {
...@@ -1514,6 +1515,13 @@ async function executeActionAndPrepareForRender< ...@@ -1514,6 +1515,13 @@ async function executeActionAndPrepareForRender<
// that in the work store to be up-to-date for subsequent rendering. // that in the work store to be up-to-date for subsequent rendering.
workStore.isDraftMode = requestStore.draftMode.isEnabled workStore.isDraftMode = requestStore.draftMode.isEnabled
// The action may enable draft mode after the request received a
// published RDC. The re-render must generate fresh values without that
// RDC.
if (!wasDraftModeEnabled && requestStore.draftMode.isEnabled) {
requestStore.resumeDataCache = null
}
// If the action called revalidateTag/revalidatePath, then that might // If the action called revalidateTag/revalidatePath, then that might
// affect data used by the subsequent render, so we need to make sure all // affect data used by the subsequent render, so we need to make sure all
// revalidations are applied before that. // revalidations are applied before that.
......
...@@ -2862,7 +2862,6 @@ async function renderAppPage( ...@@ -2862,7 +2862,6 @@ async function renderAppPage(
implicitTags, implicitTags,
} = ctx } = ctx
const { cacheComponents, setIsrStatus, serverActions } = renderOpts const { cacheComponents, setIsrStatus, serverActions } = renderOpts
const { cachedNavigations } = renderOpts.experimental
const { const {
isHmrRefresh, isHmrRefresh,
isPrefetchRequest, isPrefetchRequest,
...@@ -2957,7 +2956,7 @@ async function renderAppPage( ...@@ -2957,7 +2956,7 @@ async function renderAppPage(
createRequestStore, createRequestStore,
stagedFallbackParams stagedFallbackParams
) )
} else if (cacheComponents && cachedNavigations) { } else if (shouldUseCachedNavigations(renderOpts, requestStore)) {
// MARK: RSC cacheComponents // MARK: RSC cacheComponents
return generateStagedDynamicFlightRenderResultNode(ctx, requestStore) return generateStagedDynamicFlightRenderResultNode(ctx, requestStore)
} else { } else {
...@@ -3569,7 +3568,6 @@ async function renderToStream( ...@@ -3569,7 +3568,6 @@ async function renderToStream(
cacheComponents, cacheComponents,
} = renderOpts } = renderOpts
const { cachedNavigations } = renderOpts.experimental
const waitForAllReady = supportsDynamicResponse !== true const waitForAllReady = supportsDynamicResponse !== true
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
...@@ -3859,7 +3857,7 @@ async function renderToStream( ...@@ -3859,7 +3857,7 @@ async function renderToStream(
requestId requestId
) )
} }
} else if (cacheComponents && cachedNavigations) { } else if (shouldUseCachedNavigations(renderOpts, requestStore)) {
// Production Cache Components + Cached Navigations: use staged // Production Cache Components + Cached Navigations: use staged
// rendering so the RSC payload includes the shell byte length (`a`) // rendering so the RSC payload includes the shell byte length (`a`)
// and, with Partial Prefetching, an embedded runtime prefetch that the // and, with Partial Prefetching, an embedded runtime prefetch that the
...@@ -5406,6 +5404,17 @@ export enum PrefetchingMode { ...@@ -5406,6 +5404,17 @@ export enum PrefetchingMode {
Partial = 2, Partial = 2,
} }
function shouldUseCachedNavigations(
renderOpts: RenderOpts,
requestStore: RequestStore
): boolean {
return (
renderOpts.cacheComponents &&
renderOpts.experimental.cachedNavigations === true &&
!requestStore.draftMode.isEnabled
)
}
async function getPrefetchingModeForPage( async function getPrefetchingModeForPage(
renderOpts: Pick<RenderOpts, 'partialPrefetching'>, renderOpts: Pick<RenderOpts, 'partialPrefetching'>,
loaderTree: LoaderTree loaderTree: LoaderTree
......
'use server'
import { refresh } from 'next/cache'
import { draftMode } from 'next/headers'
export async function setDraftMode(isEnabled: boolean) {
const draftModeState = await draftMode()
if (isEnabled) {
draftModeState.enable()
} else {
draftModeState.disable()
}
refresh()
}
import { Suspense } from 'react'
import Link from 'next/link'
import { cookies, draftMode } from 'next/headers'
import { setDraftMode } from '../../actions'
import { readContent } from '../../read-content'
export function generateStaticParams() {
return [{ slug: 'a' }, { slug: 'b' }]
}
async function RequestContent() {
// Keep the route partially prerendered while cached content enters the static
// RDC.
await cookies()
const { isEnabled } = await draftMode()
return <p id="current-mode">{isEnabled ? 'DRAFT' : 'PUBLISHED'}</p>
}
export default async function Page({ params }: PageProps<'/article/[slug]'>) {
const { slug } = await params
const content = await readContent(`article:${slug}`)
return (
<>
<h1>Article {slug}</h1>
<p id="page-content">{content}</p>
<Link href={slug === 'a' ? '/article/b' : '/article/a'} prefetch={false}>
Other article
</Link>
<form action={setDraftMode.bind(null, true)}>
<button id="enable-draft">Enable draft mode</button>
</form>
<form action={setDraftMode.bind(null, false)}>
<button id="disable-draft">Disable draft mode</button>
</form>
<Suspense fallback={<p>Loading request content</p>}>
<RequestContent />
</Suspense>
</>
)
}
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export async function GET(request: Request) {
const url = new URL(request.url)
const draftModeState = await draftMode()
if (url.searchParams.get('enabled') === '1') {
draftModeState.enable()
} else {
draftModeState.disable()
}
redirect(url.searchParams.get('redirectTo') ?? '/article/a')
}
import { Suspense, type ReactNode } from 'react'
import { readContent } from './read-content'
export default async function Root({ children }: { children: ReactNode }) {
const content = await readContent('layout')
return (
<html>
<body>
<p id="layout-content">{content}</p>
<Suspense fallback={<p>Loading page</p>}>{children}</Suspense>
</body>
</html>
)
}
import { randomUUID } from 'crypto'
import { cacheLife } from 'next/cache'
import { draftMode } from 'next/headers'
export async function readContent(key: string) {
'use cache'
cacheLife('hours')
const { isEnabled } = await draftMode()
return `${isEnabled ? 'draft' : 'published'}:${key}:${randomUUID()}`
}
import type * as Playwright from 'playwright'
import { nextTestSetup } from 'e2e-utils'
import { load } from 'cheerio'
import { createRouterAct } from 'router-act'
// @force-gate prefetching
describe('draft-mode-resume-data-cache', () => {
const { next, isNextStart } = nextTestSetup({ files: __dirname })
async function createBrowser(
pathname: string,
isDraftModeEnabled: boolean,
disableJavaScript = false
) {
let page: Playwright.Page
const browser = await next.browser(
`/draft?enabled=${isDraftModeEnabled ? '1' : '0'}&redirectTo=${encodeURIComponent(pathname)}`,
{
disableJavaScript,
async beforePageLoad(browserPage: Playwright.Page) {
page = browserPage
},
}
)
return {
browser,
page: page!,
act: createRouterAct(page!, { includeAppShellRequests: true }),
}
}
it('renders fresh draft documents without cache miss warnings and preserves values for requests without draft mode', async () => {
const initialDocument = await next.render$('/article/a')
const initialLayoutValue = initialDocument('#layout-content').text()
const initialPageValue = initialDocument('#page-content').text()
const outputIndex = next.cliOutput.length
const { browser } = await createBrowser('/article/a', true)
expect(await browser.elementById('current-mode').text()).toBe('DRAFT')
const draftLayout = await browser.elementById('layout-content').text()
const draftPage = await browser.elementById('page-content').text()
expect(draftLayout).toStartWith('draft:layout:')
expect(draftPage).toStartWith('draft:article:a:')
await browser.refresh()
expect(await browser.elementById('layout-content').text()).not.toBe(
draftLayout
)
expect(await browser.elementById('page-content').text()).not.toBe(draftPage)
const documentWithoutDraftMode = await next.render$('/article/a')
expect(documentWithoutDraftMode('#current-mode').text()).toBe('PUBLISHED')
expect(documentWithoutDraftMode('#layout-content').text()).toBe(
initialLayoutValue
)
expect(documentWithoutDraftMode('#page-content').text()).toBe(
initialPageValue
)
if (isNextStart) {
expect(next.cliOutput.slice(outputIndex)).not.toContain(
'Unexpected cache miss after cache warming phase'
)
}
})
it('requests fresh draft data when navigating to another page and returning', async () => {
const { browser, act } = await createBrowser('/article/a', true)
const initialValue = await browser.elementById('page-content').text()
await act(
async () => {
await browser.elementByCss('a[href="/article/b"]').click()
},
{ includes: 'DRAFT' }
)
expect(await browser.elementById('page-content').text()).toStartWith(
'draft:article:b:'
)
await act(
async () => {
await browser.elementByCss('a[href="/article/a"]').click()
},
{ includes: 'DRAFT' }
)
const returnedValue = await browser.elementById('page-content').text()
expect(returnedValue).toStartWith('draft:article:a:')
expect(returnedValue).not.toBe(initialValue)
})
it('renders draft data after an action enables draft mode and normal data after it disables draft mode', async () => {
const { browser, act } = await createBrowser('/article/a', false)
const publishedValue = await browser.elementById('page-content').text()
expect(publishedValue).toStartWith('published:article:a:')
await act(
async () => {
await browser.elementById('enable-draft').click()
},
{ includes: 'DRAFT' }
)
expect(await browser.elementById('current-mode').text()).toBe('DRAFT')
expect(await browser.elementById('page-content').text()).toStartWith(
'draft:article:a:'
)
await act(
async () => {
await browser.elementById('disable-draft').click()
},
{ includes: 'PUBLISHED' }
)
expect(await browser.elementById('current-mode').text()).toBe('PUBLISHED')
expect(await browser.elementById('page-content').text()).toStartWith(
'published:article:a:'
)
})
it('renders fresh draft data after a progressively enhanced action enables draft mode', async () => {
const { browser, page } = await createBrowser('/article/a', false, true)
expect(await browser.elementById('page-content').text()).toStartWith(
'published:article:a:'
)
const pendingResponse = page.waitForResponse(
(response) => response.request().method() === 'POST'
)
await browser.elementById('enable-draft').click()
const response = await pendingResponse
expect(response.status()).toBe(200)
const renderedPage = load(await response.text())
expect(renderedPage('#page-content').text()).toStartWith('draft:article:a:')
expect(renderedPage('#current-mode').text()).toBe('DRAFT')
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment