Disable prefetching in draft mode

With Cache Components enabled, draft-mode prefetches bypass prerendered
output and can receive full dynamic RSC responses. The loading-boundary
fallback can cache completed content using static-stage param
dependencies, allowing sibling URLs to reuse the wrong content.

We considered preserving prefetching by fixing request scoping and
skipping staged rendering for draft responses. That still performs
speculative server work and can retain preview content after a CMS edit.
Disabling draft prefetches avoids creating those speculative snapshots,
without on-demand segment prerenders or a blanket restriction on valid
vary-param reuse.

This change pauses the prefetch scheduler while draft mode is enabled.
The initial RSC payload reports the draft state, and a Server Action
that writes the draft cookie reports the new state in a response header,
so the router applies it before Flight decoding and before cache
invalidation reschedules visible links. Paused tasks stay queued and
resume through the existing revalidation cooldown once draft mode is
disabled, including when the action response body fails to decode.
Normal navigation and cache-consumption policies remain unchanged, and
the Instant Navigation Testing API can still run the foreground tasks
needed to complete a navigation.

The router learns the state only from the initial document and from
Server Actions. A Route Handler that toggles the cookie and is called
with a client-side `fetch()` followed by `router.refresh()` leaves the
prefetching state unchanged until the next page load; the docs now say
to redirect from such a handler.

