Unverified Commit 9bfaf63e authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Fix adapter outputs for not-found routes when used with cache components (#96390)

## Summary

Fix the build output for App Router `not-found` routes that get
partially prerendered when cacheComponents is enabled.

Previously, Next.js treated any statically generated `/_not-found` route
as a complete static 404, even when it contained postponed state. It
copied the partial HTML shell to `server/pages/404.html` and omitted the
corresponding `/_not-found` prerender from adapter outputs.

This change distinguishes fully static not-found routes from partially
prerendered ones. Fully static routes retain the existing `404.html`
behavior, while PPR routes remain resumable prerender outputs.

This allows a `not-found.tsx` that suspends under Cache Components to
render its dynamic content when deployed.

Closes https://github.com/vercel/next.js/pull/96399

## Testing

Expanded `not-found-non-document-dynamic` coverage to verify that:

- dynamic not-found content renders for ordinary missing paths
- dynamic not-found content renders when `/_not-found` is selected by a
rewrite
- a PPR not-found does not emit `server/pages/404.html`
- its adapter output includes `PARTIALLY_STATIC` metadata, postponed
state, and a resume chain

Also verified that fully static App Router not-found routes continue to
emit and serve `pages/404.html`.

- `__NEXT_CACHE_COMPONENTS=true pnpm test-start-turbo
test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts`
- `pnpm test-start-turbo test/e2e/app-dir/not-found/basic/index.test.ts`
parent be7048ef
......@@ -1387,12 +1387,6 @@ export async function handleBuildComplete({
const isAppPage =
Boolean(appOutputMap[srcRoute]) || srcRoute === '/_not-found'
// if we already have 404.html favor that instead of
// _not-found prerender
if (srcRoute === '/_not-found' && hasStatic404) {
continue
}
const isNotFoundTrue = prerenderManifest.notFoundRoutes.includes(route)
let allowQuery: string[] | undefined
......@@ -1458,6 +1452,13 @@ export async function handleBuildComplete({
const meta = await getAppRouteMeta(route, isAppPage)
// If we already have a complete 404.html, favor that instead of the
// _not-found prerender. A route with postponed state only produced a
// shell, so preserve its prerender output in order to resume it.
if (srcRoute === '/_not-found' && hasStatic404 && !meta.postponed) {
continue
}
let htmlAllowQuery = allowQuery
let dataAllowQuery = allowQuery
const dataInitialHeaders: Record<string, string> = {}
......
......@@ -2983,8 +2983,6 @@ export default async function build(
!hasPages500 && !hasNonStaticErrorPage && !customAppGetInitialProps
const combinedPages = [...staticPages, ...ssgPages]
const isApp404Static = staticPaths.has(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)
const hasStaticApp404 = hasApp404 && isApp404Static
const isAppGlobalErrorStatic = staticPaths.has(
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
)
......@@ -3960,7 +3958,14 @@ export default async function build(
})
}
// If there's /not-found inside app, we prefer it over the pages 404
// If there's a fully static /not-found inside app, we prefer it over
// the pages 404. A partially prerendered not-found is only a shell,
// so it must remain associated with its resumable prerender output.
const hasStaticApp404 =
hasApp404 &&
staticPaths.has(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY) &&
!pageInfos.get(UNDERSCORE_NOT_FOUND_ROUTE)?.hasPostponed
if (hasStaticApp404) {
await moveExportedAppNotFoundTo404()
} else {
......
......@@ -3,7 +3,7 @@ import { connection } from 'next/server'
async function Dynamic() {
await connection()
return null
return <p id="dynamic-layout">dynamic layout content</p>
}
export default function Root({ children }: { children: ReactNode }) {
......
import fs from 'fs/promises'
/** @type {import('next').NextAdapter} */
export default {
name: 'not-found-non-document-dynamic',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
......@@ -3,4 +3,8 @@
*/
const nextConfig = {}
if (!process.env.NEXT_ADAPTER_PATH) {
nextConfig.adapterPath = require.resolve('./my-adapter.mjs')
}
module.exports = nextConfig
import { isNextDeploy, nextTestSetup } from 'e2e-utils'
import { isNextDeploy, isNextStart, nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
describe('not-found-non-document-dynamic', () => {
const { next } = nextTestSetup({
......@@ -48,7 +49,9 @@ describe('not-found-non-document-dynamic', () => {
})
expect(res.status).toBe(404)
expect(res.headers.get('content-type')).toContain('text/html')
expect(await res.text()).toContain('custom not found page')
const html = await res.text()
expect(html).toContain('custom not found page')
expect(html).toContain('dynamic layout content')
})
it('renders the not-found page for fetch requests to unknown paths', async () => {
......@@ -61,6 +64,49 @@ describe('not-found-non-document-dynamic', () => {
})
expect(res.status).toBe(404)
expect(res.headers.get('content-type')).toContain('text/html')
expect(await res.text()).toContain('custom not found page')
const html = await res.text()
expect(html).toContain('custom not found page')
expect(html).toContain('dynamic layout content')
})
it('renders dynamic not-found content when selected by a rewrite', async () => {
const res = await next.fetch('/rewritten-not-found')
const html = await res.text()
expect(res.status).toBe(404)
expect(res.headers.get('content-type')).toContain('text/html')
expect(html).toContain('custom not found page')
expect(html).toContain('dynamic layout content')
})
if (isNextStart && process.env.__NEXT_CACHE_COMPONENTS) {
it('publishes the partial not-found shell as a resumable prerender', async () => {
expect(await next.hasFile('.next/server/pages/404.html')).toBe(false)
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const notFoundPrerender = outputs.prerenders.find(
(output) => output.pathname === '/_not-found'
)
expect(notFoundPrerender).toMatchObject({
route: '/_not-found',
routeType: 'page',
response: 'initial',
compute: 'resuming',
pprChain: {
headers: {
'next-resume': '1',
},
},
config: {
renderingMode: 'PARTIALLY_STATIC',
},
fallback: {
postponedState: expect.any(String),
initialStatus: 404,
},
})
})
}
})
import { NextRequest, NextResponse } from 'next/server'
export function proxy(request: NextRequest) {
if (request.nextUrl.pathname === '/rewritten-not-found') {
return NextResponse.rewrite(new URL('/_not-found', request.url), {
status: 404,
})
}
}
......@@ -228,6 +228,17 @@ describe('adapter-prerender-metadata', () => {
expect(staticPage.htmlSize).toBeGreaterThan(0)
})
it('uses 404.html for a fully static not-found', async () => {
const prerenders = await getPrerenders()
expect(
prerenders.find((output) => output.pathname === '/_not-found')
).toBeUndefined()
expect(await next.readFile('.next/server/pages/404.html')).toContain(
'Not Found'
)
})
it('classifies an upgradable app template as fallback', async () => {
const prerenders = await getPrerenders()
const template = prerenders.find(
......
export default function NotFound() {
return <p>Not Found</p>
}
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