Unverified Commit 851b6cb0 authored by Josh Story's avatar Josh Story Committed by GitHub

Preserve closed-route admission across cache misses (#98964)

## Summary

Keep route admission independent of ISR cache contents. With Cache
Components disabled, a route using `dynamicParams = false` and
`generateStaticParams()` can currently return 200 for a build-generated
URL, then incorrectly return 404 after `revalidatePath` expires its
cache entry. An empty external cache causes the same failure on the
first request.

For example, if the build generated `/products/known`, that URL remains
allowed after invalidation; `/products/unlisted` remains disallowed
regardless of cache state. If a later build removes `/products/known`,
it must immediately stop matching, even if an external cache still holds
that URL's old response.

The request handler now rejects unlisted closed URLs before looking up
their ISR entries. This prevents both serving an old cache hit and
generating a new response for a URL the current build does not admit. An
admitted build path whose matched fallback is `false` regenerates using
a blocking render when necessary.

The two decisions stay separate: the manifest determines whether the URL
may match, while the response generator chooses how to produce an
admitted response. We do not share mutable fallback-mode state between
those stages.

### Preserved exceptions and adapter behavior

- **Server Actions:** forwarding can invoke a worker at
`/products/[slug]`, not a concrete page URL. Action calls retain their
existing exemption from page admission checks. A retained action must
still work after the user navigates away from its closed route.
- **Draft mode:** an unpublished URL can be previewed without admitting
it publicly or replacing its public cache entry.
- **Minimal mode:** the platform router remains responsible for
admission before invoking the renderer.
- **Adapters:** rendering a routing 404 now happens outside the response
cache. The previous placement could successfully send a 404 and then
throw `cache entry required but not generated` because it returned no
cache entry for a non-null cache key. The new adapter fixture reproduces
this on the parent runtime.

This uses the existing prerender manifest and does not change its format
or the adapter contract. The most specific matched dynamic route
continues to determine the policy for open URLs, so specialized matchers
can admit an open suffix without admitting an unknown closed prefix.

## Regression coverage

Real fixtures cover:

- Repeated invalidation, ordinary and optional catch-all paths,
time-based ISR, concurrent regeneration, and serving a stale response
while regenerating in the background.
- Empty external caches and an external cache retained across two real
builds. The latter verifies that the removed path's old entry still
exists but is never consulted.
- Document, HEAD, navigation, prefetch, bot, rewritten, and
overlapping-route requests.
- Direct and forwarded Server Actions, draft previews, and direct
minimal-mode renderer invocations.
- Adapter-specific 404 handling and regeneration of admitted paths.
- The distinction between routing rejection and content that calls
`notFound()`: an admitted URL can transition from 200 to 404 and back,
including when its build render returned 404.

These legacy `dynamicParams` fixtures are excluded from the Cache
Components matrix because that configuration does not support the API.

## Stack

This is an unflagged correctness fix, placed after #98950 and before the
parameter-matching API in #97393. It can land without committing to that
API. The API's mixed-prefix and dynamic-tail lifecycle coverage belongs
in the API layer.

## Verification

- Before the original fix, the two initial regression fixtures failed 11
checks while the open-route and time-based controls passed.
- Against the parent runtime, the new adapter fixture reproduces the
cache-entry invariant on document, navigation, prefetch, and bot
requests, plus the invalidation regression.
- The retained Server Action regression passes on the parent runtime,
fails on the earlier PR revision without the exemption, and passes with
the explicit action exemption. It also passes in development with the
exemption.
- Local production runs before replaying the follow-up onto the rebased
stack: all 49 tests across seven suites pass in both Webpack and
fresh-native Turbopack, including the existing closed-parameter
navigation suite. The follow-up patch applied unchanged; CI will verify
the rebased head.
- Development Turbopack request-mode coverage: 10 passed; the
public-cache reuse assertion is production-only.
- Repository TypeScript, Next.js declaration generation, changed-file
formatting/ESLint, and `git diff --check` pass.

No live deployment verification. A separate `revalidate-if-generated`
hang with an always-empty custom cache reproduces on both this PR and
its parent; its diagnostic is retained for a separate follow-up, not
included or silently skipped here.

<!-- NEXT_JS_LLM -->
parent 82dd6d6d
......@@ -733,6 +733,7 @@ export function createAppPageEntrypoint({
if (routerServerContext?.render404) {
await routerServerContext.render404(req, res, parsedUrl, false)
} else {
res.statusCode = 404
res.end('This page could not be found')
}
return null
......@@ -1129,6 +1130,13 @@ export function createAppPageEntrypoint({
fallbackMode = parseFallbackField(prerenderInfo.fallback)
}
// A closed matcher rejects new paths, not regeneration of paths that
// were produced by the build. Their cache entries can be invalidated
// or evicted without removing the path from the build manifest.
if (fallbackMode === FallbackMode.NOT_FOUND && isPrerendered) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER
}
if (
nextConfig.partialPrefetching &&
prerenderInfo?.fallback === null &&
......@@ -1160,14 +1168,9 @@ export function createAppPageEntrypoint({
isOnDemandRevalidate = true
}
// TODO: adapt for PPR
// only allow on-demand revalidate for fallback: true/blocking
// or for prerendered fallback: false paths
if (
isOnDemandRevalidate &&
(fallbackMode !== FallbackMode.NOT_FOUND ||
previousIncrementalCacheEntry)
) {
// On-demand revalidation blocks for admitted paths. Cache contents
// must not make an otherwise closed path eligible for generation.
if (isOnDemandRevalidate && fallbackMode !== FallbackMode.NOT_FOUND) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER
}
......@@ -1180,21 +1183,6 @@ export function createAppPageEntrypoint({
pageIsDynamic &&
(isProduction || !isPrerendered)
) {
// if the page has dynamicParams: false and this pathname wasn't
// prerendered trigger the no fallback handling
if (
// In development, fall through to render to handle missing
// getStaticPaths.
(isProduction || prerenderInfo) &&
// When fallback isn't present, abort this render so we 404
fallbackMode === FallbackMode.NOT_FOUND
) {
if (nextConfig.adapterPath) {
return await render404()
}
throw new NoFallbackError()
}
// When cacheComponents is enabled, we can use the fallback
// response if the request is not a dynamic RSC request because the
// RSC data when this feature flag is enabled does not contain any
......@@ -1637,6 +1625,26 @@ export function createAppPageEntrypoint({
}
const handleResponse = async (span?: Span): Promise<null | void> => {
// Decide whether this URL is allowed before consulting ISR. An exact
// build path remains valid even when its cached result is missing, and
// the most specific matched route controls whether other paths may be
// generated. Neither a cache hit nor revalidation changes that decision.
// Server Actions may be forwarded to a worker's route pattern rather
// than a concrete URL. That invokes the action, not a page navigation.
if (
!isMinimalMode &&
!isDraftMode &&
!isPossibleServerAction &&
pageIsDynamic &&
prerenderInfo?.fallback === false &&
!isPrerendered
) {
if (nextConfig.adapterPath) {
return await render404()
}
throw new NoFallbackError()
}
const cacheEntry = await routeModule.handleResponse({
cacheKey: ssgCacheKey,
responseGenerator: (c) =>
......
......@@ -163,6 +163,7 @@
"test/e2e/app-dir/dynamic-in-generate-params/index.test.ts",
"test/e2e/app-dir/dynamic-import-tree-shaking/dynamic-import-tree-shaking.test.ts",
"test/e2e/app-dir/dynamic-interception-route-revalidate/dynamic-interception-route-revalidate.test.ts",
"test/e2e/app-dir/dynamic-params-request-modes/dynamic-params-request-modes.test.ts",
"test/e2e/app-dir/cache-components-*/**/*",
"test/e2e/app-dir/cache-components/**/*",
"test/e2e/app-dir/dynamic-requests/dynamic-requests.test.ts",
......@@ -355,6 +356,11 @@
"test/production/app-dir/build-output/index.test.ts",
"test/production/app-dir/client-components-tree-shaking/index.test.ts",
"test/production/app-dir/deopted-into-client-rendering-warning/deopted-into-client-rendering-warning.test.ts",
"test/production/app-dir/dynamic-params-adapter/dynamic-params-adapter.test.ts",
"test/production/app-dir/dynamic-params-cache-miss/dynamic-params-cache-miss.test.ts",
"test/production/app-dir/dynamic-params-minimal-mode/dynamic-params-minimal-mode.test.ts",
"test/production/app-dir/dynamic-params-retained-cache/dynamic-params-retained-cache.test.ts",
"test/production/app-dir/dynamic-params-revalidation/dynamic-params-revalidation.test.ts",
"test/production/app-dir/global-default-cache-handler/global-default-cache-handler.test.ts",
"test/production/app-dir/graceful-degrade/graceful-degrade-non-bot.test.ts",
"test/production/app-dir/graceful-degrade/graceful-degrade.test.ts",
......
import { draftMode } from 'next/headers'
export async function GET() {
;(await draftMode()).enable()
return new Response(null, { status: 204 })
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default async function Page({
params,
}: {
params: Promise<{ rest: string[] }>
}) {
const { rest } = await params
return <p id="catch-all">{rest.join('/')}</p>
}
export const dynamicParams = false
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default function Page() {
return <p id="specific">Specific route</p>
}
import { RetainedActionButton } from './retained-action-button'
export default function Page() {
return (
<main id="home">
Home
<RetainedActionButton />
</main>
)
}
'use server'
import { revalidatePath } from 'next/cache'
export async function refreshProduct() {
revalidatePath('/products/known')
return 'action completed'
}
'use client'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { refreshProduct } from './actions'
export function ActionButton() {
const [ready, setReady] = useState(false)
const [result, setResult] = useState('not called')
useEffect(() => {
// Keep the reference after navigating to a page that does not import it.
// The next invocation must be forwarded to this action's route worker.
window.retainedClosedAction = refreshProduct
setReady(true)
}, [])
return (
<>
<p id="action-ready">{ready ? 'ready' : 'loading'}</p>
<button
id="call-action"
onClick={async () => {
try {
setResult(await refreshProduct())
} catch (error) {
setResult(`error: ${String(error)}`)
}
}}
>
Refresh product
</button>
<p id="action-result">{result}</p>
<Link id="navigate-home" href="/" prefetch={false}>
Home
</Link>
</>
)
}
import { randomUUID } from 'node:crypto'
import { draftMode } from 'next/headers'
import { ActionButton } from './button'
export const dynamicParams = false
export const revalidate = 3600
export function generateStaticParams() {
return [{ slug: 'known' }, { slug: 'forwarded' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const { isEnabled } = await draftMode()
return (
<main id="product">
<p id="slug">{slug}</p>
<p id="draft">{isEnabled ? 'draft' : 'published'}</p>
<p id="generation">{randomUUID()}</p>
<ActionButton />
</main>
)
}
'use client'
import { useState } from 'react'
declare global {
interface Window {
retainedClosedAction?: () => Promise<string>
}
}
export function RetainedActionButton() {
const [result, setResult] = useState('not called')
return (
<>
<button
id="call-retained-action"
onClick={async () => {
try {
setResult(await window.retainedClosedAction!())
} catch (error) {
setResult(`error: ${String(error)}`)
}
}}
>
Call retained action
</button>
<p id="action-result">{result}</p>
</>
)
}
import { load } from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('dynamicParams: false request modes', () => {
const { next } = nextTestSetup({ files: __dirname })
it.each(['document', 'head', 'navigation', 'prefetch', 'bot'])(
'admits only generated paths for a %s request',
async (kind) => {
const headers: Record<string, string> = {}
if (kind === 'navigation' || kind === 'prefetch') headers.RSC = '1'
if (kind === 'prefetch') headers['Next-Router-Prefetch'] = '1'
if (kind === 'bot') headers['user-agent'] = 'Googlebot'
const options = { headers, method: kind === 'head' ? 'HEAD' : 'GET' }
const known = await next.fetch('/products/known', options)
expect(known.status).toBe(200)
const unlisted = await next.fetch('/products/unlisted', options)
expect(unlisted.status).toBe(404)
if (kind === 'head') {
expect(await known.text()).toBe('')
expect(await unlisted.text()).toBe('')
}
}
)
it('checks the rewritten destination against the generated paths', async () => {
const known = await next.fetch('/alias/known')
expect(known.status).toBe(200)
expect(load(await known.text())('#slug').text()).toBe('known')
expect((await next.fetch('/alias/unlisted')).status).toBe(404)
})
it('can try a less specific route after rejecting a closed matcher', async () => {
const known = await next.fetch('/overlap/known')
expect(known.status).toBe(200)
expect(load(await known.text())('#specific').text()).toBe('Specific route')
const unlisted = await next.fetch('/overlap/unlisted')
expect(unlisted.status).toBe(200)
expect(load(await unlisted.text())('#catch-all').text()).toBe('unlisted')
})
async function enableDraftMode() {
const response = await next.fetch('/draft')
expect(response.status).toBe(204)
const cookie = response.headers.get('set-cookie')!.split(';')[0]
expect(cookie).toMatch(/^__prerender_bypass=/)
return cookie
}
// Existing adapter routing requires legacy preview cookies and rejects App
// Router draft requests to unlisted closed URLs before Next.js handles them.
// @force-gate !deploy
it('previews an unlisted path without admitting it for ordinary requests', async () => {
expect((await next.fetch('/products/unpublished')).status).toBe(404)
const cookie = await enableDraftMode()
const draft = await next.fetch('/products/unpublished', {
headers: { cookie },
})
expect(draft.status).toBe(200)
expect(draft.headers.get('cache-control')).toContain('no-store')
const $ = load(await draft.text())
expect($('#slug').text()).toBe('unpublished')
expect($('#draft').text()).toBe('draft')
expect((await next.fetch('/products/unpublished')).status).toBe(404)
})
// Dev deliberately does not reuse the Full Route Cache.
// @force-gate prod
it('does not read or replace the public cache when previewing a known path', async () => {
const before = await next.render$('/products/known')
const generation = before('#generation').text()
expect(generation).not.toBe('')
const cookie = await enableDraftMode()
const draft = await next.fetch('/products/known', { headers: { cookie } })
expect(draft.status).toBe(200)
const $ = load(await draft.text())
expect($('#draft').text()).toBe('draft')
expect($('#generation').text()).not.toBe(generation)
const after = await next.render$('/products/known')
expect(after('#generation').text()).toBe(generation)
expect(after('#draft').text()).toBe('published')
})
it('runs a Server Action and revalidates the currently rendered closed path', async () => {
const browser = await next.browser('/products/known')
const generation = await browser.elementById('generation').text()
await browser.elementById('call-action').click()
await retry(async () => {
expect(await browser.elementById('action-result').text()).toBe(
'action completed'
)
expect(await browser.elementById('generation').text()).not.toBe(
generation
)
})
expect(await browser.elementById('slug').text()).toBe('known')
})
it('forwards a retained Server Action to its closed route after navigating away', async () => {
const browser = await next.browser('/products/forwarded')
await retry(async () => {
expect(await browser.elementById('action-ready').text()).toBe('ready')
})
await browser.elementById('navigate-home').click()
await browser.waitForElementByCss('#home')
await browser.elementById('call-retained-action').click()
await retry(async () => {
expect(await browser.elementById('action-result').text()).toBe(
'action completed'
)
})
expect(await browser.hasElementByCssSelector('#home')).toBe(true)
expect(await browser.hasElementByCssSelector('#product')).toBe(false)
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: false,
async rewrites() {
return [{ source: '/alias/:slug', destination: '/products/:slug' }]
},
}
export default nextConfig
export default { name: 'closed-route-test-adapter' }
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function NotFound() {
return <p id="not-found">Product not found</p>
}
export default function Page() {
return <p>Adapter route admission</p>
}
import { randomUUID } from 'node:crypto'
export const dynamicParams = false
export const revalidate = 3600
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
console.log('product render', slug)
return (
<main>
<p id="slug">{slug}</p>
<p id="generation">{randomUUID()}</p>
</main>
)
}
import { revalidatePath } from 'next/cache'
export async function POST() {
revalidatePath('/products/known')
return Response.json({ revalidated: true })
}
import { load } from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
} from 'next-test-utils'
import { join } from 'node:path'
describe('dynamicParams: false with adapterPath', () => {
const { next } = nextTestSetup({ files: __dirname })
it.each(['document', 'head', 'navigation', 'prefetch', 'bot'])(
'renders the adapter 404 for an unlisted %s request',
async (kind) => {
const headers: Record<string, string> = {}
if (kind === 'navigation' || kind === 'prefetch') headers.RSC = '1'
if (kind === 'prefetch') headers['Next-Router-Prefetch'] = '1'
if (kind === 'bot') headers['user-agent'] = 'Googlebot'
const options = { headers, method: kind === 'head' ? 'HEAD' : 'GET' }
expect((await next.fetch('/products/known', options)).status).toBe(200)
const outputStart = next.cliOutput.length
const response = await next.fetch('/products/unlisted', options)
expect(response.status).toBe(404)
const body = await response.text()
if (kind === 'head') {
expect(body).toBe('')
} else {
expect(body).toContain('Product not found')
if (!headers.RSC) {
expect(load(body)('#not-found').text()).toBe('Product not found')
}
}
const output = next.cliOutput.slice(outputStart)
expect(output).not.toContain('product render unlisted')
expect(output).not.toContain('cache entry required but not generated')
expect(output).not.toContain('ERR_HTTP_HEADERS_SENT')
expect(output).not.toContain('NoFallbackError')
}
)
it.each(['GET', 'HEAD'])(
'returns a 404 for an unlisted %s request without an adapter 404 renderer',
async (method) => {
const port = await findPort()
const server = await initNextServerScript(
join(next.testDir, 'server.cjs'),
/Adapter ready/,
{
...process.env,
NODE_ENV: 'production',
PORT: String(port),
TURBOPACK: process.env.IS_TURBOPACK_TEST ? '1' : '',
},
undefined,
{ cwd: next.testDir, shouldRejectOnError: true }
)
try {
const known = await fetchViaHTTP(port, '/products/known', undefined, {
method,
})
expect(known.status).toBe(200)
const response = await fetchViaHTTP(
port,
'/products/unlisted',
undefined,
{ method }
)
expect(response.status).toBe(404)
expect(await response.text()).toBe(
method === 'HEAD' ? '' : 'This page could not be found'
)
} finally {
await killApp(server)
}
}
)
it('regenerates an admitted path after invalidation', async () => {
const before = await next.render$('/products/known')
const generation = before('#generation').text()
expect(generation).not.toBe('')
expect((await next.fetch('/revalidate', { method: 'POST' })).status).toBe(
200
)
const response = await next.fetch('/products/known')
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#slug').text()).toBe('known')
expect($('#generation').text()).not.toBe(generation)
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: false,
adapterPath: require.resolve('./adapter.mjs'),
}
export default nextConfig
require('next/dist/build/adapter/setup-node-env.external')
const { createServer } = require('node:http')
const { handler } = require('./.next/server/app/products/[slug]/page.js')
// Invoke the built adapter entrypoint directly. Starting Next's router server
// would supply render404 and hide the handler's callback-less response path.
createServer((req, res) => {
handler(req, res, {}).catch((error) => {
console.error(error)
res.statusCode = 500
res.end('Handler failed')
})
}).listen(Number(process.env.PORT), () => {
console.log('Adapter ready')
})
export const dynamicParams = false
export const revalidate = 3600
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
console.log('closed page render', slug)
return <p id="slug">{slug}</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
// Model an empty external cache through the public cache-handler interface.
module.exports = class CacheHandler {
async get(key) {
console.log('cache lookup', key)
return null
}
async set() {}
async revalidateTag() {}
resetRequestCache() {}
}
import { load } from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
describe('dynamicParams: false with an empty cache', () => {
const { next } = nextTestSetup({ files: __dirname })
it('renders a build-generated path on every cache miss', async () => {
const outputStart = next.cliOutput.length
for (let i = 0; i < 2; i++) {
const response = await next.fetch('/closed/known')
expect(response.status).toBe(200)
expect(load(await response.text())('#slug').text()).toBe('known')
}
expect(next.cliOutput.slice(outputStart)).toContain(
'cache lookup /closed/known'
)
})
it('allows authenticated revalidation of an admitted path with no cache entry', async () => {
const { previewModeId } = JSON.parse(
await next.readFile('.next/server/preview-props.json')
)
const headers = { 'x-prerender-revalidate': previewModeId }
const known = await next.fetch('/closed/known', { headers })
expect(known.status).toBe(200)
expect(load(await known.text())('#slug').text()).toBe('known')
expect((await next.fetch('/closed/unlisted', { headers })).status).toBe(404)
})
it.each(['document', 'navigation', 'bot'])(
'rejects an unlisted %s request before a cache lookup or render',
async (kind) => {
const headers: Record<string, string> = {}
if (kind === 'navigation') headers.RSC = '1'
if (kind === 'bot') headers['user-agent'] = 'Googlebot'
const outputStart = next.cliOutput.length
const response = await next.fetch('/closed/unlisted', { headers })
expect(response.status).toBe(404)
await response.text()
const output = next.cliOutput.slice(outputStart)
expect(output).not.toContain('cache lookup /closed/unlisted')
expect(output).not.toContain('closed page render unlisted')
expect(output).not.toContain('NoFallbackError')
}
)
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: false,
cacheHandler: require.resolve('./cache-handler.js'),
cacheMaxMemorySize: 0,
}
export default nextConfig
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>Platform-selected renderer</p>
}
export const dynamicParams = false
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return <p id="slug">{slug}</p>
}
import { load } from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
describe('dynamicParams: false in minimal mode', () => {
const { next } = nextTestSetup({
files: __dirname,
// This fixture invokes the renderer directly, bypassing a deployment's
// public router. Public requests to these unlisted URLs must still 404.
skipDeployment: true,
env: {
NEXT_PRIVATE_TEST_HEADERS: '1',
NEXT_PRIVATE_MINIMAL_MODE: '1',
},
})
// These are direct invocations of a platform-selected renderer. The external
// router is responsible for deciding which public URLs may reach it.
it.each(['known', 'unlisted'])(
'renders a platform-selected document for %s',
async (slug) => {
const response = await next.fetch(`/products/${slug}`, {
headers: { 'x-matched-path': '/products/[slug]' },
})
expect(response.status).toBe(200)
expect(load(await response.text())('#slug').text()).toBe(slug)
}
)
it('renders a platform-selected RSC request', async () => {
const response = await next.fetch('/products/unlisted-rsc', {
headers: { 'x-matched-path': '/products/[slug]', RSC: '1' },
})
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/x-component')
expect(await response.text()).toContain('unlisted-rsc')
})
it('leaves revalidate-if-generated admission to the platform cache', async () => {
const { previewModeId } = JSON.parse(
await next.readFile('.next/server/preview-props.json')
)
const response = await next.fetch('/products/platform-revalidation', {
headers: {
'x-matched-path': '/products/[slug]',
'x-prerender-revalidate': previewModeId,
'x-prerender-revalidate-if-generated': '1',
},
})
expect(response.status).toBe(200)
expect(load(await response.text())('#slug').text()).toBe(
'platform-revalidation'
)
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = { cacheComponents: false }
export default nextConfig
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>Cache retained across builds</p>
}
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
export const dynamicParams = false
export const revalidate = 3600
export async function generateStaticParams() {
const slugs: string[] = JSON.parse(
await readFile(join(process.cwd(), 'slugs.json'), 'utf8')
)
return slugs.map((slug) => ({ slug }))
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
console.log('product render', slug)
return <p id="slug">{slug}</p>
}
const { mkdir, readFile, writeFile } = require('node:fs/promises')
const { join } = require('node:path')
const { serialize, deserialize } = require('node:v8')
// Model an external ISR cache that survives replacement of the build output.
const cacheDirectory = join(process.cwd(), 'external-cache')
module.exports = class CacheHandler {
async get(key) {
console.log('cache lookup', key)
try {
return deserialize(
await readFile(join(cacheDirectory, encodeURIComponent(key)))
)
} catch (error) {
if (error.code === 'ENOENT') return null
throw error
}
}
async set(key, value) {
await mkdir(cacheDirectory, { recursive: true })
await writeFile(
join(cacheDirectory, encodeURIComponent(key)),
serialize({ value, lastModified: Date.now() })
)
}
async revalidateTag() {}
resetRequestCache() {}
}
import { load } from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { deserialize } from 'node:v8'
describe('dynamicParams: false with a cache retained across builds', () => {
const { next } = nextTestSetup({ files: __dirname, skipStart: true })
it('rejects a removed build path even when its old cache entry still exists', async () => {
const original = await next.readFile('slugs.json')
const cacheFile = join(
next.testDir,
'external-cache',
encodeURIComponent('/products/removed')
)
try {
await next.start()
expect((await next.fetch('/products/removed')).status).toBe(200)
const cached = await next.fetch('/products/removed')
expect(cached.status).toBe(200)
expect(cached.headers.get('x-nextjs-cache')).toBe('HIT')
expect(load(await cached.text())('#slug').text()).toBe('removed')
// Keep the real entry written by Next, outside the build output directory.
const previousEntry = await readFile(cacheFile)
expect(deserialize(previousEntry).value.html).toContain('removed')
await next.stop()
await next.patchFile('slugs.json', JSON.stringify(['known']))
await next.start()
const manifest = await next.readJSON('.next/prerender-manifest.json')
expect(manifest.routes['/products/known']).toBeDefined()
expect(manifest.routes['/products/removed']).toBeUndefined()
expect(await readFile(cacheFile)).toEqual(previousEntry)
const outputStart = next.cliOutput.length
for (const headers of [{}, { RSC: '1' }]) {
const response = await next.fetch('/products/removed', { headers })
expect(response.status).toBe(404)
await response.text()
}
const output = next.cliOutput.slice(outputStart)
expect(output).not.toContain('cache lookup /products/removed')
expect(output).not.toContain('product render removed')
expect(await readFile(cacheFile)).toEqual(previousEntry)
expect((await next.fetch('/products/known')).status).toBe(200)
} finally {
await next.stop()
await next.patchFile('slugs.json', original)
}
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: false,
cacheHandler: require.resolve('./cache-handler.js'),
cacheMaxMemorySize: 0,
}
export default nextConfig
import { randomUUID } from 'node:crypto'
export const dynamicParams = false
export const revalidate = 3600
export function generateStaticParams() {
return [{ slug: ['known', 'nested'] }]
}
export default function Page() {
console.log('closed page render')
return <p id="generation">{randomUUID()}</p>
}
import { randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { notFound } from 'next/navigation'
export const dynamicParams = false
export const revalidate = 3600
export function generateStaticParams() {
return [
{ slug: 'known' },
{ slug: 'concurrent' },
{ slug: 'mutable' },
{ slug: 'initially-missing' },
]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
console.log('closed page render', slug)
// A small file-backed data source lets content change without rebuilding.
const content = JSON.parse(
await readFile(join(process.cwd(), 'content.json'), 'utf8')
)
if (content[slug] === null) notFound()
return <p id="generation">{randomUUID()}</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { randomUUID } from 'node:crypto'
export const revalidate = 3600
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default function Page() {
return <p id="generation">{randomUUID()}</p>
}
import { randomUUID } from 'node:crypto'
export const dynamicParams = false
export const revalidate = 3600
export function generateStaticParams() {
return [{ slug: [] }, { slug: ['known'] }]
}
export default function Page() {
console.log('closed page render')
return <p id="generation">{randomUUID()}</p>
}
export default function Page() {
return <p>hello world</p>
}
import { revalidatePath } from 'next/cache'
export async function POST(request: Request) {
const { pathname } = await request.json()
revalidatePath(pathname)
return Response.json({ revalidated: true })
}
import { randomUUID } from 'node:crypto'
export const dynamicParams = false
export const revalidate = 1
export function generateStaticParams() {
return [{ slug: 'known' }, { slug: 'stale' }]
}
export default function Page() {
return <p id="generation">{randomUUID()}</p>
}
{ "mutable": "available", "initially-missing": null }
import { load } from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('dynamicParams: false revalidation', () => {
const { next } = nextTestSetup({ files: __dirname })
async function readPage(pathname: string) {
const response = await next.fetch(pathname)
const $ = load(await response.text())
return { status: response.status, generation: $('#generation').text() }
}
async function revalidate(pathname: string) {
const response = await next.fetch('/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname }),
})
expect(response.status).toBe(200)
}
it.each([
'/closed/known',
'/catch-all/known/nested',
'/optional',
'/optional/known',
'/open/known',
'/open/generated-at-runtime',
])('regenerates %s after repeated invalidation', async (pathname) => {
let previous = await readPage(pathname)
expect(previous.status).toBe(200)
expect(previous.generation).not.toBe('')
expect(await readPage(pathname)).toEqual(previous)
for (let i = 0; i < 2; i++) {
await revalidate(pathname)
const current = await readPage(pathname)
expect(current.status).toBe(200)
expect(current.generation).not.toBe('')
expect(current.generation).not.toBe(previous.generation)
expect(await readPage(pathname)).toEqual(current)
previous = current
}
})
it('preserves time-based regeneration of a closed route', async () => {
const before = await readPage('/timed/known')
expect(before.status).toBe(200)
expect(before.generation).not.toBe('')
await retry(async () => {
const after = await readPage('/timed/known')
expect(after.status).toBe(200)
expect(after.generation).not.toBe('')
expect(after.generation).not.toBe(before.generation)
})
})
it('shares regeneration across concurrent requests after invalidation', async () => {
const before = await readPage('/closed/concurrent')
expect(before.status).toBe(200)
await revalidate('/closed/concurrent')
const responses = await Promise.all(
Array.from({ length: 5 }, () => readPage('/closed/concurrent'))
)
for (const response of responses) {
expect(response.status).toBe(200)
expect(response.generation).not.toBe('')
expect(response.generation).not.toBe(before.generation)
expect(response).toEqual(responses[0])
}
expect(await readPage('/closed/concurrent')).toEqual(responses[0])
})
it('serves a stale response while regenerating without changing that response to a 404', async () => {
const outputStart = next.cliOutput.length
await revalidate('/timed/stale')
const before = await readPage('/timed/stale')
expect(before.status).toBe(200)
expect(before.generation).not.toBe('')
// A stale cache hit resolves the request before the background generator
// finishes. Admission checks must not turn that regeneration into a 404.
await retry(async () => {
const response = await next.fetch('/timed/stale')
expect(response.status).toBe(200)
const $ = load(await response.text())
expect(response.headers.get('x-nextjs-cache')).toBe('STALE')
expect($('#generation').text()).toBe(before.generation)
})
await retry(async () => {
const after = await readPage('/timed/stale')
expect(after.status).toBe(200)
expect(after.generation).not.toBe('')
expect(after.generation).not.toBe(before.generation)
})
const output = next.cliOutput.slice(outputStart)
expect(output).not.toContain('NoFallbackError')
expect(output).not.toContain('ERR_HTTP_HEADERS_SENT')
})
it('allows content to disappear and return at an admitted URL', async () => {
const original = await next.readFile('content.json')
try {
expect((await readPage('/closed/mutable')).status).toBe(200)
await next.patchFile('content.json', JSON.stringify({ mutable: null }))
await revalidate('/closed/mutable')
expect((await readPage('/closed/mutable')).status).toBe(404)
await next.patchFile('content.json', original)
await revalidate('/closed/mutable')
expect((await readPage('/closed/mutable')).status).toBe(200)
} finally {
await next.patchFile('content.json', original)
}
})
it('can regenerate an admitted URL that rendered notFound during the build', async () => {
const original = await next.readFile('content.json')
try {
expect((await readPage('/closed/initially-missing')).status).toBe(404)
// Omit the key: only an explicit null means the content is unavailable.
await next.patchFile(
'content.json',
JSON.stringify({ mutable: 'available' })
)
await revalidate('/closed/initially-missing')
expect((await readPage('/closed/initially-missing')).status).toBe(200)
} finally {
await next.patchFile('content.json', original)
}
})
it.each([
'/closed/unlisted',
'/catch-all/unlisted/nested',
'/optional/unlisted',
])('does not admit %s after invalidation', async (pathname) => {
const outputStart = next.cliOutput.length
expect((await readPage(pathname)).status).toBe(404)
await revalidate(pathname)
expect((await readPage(pathname)).status).toBe(404)
expect(next.cliOutput.slice(outputStart)).not.toContain(
'closed page render'
)
expect(next.cliOutput.slice(outputStart)).not.toContain('NoFallbackError')
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = { cacheComponents: false }
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