Forwarded Server Actions now also pass the worker's `Set-Cookie` headers
through to the browser. They were previously dropped together with the
other `actionsForbiddenHeaders`, so a `cookies().set()` inside a
forwarded action never reached the client. Draft mode depends on this,
but it applies to every cookie a forwarded action writes.
parent 63bb9d6a
......@@ -21,9 +21,12 @@ When Draft Mode is enabled for a request:
- Components and functions inside [`'use cache'`](/docs/app/api-reference/directives/use-cache) re-execute on every request, and their results are not saved to the cache.
- [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) reads and writes are bypassed in the same way.
- The page is excluded from the ISR response cache and is served with `Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate`.
- The App Router disables prefetching through [`<Link>`](/docs/app/api-reference/components/link) and [`router.prefetch()`](/docs/app/api-reference/functions/use-router). Client-side navigation still works and fetches missing data when needed.
The effect applies whether the page is statically generated, served from cache, or revalidated through ISR.
> **Good to know:** The router learns the Draft Mode state from the initial page load and from Server Actions that call `enable()` or `disable()`. A Route Handler that toggles Draft Mode should redirect, as in the examples below, so that the browser loads a new document. Toggling the cookie with a client-side `fetch()` and calling `router.refresh()` does not update the router's prefetching behavior until the next page load.
## What this guide covers
This guide assumes:
......
......@@ -45,6 +45,7 @@ The following methods and properties are available:
- [`isEnabled`](#checking-if-draft-mode-is-enabled) is readable inside a [caching directive](/docs/app/api-reference/directives/use-cache) scope. Other runtime APIs like `cookies()` and `headers()` are not allowed inside caching directive scopes, even when Draft Mode is active.
- Calling `enable()` or `disable()` inside a caching directive scope will throw an error.
- When Draft Mode is enabled, all functions and components under a caching directive scope re-execute on every request and results are not saved to the cache. This ensures draft content is always fresh.
- In the App Router, [`<Link>`](/docs/app/api-reference/components/link) and [`router.prefetch()`](/docs/app/api-reference/functions/use-router) do not prefetch routes while Draft Mode is enabled. Client-side navigation still works and fetches missing data when needed. The router learns the state from the initial page load and from Server Actions that call `enable()` or `disable()`; a Route Handler that toggles Draft Mode should redirect so the browser loads a new document.
## Examples
......
......@@ -27,6 +27,7 @@ import type { StaticIndicatorState } from './dev/hot-reloader/app/hot-reloader-a
import { createInitialRSCPayloadFromFallbackPrerender } from './flight-data-helpers'
import { getDeploymentId } from '../shared/lib/deployment-id'
import { setNavigationBuildId } from './navigation-build-id'
import { setIsDraftMode } from './components/segment-cache/scheduler'
import type { ClientInstrumentationModules } from './router-transition-types'
import { initializeRouterTransitionModules } from './components/router-transition'
......@@ -375,6 +376,10 @@ export async function hydrate(
initializeRouterTransitionModules(instrumentationModules)
// The prefetch scheduler needs the draft-mode state before the first Link
// mounts/hydrates.
setIsDraftMode(initialRSCPayload.D)
const initialTimestamp = Date.now()
const actionQueue: AppRouterActionQueue = createMutableActionQueue(
createInitialRouterState({
......
......@@ -42,3 +42,4 @@ export const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id' as const
// TODO: Should this include nextjs in the name, like the others?
export const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated' as const
export const NEXT_ACTION_DRAFT_MODE_HEADER = 'x-action-draft-mode' as const
......@@ -7,6 +7,7 @@ import { findSourceMapURL } from '../../../app-find-source-map-url'
import {
ACTION_HEADER,
NEXT_ACTION_NOT_FOUND_HEADER,
NEXT_ACTION_DRAFT_MODE_HEADER,
NEXT_IS_PRERENDER_HEADER,
NEXT_HTML_REQUEST_ID_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
......@@ -48,7 +49,10 @@ import {
invalidateEntirePrefetchCache,
segmentCacheMap,
} from '../../segment-cache/cache'
import { startRevalidationCooldown } from '../../segment-cache/scheduler'
import {
setIsDraftMode,
startRevalidationCooldown,
} from '../../segment-cache/scheduler'
import { getDeploymentId } from '../../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../../lib/constants'
......@@ -174,6 +178,18 @@ async function fetchServerAction(
throw err
}
// The action wrote the draft cookie. Update the scheduler from the headers,
// before the cache invalidation below reschedules visible links and before
// the body can fail to decode.
const draftMode = res.headers.get(NEXT_ACTION_DRAFT_MODE_HEADER)
if (draftMode !== null) {
if (draftMode !== '0' && draftMode !== '1') {
throw new Error('Invalid draft mode header in Server Action response.')
}
setIsDraftMode(draftMode === '1')
action.didRevalidate = true
}
// Handle server actions that the server didn't recognize.
const unrecognizedActionHeader = res.headers.get(NEXT_ACTION_NOT_FOUND_HEADER)
if (unrecognizedActionHeader === '1') {
......@@ -557,6 +573,14 @@ export function serverActionReducer(
)
},
(e: any) => {
if (action.didRevalidate) {
// The draft cookie can change even if decoding the action response
// fails. Invalidate its old cache entries and let the normal cooldown
// restart queued prefetches.
invalidateBfCache()
invalidateEntirePrefetchCache(nextUrl, state.root)
startRevalidationCooldown()
}
// When the server action is rejected we don't update the state and instead call the reject handler of the promise.
reject(e)
......
......@@ -33,6 +33,7 @@ import { fetch } from './fetch'
import {
pingPrefetchTask,
isPrefetchTaskDirty,
isPrefetchingAllowed,
type PrefetchTask,
type PrefetchSubtaskResult,
} from './scheduler'
......@@ -2452,13 +2453,14 @@ function readFulfilledStaleAt(
* task's *other* fallback segments get re-attempted. If every attempt is
* still a fallback (or fails), it gives up.
*
* A loop runs at most once per task, ever (fetchAndWritePerSegmentPrefetchResponse
* gates on `fallbackRetryStatus === Empty`, set to `Pending` before this runs
* and never reset to `Empty`). The sleep timer is never `clearTimeout`-ed, so
* the awaited sleep always settles; the loop simply checks `isCanceled` after
* waking and bails if the task was canceled in the meantime. On success the
* status becomes `Fulfilled`; on any non-success exit (exhausted retries,
* fetch error, or cancel) it becomes `Rejected`.
* A loop runs at most once per task, ever
* (fetchAndWritePerSegmentPrefetchResponse gates on `fallbackRetryStatus ===
* Empty`, set to `Pending` before this runs and never reset to `Empty`). The
* sleep timer is never `clearTimeout`-ed, so the awaited sleep always settles;
* the loop simply checks `isCanceled` and `isPrefetchingAllowed` after waking
* and bails if the task was canceled or prefetching was paused in the meantime.
* On success the status becomes `Fulfilled`; on any non-success exit (exhausted
* retries, fetch error, cancel, or pause) it becomes `Rejected`.
*/
async function retryUpgradeableFallbackPrefetch(
task: PrefetchTask,
......@@ -2473,8 +2475,7 @@ async function retryUpgradeableFallbackPrefetch(
await new Promise<void>((resolve) =>
setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)
)
if (task.isCanceled) {
if (task.isCanceled || !isPrefetchingAllowed(task)) {
break
}
......@@ -2519,7 +2520,8 @@ async function retryUpgradeableFallbackPrefetch(
}
// The loop finished without success (exhausted its retries, broke out on a
// fetch error, or the task was canceled). It won't run again for this task.
// fetch error, the task was canceled, or prefetching was paused). It won't
// run again for this task.
task.fallbackRetryStatus = EntryStatus.Rejected
}
......
......@@ -294,6 +294,18 @@ export function startRevalidationCooldown(): void {
}, REVALIDATION_COOLDOWN_MS)
}
// Whether the browser session is in draft mode. Prefetching pauses while it is,
// because a draft response must not be stored as speculative data. Null until
// hydration reports the initial state; a Server Action that writes the draft
// cookie updates it from its response headers. The state lives here, not in the
// router state, because the cookie still changes when a navigation discards the
// action's render result.
let isDraftMode: boolean | null = null
export function setIsDraftMode(value: boolean): void {
isDraftMode = value
}
export type IncludeDynamicData = null | 'full' | 'dynamic'
/**
......@@ -475,6 +487,24 @@ export function pingPrefetchScheduler() {
scheduleMicrotask(processQueueInMicrotask)
}
export function isPrefetchingAllowed(task: PrefetchTask): boolean {
if (
process.env.__NEXT_EXPOSE_TESTING_API &&
task._navigationLockPrefetch != null
) {
// The testing API uses this task to fulfill a navigation, not to fetch
// speculative data. Blocking it would leave that navigation waiting
// forever.
return true
}
if (isDraftMode === null) {
throw new Error(
'Internal Next.js error: Prefetch scheduled before hydration.'
)
}
return !isDraftMode
}
/**
* Checks if we've exceeded the maximum number of concurrent prefetch requests,
* to avoid saturating the browser's internal network queue. This is a
......@@ -588,8 +618,27 @@ function processQueueInMicrotask() {
const now = Date.now()
// Process the task queue until we run out of network bandwidth.
let pausedTasks: PrefetchTask[] | null = null
let task = heapPeek(taskHeap)
while (task !== null && hasNetworkBandwidth(task)) {
processTasks: while (task !== null) {
if (!isPrefetchingAllowed(task)) {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// A navigation-testing task may be behind a paused Link prefetch. Keep
// the paused tasks out of this pass so they cannot block the
// navigation.
heapPop(taskHeap)
if (pausedTasks === null) {
pausedTasks = []
}
pausedTasks.push(task)
task = heapPeek(taskHeap)
continue
}
break
}
if (!hasNetworkBandwidth(task)) {
break
}
task.routeCacheVersion = getCurrentRouteCacheVersion()
task.segmentCacheVersion = getCurrentSegmentCacheVersion()
......@@ -608,7 +657,7 @@ function processQueueInMicrotask() {
case PrefetchTaskExitStatus.InProgress:
// The task yielded because there are too many requests in progress.
// Stop processing tasks until we have more bandwidth.
return
break processTasks
case PrefetchTaskExitStatus.Blocked:
// The task is blocked. It needs more data before it can proceed.
// Keep the task out of the queue until the server responds.
......@@ -691,11 +740,21 @@ function processQueueInMicrotask() {
}
}
// Run LRU cleanup only when the scheduler is fully idle: no queued tasks and
// no in-progress requests. At that point, all active prefetch tasks have
if (pausedTasks !== null) {
for (const pausedTask of pausedTasks) {
heapPush(taskHeap, pausedTask)
}
task = heapPeek(taskHeap)
}
// Run LRU cleanup only when the scheduler is fully idle: no runnable tasks
// and no in-progress requests. At that point, all active prefetch tasks have
// finished reading from the cache (moving recently used entries to the front
// of the list), so only genuinely stale data gets evicted.
if (task === null && inProgressRequests === 0) {
if (
inProgressRequests === 0 &&
(task === null || !isPrefetchingAllowed(task))
) {
cleanup()
}
}
......
......@@ -48,6 +48,7 @@ export function createInitialRSCPayloadFromFallbackPrerender(
const canonicalUrl = createHrefFromUrl(new URL(location.href))
const fallbackTransportData = fallbackInitialRSCPayload.t
const payload: InitialRSCPayload = {
D: fallbackInitialRSCPayload.D,
c: canonicalUrl.split('/'),
q: renderedSearch,
i: fallbackInitialRSCPayload.i,
......
......@@ -15,6 +15,7 @@ import {
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_URL,
NEXT_ACTION_REVALIDATED_HEADER,
NEXT_ACTION_DRAFT_MODE_HEADER,
} from '../../client/components/app-router-headers'
import {
getAccessFallbackHTTPStatus,
......@@ -81,6 +82,7 @@ import {
ActionDidRevalidateStaticAndDynamic,
} from '../../shared/lib/action-revalidation-kind'
import { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'
import { COOKIE_NAME_PRERENDER_BYPASS } from '../api-utils'
const INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'
......@@ -160,7 +162,7 @@ function getForwardedHeaders(
return new Headers(mergedHeaders)
}
function addRevalidationHeader(
function addActionResponseHeaders(
res: BaseNextResponse,
{
workStore,
......@@ -192,11 +194,22 @@ function addRevalidationHeader(
)
? 1
: 0
const isCookieRevalidated = getModifiedCookieValues(
requestStore.mutableCookies
).length
? 1
: 0
const modifiedCookies = getModifiedCookieValues(requestStore.mutableCookies)
const isCookieRevalidated = modifiedCookies.length ? 1 : 0
// Report draft mode only when this action writes its cookie. An unrelated
// action can finish after a mode change and still have the old request's
// draft state.
if (
modifiedCookies.some(
(cookie) => cookie.name === COOKIE_NAME_PRERENDER_BYPASS
)
) {
res.setHeader(
NEXT_ACTION_DRAFT_MODE_HEADER,
requestStore.draftMode.isEnabled ? '1' : '0'
)
}
// First check if a tag, cookie, or path was revalidated.
if (isTagRevalidated || isCookieRevalidated) {
......@@ -318,6 +331,11 @@ async function createForwardedActionResponse(
if (
response.headers.get('content-type')?.startsWith(RSC_CONTENT_TYPE_HEADER)
) {
// Forward cookie changes together with the action's revalidation and
// draft-mode headers.
for (const cookie of response.headers.getSetCookie()) {
res.appendHeader('set-cookie', cookie)
}
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers) {
if (!actionsForbiddenHeaders.includes(key)) {
......@@ -1303,7 +1321,7 @@ export async function handleAction({
requestStore,
shouldSkipPageRendering
).finally(() => {
addRevalidationHeader(res, { workStore, requestStore })
addActionResponseHeaders(res, { workStore, requestStore })
if (logInfo) {
// Store server action log info to be logged after the request log
const duration = Math.round(performance.now() - startTime)
......
......@@ -255,6 +255,7 @@ import { runInSequentialTasks } from './app-render-render-utils'
import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler'
import {
getHmrRefreshHash,
throwInvariantForMissingStore,
workUnitAsyncStorage,
type PrerenderStore,
} from './work-unit-async-storage.external'
......@@ -2165,6 +2166,34 @@ function prepareInitialCanonicalUrl(url: RequestStore['url']) {
return (url.pathname + url.search).split('/')
}
function getInitialDraftMode(workStore: WorkStore): boolean {
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore) {
throwInvariantForMissingStore()
}
switch (workUnitStore.type) {
case 'request':
case 'prerender-runtime':
// These stores carry the request's validated draft-cookie state. The Edge
// SSR entrypoint sets renderOpts.isDraftMode to false, so
// workStore.isDraftMode can be false even when the request is in draft
// mode.
return workUnitStore.draftMode.isEnabled
case 'prerender':
case 'prerender-client':
case 'prerender-legacy':
case 'validation-client':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'build-time-generator':
return workStore.isDraftMode === true
default:
return workUnitStore satisfies never
}
}
// This is the data necessary to render <AppRouter /> when no SSR errors are encountered
async function getRSCPayload(
tree: LoaderTree,
......@@ -2292,6 +2321,7 @@ async function getRSCPayload(
P: createElement(Preloads, {
preloadCallbacks: preloadCallbacks,
}),
D: getInitialDraftMode(ctx.workStore),
c: prepareInitialCanonicalUrl(url),
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
......@@ -2445,6 +2475,7 @@ async function getErrorRSCPayload(
const isPossiblyPartialHead = ctx.renderCapabilities.isPossiblyPartialResponse
return maybeAppendBuildIdToRSCPayload(ctx, {
D: getInitialDraftMode(ctx.workStore),
c: prepareInitialCanonicalUrl(url),
q: getRenderedSearch(query),
m: undefined,
......
......@@ -419,6 +419,10 @@ export type PrefetchHints = {
export type ActionResult = Promise<any>
export type InitialRSCPayload = {
/**
* isDraftMode
*/
D: boolean
/** buildId, can be empty if the x-nextjs-build-id header is set */
b?: string
/** initialCanonicalUrlParts */
......
import { draftMode } from 'next/headers'
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const { isEnabled } = await draftMode()
return (
<p id="target-content">
{`${isEnabled ? 'Draft' : 'Published'} content: ${slug}`}
</p>
)
}
export default function Loading() {
return <p>Loading article...</p>
}
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export const runtime = 'edge'
export async function GET(request: Request) {
const draft = await draftMode()
draft.enable()
redirect(new URL(request.url).searchParams.has('error') ? '/error' : '/')
}
'use client'
export default function Page(): never {
throw new Error('Edge page render error')
}
'use client'
import { Links } from './links'
export default function GlobalError() {
return (
<html>
<body>
<h1>Edge global error</h1>
<Links />
</body>
</html>
)
}
import type { ReactNode } from 'react'
export const runtime = 'edge'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState, type ReactNode } from 'react'
function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
aria-label={`Show ${href}`}
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<span>{children} (link is hidden)</span>
)}
</>
)
}
export function Links() {
return (
<nav>
<LinkAccordion href="/article/auto">Automatic prefetch</LinkAccordion>
<LinkAccordion href="/article/full" prefetch={true}>
Full prefetch
</LinkAccordion>
</nav>
)
}
import { draftMode } from 'next/headers'
import { Links } from './links'
export default async function Page() {
const { isEnabled } = await draftMode()
return (
<>
<h1>Edge page</h1>
<p id="draft-mode">
{`Draft mode: ${isEnabled ? 'enabled' : 'disabled'}`}
</p>
<Links />
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
// @force-gate prefetching
describe('draft-mode-prefetch-edge', () => {
const { next } = nextTestSetup({
files: __dirname,
})
let browserForCleanup: Awaited<ReturnType<typeof next.browser>> | undefined
afterEach(async () => {
if (browserForCleanup !== undefined) {
await browserForCleanup.deleteCookies()
browserForCleanup = undefined
}
})
async function startBrowser(url: string) {
let act: ReturnType<typeof createRouterAct> | undefined
const browser = await next.browser(url, {
beforePageLoad(page) {
act = createRouterAct(page, { includeAppShellRequests: true })
},
})
browserForCleanup = browser
if (act === undefined) {
throw new Error('Router act was not initialized')
}
await browser.eval('window.__testDocument = "retained"')
return { browser, act }
}
describe.each([
{
name: 'initial document',
pathname: '/',
enablePathname: '/draft',
heading: 'Edge page',
},
{
name: 'initial error document',
pathname: '/error',
enablePathname: '/draft?error',
heading: 'Edge global error',
},
])('$name', ({ pathname, enablePathname, heading }) => {
it('prefetches automatic and full Links when draft mode is disabled', async () => {
const { browser, act } = await startBrowser(pathname)
expect(await browser.elementByCss('h1').text()).toBe(heading)
if (pathname === '/') {
expect(await browser.elementById('draft-mode').text()).toBe(
'Draft mode: disabled'
)
}
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/article/auto"]')
.click()
})
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/article/full"]')
.click()
},
{ includes: 'Published content: full' }
)
})
it('suppresses draft-mode prefetches and hover without preventing SPA navigation', async () => {
const { browser, act } = await startBrowser(enablePathname)
expect(new URL(await browser.url()).pathname).toBe(pathname)
expect(await browser.elementByCss('h1').text()).toBe(heading)
if (pathname === '/') {
expect(await browser.elementById('draft-mode').text()).toBe(
'Draft mode: enabled'
)
}
for (const target of ['auto', 'full']) {
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="/article/${target}"]`)
.click()
}, 'no-requests')
await act(async () => {
await browser.locator(`a[href="/article/${target}"]`).hover()
}, 'no-requests')
}
await act(
async () => {
await browser.elementByCss('a[href="/article/full"]').click()
},
{ includes: 'Draft content: full' }
)
expect(await browser.elementById('target-content').text()).toBe(
'Draft content: full'
)
expect(await browser.eval('window.__testDocument')).toBe('retained')
})
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: false,
partialPrefetching: false,
experimental: { cachedNavigations: false },
}
export default nextConfig
'use server'
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export async function enableDraftMode() {
const draft = await draftMode()
draft.enable()
}
export async function disableDraftMode() {
const draft = await draftMode()
draft.disable()
}
export async function enableDraftModeAndRedirect() {
const draft = await draftMode()
draft.enable()
redirect('/article/redirect')
}
export async function unrelatedAction() {
return 'Unrelated action done'
}
import { draftMode } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
async function Content({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const { isEnabled } = await draftMode()
return (
<>
<p id="target-content">
{`${isEnabled ? 'Draft' : 'Published'} content: ${slug}`}
</p>
<Suspense fallback={<p>Loading dynamic content...</p>}>
<DynamicContent />
</Suspense>
</>
)
}
async function DynamicContent() {
await connection()
return <p id="dynamic-content">Dynamic content</p>
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<Suspense fallback={<p>Loading target content...</p>}>
<Content params={params} />
</Suspense>
)
}
export default function Loading() {
return <p>Loading target...</p>
}
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import {
disableDraftMode,
enableDraftMode,
enableDraftModeAndRedirect,
unrelatedAction,
} from './actions'
import { LinkAccordion } from './link-accordion'
export function Controls() {
const router = useRouter()
const [actionResult, setActionResult] = useState<string | null>(null)
return (
<>
<form action={enableDraftMode}>
<button id="enable-draft-mode">Enable draft mode</button>
</form>
<form action={disableDraftMode}>
<button id="disable-draft-mode">Disable draft mode</button>
</form>
<button
id="disable-with-catch"
onClick={async () => {
try {
await disableDraftMode()
} catch {
setActionResult('Action response failed')
}
}}
>
Disable draft mode and catch errors
</button>
<form action={enableDraftModeAndRedirect}>
<button id="enable-and-redirect">Enable draft mode and redirect</button>
</form>
<button
id="unrelated-action"
onClick={async () => setActionResult(await unrelatedAction())}
>
Run unrelated action
</button>
<p id="action-result">{actionResult}</p>
<div>
<LinkAccordion href="/article/foreground" prefetch={false}>
Navigate without prefetching
</LinkAccordion>
</div>
<div>
<LinkAccordion href="/article/auto">Auto target</LinkAccordion>
</div>
<div>
<LinkAccordion href="/article/full" prefetch={true}>
Full target
</LinkAccordion>
</div>
<div>
<LinkAccordion href="/article/retained" prefetch={true}>
Retained target
</LinkAccordion>
</div>
<button
id="router-prefetch"
onClick={() => router.prefetch('/article/imperative')}
>
Prefetch imperative target
</button>
<fieldset>
<legend>Queued prefetches</legend>
{Array.from({ length: 9 }, (_, index) => (
<div key={index}>
<LinkAccordion href={`/article/queued-${index}`} prefetch={true}>
Queued target {index}
</LinkAccordion>
</div>
))}
</fieldset>
</>
)
}
import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation'
export async function GET() {
const draft = await draftMode()
draft.enable()
redirect('/')
}
import { draftMode } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
import { RetainedActionControls } from '../retained-actions'
async function Mode() {
await connection()
const { isEnabled } = await draftMode()
return (
<p id="forwarded-target-mode">
{isEnabled
? 'Forwarded target draft mode: enabled'
: 'Forwarded target draft mode: disabled'}
</p>
)
}
export default function Page() {
return (
<>
<h1>Forwarded target</h1>
<Suspense fallback={<p>Loading forwarded draft mode...</p>}>
<Mode />
</Suspense>
<RetainedActionControls />
</>
)
}
import type { ReactNode } from 'react'
import { RetainedActionsProvider } from './retained-actions'
export default function Layout({ children }: { children: ReactNode }) {
return <RetainedActionsProvider>{children}</RetainedActionsProvider>
}
'use client'
import {
createContext,
useContext,
useEffect,
useState,
type ReactNode,
} from 'react'
import { LinkAccordion } from '../link-accordion'
type RetainedActions = {
enable: () => Promise<void>
disable: () => Promise<void>
enableAndRedirect: () => Promise<void>
}
const RetainedActionsContext = createContext<{
actions: RetainedActions | null
setActions: (actions: RetainedActions) => void
} | null>(null)
export function RetainedActionsProvider({ children }: { children: ReactNode }) {
const [actions, setActions] = useState<RetainedActions | null>(null)
return (
<RetainedActionsContext.Provider value={{ actions, setActions }}>
{children}
</RetainedActionsContext.Provider>
)
}
export function RegisterActions({ actions }: { actions: RetainedActions }) {
const context = useContext(RetainedActionsContext)
if (context === null) {
throw new Error('RegisterActions requires RetainedActionsProvider')
}
const { setActions } = context
useEffect(() => {
// Keep the action references after the source page unmounts.
setActions(actions)
}, [actions, setActions])
return context.actions === null ? null : (
<p id="forwarded-actions-ready">Forwarded actions registered</p>
)
}
export function RetainedActionControls() {
const context = useContext(RetainedActionsContext)
if (context === null) {
throw new Error('RetainedActionControls requires RetainedActionsProvider')
}
const { actions } = context
if (actions === null) {
return <p>Visit the source page to register its actions.</p>
}
return (
<>
<div>
<LinkAccordion href="/article/forwarded-retained" prefetch={true}>
Forwarded retained target
</LinkAccordion>
</div>
<form action={actions.enable}>
<button id="forwarded-enable-draft-mode">Enable draft mode</button>
</form>
<form action={actions.disable}>
<button id="forwarded-disable-draft-mode">Disable draft mode</button>
</form>
<form action={actions.enableAndRedirect}>
<button id="forwarded-enable-and-redirect">
Enable draft mode and redirect
</button>
</form>
</>
)
}
'use server'
import { draftMode, headers } from 'next/headers'
import { redirect } from 'next/navigation'
export async function enableDraftMode() {
await assertForwarded()
const draft = await draftMode()
draft.enable()
}
export async function disableDraftMode() {
await assertForwarded()
const draft = await draftMode()
draft.disable()
}
export async function enableDraftModeAndRedirect() {
await assertForwarded()
const draft = await draftMode()
draft.enable()
redirect('/article/forwarded-redirect')
}
async function assertForwarded() {
if ((await headers()).get('x-action-forwarded') !== '1') {
throw new Error('Expected this action to run on the forwarded worker')
}
}
import { LinkAccordion } from '../../link-accordion'
import { RegisterActions } from '../retained-actions'
import {
disableDraftMode,
enableDraftMode,
enableDraftModeAndRedirect,
} from './actions'
export default function Page() {
return (
<>
<h1>Forwarded source</h1>
<RegisterActions
actions={{
enable: enableDraftMode,
disable: disableDraftMode,
enableAndRedirect: enableDraftModeAndRedirect,
}}
/>
<LinkAccordion href="/forwarded/action-target" prefetch={false}>
Forwarded target
</LinkAccordion>
</>
)
}
import { draftMode } from 'next/headers'
import { connection } from 'next/server'
import { Suspense, type ReactNode } from 'react'
import { Controls } from './controls'
async function Mode() {
await connection()
const { isEnabled } = await draftMode()
return (
<p id="draft-mode">
{isEnabled ? 'Draft mode: enabled' : 'Draft mode: disabled'}
</p>
)
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<Suspense fallback={<p>Loading draft mode...</p>}>
<Mode />
</Suspense>
<Controls />
{children}
</body>
</html>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState, type ReactNode } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
aria-label={`Show ${href}`}
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<span>{children} (link is hidden)</span>
)}
</>
)
}
export default function Page() {
return <h1>Draft mode prefetching</h1>
}
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