Unverified Commit 8d6c076d authored by Josh Story's avatar Josh Story Committed by GitHub

Include additional prerender metadata about build-time routes (#96080)

Building on top of @agadzik work (see first commit)

Adds prerender route metadata to help downstream consumers understand
the nature of build-time prerenders

We break down prerender taxonomy as follows

routeType describes what the prerender serves:
* `route`: a non-UI endpoint, such as a Route Handler.
* `page`: a page whose route parameters are fully known.
* `shell`: a reusable PPR shell for a parameterized page.
* `fallback`: a fallback that may serve or specialize additional
parameter values.

response describes how complete the static response is:
* `complete`: the prerender contains the completed response.
* `initial`: an initial response is available, but the page UI is
incomplete; in practice this applies to partially prerenderable UI
routes.
* `empty`: there is no initial static response to send.

compute describes the request-time work required:
* `static`: no request-time server compute is needed.
* `resuming`: request-time compute resumes from the static response.
* `blocking`: the initial response is blocked until request-time compute
starts, but it may stream while that compute continues.

`htmlSize` reports the byte size of prerendered HTML when the output has
HTML.

The taxonomy is included only on a prerender group’s canonical primary
output—the HTML output for pages or the response output for Route
Handlers—and is omitted from secondary RSC and segment-data outputs.

---------
Co-authored-by: 's avataragadzik <andrew.gadzik@vercel.com>
parent 3a48dd6a
......@@ -136,6 +136,11 @@ ISR-enabled routes and static prerenders:
pathname: string // URL pathname
parentOutputId: string // ID of the source page/route
groupId: number // Revalidation group identifier (prerenders with same groupId revalidate together)
route: string // Source route matcher aligned with the filesystem route, keeping dynamic segments (e.g. /blog/[slug] for the prerendered path /blog/first)
routeType?: 'route' | 'fallback' | 'shell' | 'page' // Kind of canonical response
response?: 'empty' | 'initial' | 'complete' // Completeness before request-time work
compute?: 'blocking' | 'resuming' | 'static' // Request-time compute needed for the completed response
htmlSize?: number // Byte size of the prerendered App Router HTML shell
pprChain?: {
headers: Record<string, string> // PPR chain headers (e.g., 'next-resume': '1')
}
......@@ -159,6 +164,31 @@ ISR-enabled routes and static prerenders:
}
```
### Prerender classification
`routeType`, `response`, and `compute` are emitted together on the primary response in a prerender group. Related RSC, data, and segment outputs omit these fields. Pages Router templates with `fallback: false` also omit them because those templates are never served for unmatched URLs.
`routeType` identifies the kind of canonical response:
- `route`: a non-UI route, such as a Route Handler
- `page`: a page whose URL has no missing prerenderable parameters
- `shell`: the most specific reusable page shell for its class of URLs
- `fallback`: a reusable page response that can be specialized by filling more prerenderable parameters
`response` describes how complete the response is before request-time work:
- `empty`: no initial page response can be served
- `initial`: an initial response can be served, but it is not the completed page UI. In practice, this only applies to UI routes that are partially prerenderable
- `complete`: the response is complete; this can include a zero-byte response body, such as a `204` Route Handler response
`compute` describes the request-time compute needed to serve the completed response:
- `blocking`: no initial response can be sent before request-time compute starts; once started, the response can stream while compute continues
- `resuming`: an initial response is served while postponed work resumes on the server
- `static`: no server compute is required per request
`htmlSize` is only included on the primary App Router HTML output. A value of `0` means that the HTML shell is empty. Pages Router prerenders, Route Handlers, and related RSC, data, and segment outputs omit it.
## Static Files (`outputs.staticFiles`)
Static assets and auto-statically optimized pages:
......
......@@ -1453,5 +1453,8 @@
"1452": "Page \"%s\" is missing \"generateStaticParams()\" so it cannot be used with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params",
"1453": "Page \"%s\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params",
"1454": "Page \"%s\" returned an empty array from \"generateStaticParams()\". With \"output: export\", at least one route must be generated. See more info here: https://nextjs.org/docs/messages/generate-static-params",
"1455": "Page \"%s\" returned incomplete params from \"generateStaticParams()\". With \"output: export\", every params object must include all dynamic route parameters. Missing: %s. See more info here: https://nextjs.org/docs/messages/generate-static-params"
"1455": "Page \"%s\" returned incomplete params from \"generateStaticParams()\". With \"output: export\", every params object must include all dynamic route parameters. Missing: %s. See more info here: https://nextjs.org/docs/messages/generate-static-params",
"1456": "Expected an HTML size for prerendered app route \"%s\"",
"1457": "Expected prerender classification data for PPR route \"%s\"",
"1458": "Expected complete prerender classification for route \"%s\""
}
This diff is collapsed.
......@@ -856,6 +856,14 @@ async function exportAppImpl(
info.hasPostponed = result.hasPostponed
}
if (typeof result.hasPendingUi !== 'undefined') {
info.hasPendingUi = result.hasPendingUi
}
if (typeof result.htmlSize !== 'undefined') {
info.htmlSize = result.htmlSize
}
if (typeof result.hasStaticRsc !== 'undefined') {
info.hasStaticRsc = result.hasStaticRsc
}
......
......@@ -102,6 +102,7 @@ export async function exportAppPage(
segmentData,
prefetchHints,
renderResumeDataCache,
hasPendingUi,
} = metadata
// Ensure we don't postpone without having PPR enabled.
......@@ -237,6 +238,8 @@ export async function exportAppPage(
},
hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed),
hasPendingUi: hasPendingUi ?? false,
htmlSize: Buffer.byteLength(html),
hasStaticRsc,
cacheControl,
fetchMetrics,
......
......@@ -72,6 +72,8 @@ export type ExportRouteResult =
ssgNotFound?: boolean
hasEmptyStaticShell?: boolean
hasPostponed?: boolean
hasPendingUi?: boolean
htmlSize?: number
hasStaticRsc?: boolean
fetchMetrics?: FetchMetrics
renderResumeDataCache?: string
......@@ -150,6 +152,14 @@ export type ExportAppResult = {
* If the page has postponed when using PPR.
*/
hasPostponed?: boolean
/**
* If the prerender has UI that will resolve after the initial HTML.
*/
hasPendingUi?: boolean
/**
* The byte size of the HTML returned by the prerender.
*/
htmlSize?: number
/**
* If the page emitted a static RSC payload.
*/
......
......@@ -2623,6 +2623,7 @@ async function renderToHTMLOrFlightImpl(
const metadata: AppPageRenderResultMetadata = {
statusCode: isNotFoundPath ? 404 : undefined,
hasPendingUi: false,
}
const appUsingSizeAdjustment = !!nextFontManifest?.appUsingSizeAdjust
......@@ -8771,6 +8772,8 @@ async function prerenderToStream(
}
)
metadata.hasPendingUi = postponed != null
const { prelude, preludeIsEmpty } =
await processPreludeOp(unprocessedPrelude)
......@@ -8970,6 +8973,8 @@ async function prerenderToStream(
bootstrapScripts: [bootstrapScript],
}
)
metadata.hasPendingUi = postponed != null
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
......@@ -9539,6 +9544,8 @@ async function prerenderToStream(
}
)
metadata.hasPendingUi = errorPostponed != null
const { prelude, preludeIsEmpty } = await processPreludeOp(
unprocessedErrorHtmlStream
)
......
......@@ -43,6 +43,13 @@ export type AppPageRenderResultMetadata = {
*/
postponed?: string
/**
* Whether the prerender left any UI pending in a Suspense boundary. This is
* reported directly by React's prerender result before Next.js resumes
* client-only boundaries.
*/
hasPendingUi?: boolean
/**
* The headers to set on the response that were added by the render.
*/
......
......@@ -55,6 +55,9 @@ describe('404 Page Support SSG', () => {
it('should have 404 page in prerender-manifest', async () => {
const data = await next.readJSON('.next/prerender-manifest.json')
expect(data.routes['/404']).toEqual({
routeType: 'page',
response: 'complete',
compute: 'static',
allowHeader: [
'host',
'x-matched-path',
......
This diff is collapsed.
......@@ -94,6 +94,22 @@ describe('Prerender', () => {
'x-next-revalidate-tag-token',
]
const completeStaticPageClassification = {
routeType: 'page',
response: 'complete',
compute: 'static',
}
const initialStaticFallbackClassification = {
routeType: 'fallback',
response: 'initial',
compute: 'static',
}
const emptyBlockingPageClassification = {
routeType: 'page',
response: 'empty',
compute: 'blocking',
}
const expectedManifestRoutes = () => ({
'/': {
allowHeader,
......@@ -1721,9 +1737,22 @@ describe('Prerender', () => {
})
expect(manifest.version).toBe(4)
expect(manifest.routes).toEqual(expectedManifestRoutes())
expect(manifest.routes).toEqual(
Object.fromEntries(
Object.entries(expectedManifestRoutes()).map(
([pathname, route]) => [
pathname,
{
...route,
...completeStaticPageClassification,
},
]
)
)
)
expect(manifest.dynamicRoutes).toEqual({
'/api-docs/[...slug]': {
...initialStaticFallbackClassification,
dataRoute: `/_next/data/${next.buildId}/api-docs/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/api\\-docs\\/(.+?)\\.json$`
......@@ -1733,6 +1762,7 @@ describe('Prerender', () => {
allowHeader,
},
'/blocking-fallback-once/[slug]': {
...emptyBlockingPageClassification,
dataRoute: `/_next/data/${next.buildId}/blocking-fallback-once/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`
......@@ -1744,6 +1774,7 @@ describe('Prerender', () => {
allowHeader,
},
'/blocking-fallback-some/[slug]': {
...emptyBlockingPageClassification,
dataRoute: `/_next/data/${next.buildId}/blocking-fallback-some/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`
......@@ -1755,6 +1786,7 @@ describe('Prerender', () => {
allowHeader,
},
'/blocking-fallback/[slug]': {
...emptyBlockingPageClassification,
dataRoute: `/_next/data/${next.buildId}/blocking-fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
......@@ -1766,6 +1798,7 @@ describe('Prerender', () => {
allowHeader,
},
'/blog/[post]': {
...initialStaticFallbackClassification,
fallback: '/blog/[post].html',
dataRoute: `/_next/data/${next.buildId}/blog/[post].json`,
dataRouteRegex: normalizeRegEx(
......@@ -1775,6 +1808,7 @@ describe('Prerender', () => {
allowHeader,
},
'/blog/[post]/[comment]': {
...initialStaticFallbackClassification,
fallback: '/blog/[post]/[comment].html',
dataRoute: `/_next/data/${next.buildId}/blog/[post]/[comment].json`,
dataRouteRegex: normalizeRegEx(
......@@ -1795,6 +1829,7 @@ describe('Prerender', () => {
allowHeader,
},
'/fallback-only/[slug]': {
...initialStaticFallbackClassification,
dataRoute: `/_next/data/${next.buildId}/fallback-only/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/fallback\\-only\\/([^\\/]+?)\\.json$`
......@@ -1806,6 +1841,7 @@ describe('Prerender', () => {
allowHeader,
},
'/fallback-true/[slug]': {
...initialStaticFallbackClassification,
allowHeader,
dataRoute: `/_next/data/${next.buildId}/fallback-true/[slug].json`,
dataRouteRegex: normalizeRegEx(
......@@ -1828,6 +1864,7 @@ describe('Prerender', () => {
allowHeader,
},
'/non-json-blocking/[p]': {
...emptyBlockingPageClassification,
dataRoute: `/_next/data/${next.buildId}/non-json-blocking/[p].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`
......@@ -1839,6 +1876,7 @@ describe('Prerender', () => {
allowHeader,
},
'/non-json/[p]': {
...initialStaticFallbackClassification,
dataRoute: `/_next/data/${next.buildId}/non-json/[p].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\/([^\\/]+?)\\.json$`
......@@ -1850,6 +1888,7 @@ describe('Prerender', () => {
allowHeader,
},
'/user/[user]/profile': {
...initialStaticFallbackClassification,
fallback: '/user/[user]/profile.html',
dataRoute: `/_next/data/${next.buildId}/user/[user]/profile.json`,
dataRouteRegex: normalizeRegEx(
......@@ -1862,6 +1901,7 @@ describe('Prerender', () => {
},
'/catchall/[...slug]': {
...initialStaticFallbackClassification,
fallback: '/catchall/[...slug].html',
routeRegex: normalizeRegEx('^\\/catchall\\/(.+?)(?:\\/)?$'),
dataRoute: `/_next/data/${next.buildId}/catchall/[...slug].json`,
......
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
type AdapterBuildContext = Parameters<NextAdapter['onBuildComplete']>[0]
type Classification = {
routeType: 'route' | 'page' | 'fallback'
response: 'complete' | 'initial' | 'empty'
compute: 'static' | 'blocking'
}
const classificationKey = ({ routeType, response, compute }: Classification) =>
`${routeType}/${response}/${compute}`
// Cache Components CI enables the feature for every fixture through this
// environment variable, which would change the expected non-CC taxonomy.
// Skip the whole suite so nextTestSetup does not start a build in that job.
;(process.env.__NEXT_CACHE_COMPONENTS === 'true' ? describe.skip : describe)(
'adapter-prerender-metadata-non-cc',
() => {
const { next } = nextTestSetup({
files: __dirname,
})
async function getPrerenders() {
const { outputs }: AdapterBuildContext = await next.readJSON(
'build-complete.json'
)
return outputs.prerenders
}
it('exercises every valid non-Cache-Components combination', async () => {
const cases: Array<
Classification & {
pathname: string
manifestSection: 'routes' | 'dynamicRoutes'
}
> = [
{
pathname: '/static-route',
manifestSection: 'routes',
routeType: 'route',
response: 'complete',
compute: 'static',
},
{
pathname: '/',
manifestSection: 'routes',
routeType: 'page',
response: 'complete',
compute: 'static',
},
{
pathname: '/gsp',
manifestSection: 'routes',
routeType: 'page',
response: 'complete',
compute: 'static',
},
{
pathname: '/products/[slug]',
manifestSection: 'dynamicRoutes',
routeType: 'page',
response: 'empty',
compute: 'blocking',
},
{
pathname: '/blocking/[id]',
manifestSection: 'dynamicRoutes',
routeType: 'page',
response: 'empty',
compute: 'blocking',
},
{
pathname: '/static-fallback/[id]',
manifestSection: 'dynamicRoutes',
routeType: 'fallback',
response: 'initial',
compute: 'static',
},
]
const expectedKeys = [
'route/complete/static',
'page/complete/static',
'page/empty/blocking',
'fallback/initial/static',
]
expect(Array.from(new Set(cases.map(classificationKey))).sort()).toEqual(
expectedKeys.sort()
)
const prerenders = await getPrerenders()
const manifest = await next.readJSON('.next/prerender-manifest.json')
for (const { pathname, manifestSection, ...classification } of cases) {
const output = prerenders.find(
(prerender) => prerender.pathname === pathname
)
expect(output).toMatchObject(classification)
expect(manifest[manifestSection][pathname]).toMatchObject(
classification
)
}
const omittedFallback = prerenders.find(
(prerender) => prerender.pathname === '/omitted/[id]'
)
expect(omittedFallback).toBeDefined()
expect(omittedFallback).not.toHaveProperty('routeType')
expect(omittedFallback).not.toHaveProperty('response')
expect(omittedFallback).not.toHaveProperty('compute')
})
it('exposes classification only on canonical responses', async () => {
const prerenders = await getPrerenders()
const completePage = prerenders.find((output) => output.pathname === '/')
const blockingPage = prerenders.find(
(output) => output.pathname === '/products/[slug]'
)
const route = prerenders.find(
(output) => output.pathname === '/static-route'
)
const rsc = prerenders.find((output) => output.pathname === '/index.rsc')
expect(completePage).toMatchObject({
routeType: 'page',
response: 'complete',
compute: 'static',
htmlSize: expect.any(Number),
})
expect(blockingPage).toMatchObject({
routeType: 'page',
response: 'empty',
compute: 'blocking',
})
expect(blockingPage).not.toHaveProperty('htmlSize')
expect(route).toMatchObject({
routeType: 'route',
response: 'complete',
compute: 'static',
})
expect(route).not.toHaveProperty('htmlSize')
expect(rsc).toBeDefined()
expect(rsc).not.toHaveProperty('routeType')
expect(rsc).not.toHaveProperty('response')
expect(rsc).not.toHaveProperty('compute')
expect(rsc).not.toHaveProperty('htmlSize')
})
}
)
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>static page</p>
}
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return <p>product {slug}</p>
}
export const dynamic = 'force-static'
export function GET() {
return Response.json({ static: true })
}
import fs from 'fs/promises'
/** @type {import('next').NextAdapter } */
export default {
name: 'adapter-prerender-metadata-non-cc',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
adapterPath: require.resolve('./my-adapter.mjs'),
}
module.exports = nextConfig
export function getStaticPaths() {
return {
paths: [{ params: { id: 'known' } }],
fallback: 'blocking',
}
}
export function getStaticProps({ params }: { params: { id: string } }) {
return { props: { id: params.id } }
}
export default function Page({ id }: { id: string }) {
return <p>blocking {id}</p>
}
export function getStaticProps() {
return { props: { message: 'pages static props' } }
}
export default function Page({ message }: { message: string }) {
return <p>{message}</p>
}
export function getStaticPaths() {
return {
paths: [{ params: { id: 'known' } }],
fallback: false,
}
}
export function getStaticProps({ params }: { params: { id: string } }) {
return { props: { id: params.id } }
}
export default function Page({ id }: { id: string }) {
return <p>omitted {id}</p>
}
export function getStaticPaths() {
return { paths: [], fallback: true }
}
export function getStaticProps({ params }: { params: { id: string } }) {
return { props: { id: params.id } }
}
export default function Page({ id }: { id: string }) {
return <p>static fallback {id}</p>
}
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 100))
return <div>Custom Data</div>
}
export function generateStaticParams() {
return [{ slug: 'first' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<div>{slug}</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
export function ClientHole() {
const searchParams = useSearchParams()
return <p>q: {searchParams?.get('q')}</p>
}
import { Suspense } from 'react'
import { ClientHole } from './client'
export default function Page() {
return (
<div>
<p>static part</p>
<Suspense fallback={<p>loading...</p>}>
<ClientHole />
</Suspense>
</div>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
export function ClientHole() {
return <p>query: {useSearchParams()?.get('query')}</p>
}
export default function Page() {
return <p>complete static partial fallback</p>
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return children
}
import { Suspense } from 'react'
import { ClientHole } from '../../client-hole'
export function generateStaticParams() {
return [{ slug: 'known' }]
}
export default function Page() {
return (
<Suspense fallback={<p>loading query</p>}>
<ClientHole />
</Suspense>
)
}
import { cookies } from 'next/headers'
export const instant = false
export default async function Page() {
await cookies()
return <p>empty blocking shell</p>
}
import { Suspense } from 'react'
import { ClientHole } from '../../client-hole'
export default function Page() {
return (
<Suspense fallback={<p>loading query</p>}>
<ClientHole />
</Suspense>
)
}
import { cookies } from 'next/headers'
export const instant = false
export default async function Page() {
await cookies()
return <p>empty shell</p>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Loading() {
return <div>loading...</div>
}
import { headers } from 'next/headers'
export default async function Page() {
const requestHeaders = await headers()
return <div>{requestHeaders.get('user-agent')}</div>
}
export default function Page() {
return <p>hello world</p>
}
import { Suspense } from 'react'
import { headers } from 'next/headers'
async function Dynamic() {
const requestHeaders = await headers()
return <div>{requestHeaders.get('user-agent')}</div>
}
export default function Page() {
return (
<div>
<p>static shell content</p>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
export default function Loading() {
return <div>loading...</div>
}
export default async function Page({
params,
}: {
params: Promise<{ one: string; two: string }>
}) {
const { one, two } = await params
return (
<div>
{one}:{two}
</div>
)
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ one: 'b' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return <>{children}</>
}
export function GET() {
return Response.json({ static: true })
}
export default function Page() {
return <p>fully static shell</p>
}
import fs from 'fs/promises'
/** @type {import('next').NextAdapter } */
export default {
name: 'adapter-prerender-metadata',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
adapterPath: require.resolve('./my-adapter.mjs'),
}
module.exports = nextConfig
export function getStaticPaths() {
return {
paths: [{ params: { id: 'a' } }],
fallback: 'blocking',
}
}
export function getStaticProps({ params }: { params: { id: string } }) {
return { props: { id: params.id } }
}
export default function Page({ id }: { id: string }) {
return <p>blocking {id}</p>
}
export function getStaticProps() {
return { props: { message: 'pages static props' } }
}
export default function Page({ message }: { message: string }) {
return <p>{message}</p>
}
export function getStaticPaths() {
return {
paths: [{ params: { id: 'a' } }],
fallback: false,
}
}
export function getStaticProps({ params }: { params: { id: string } }) {
return { props: { id: params.id } }
}
export default function Page({ id }: { id: string }) {
return <p>omitted {id}</p>
}
export function getStaticPaths() {
return { paths: [], fallback: true }
}
export function getStaticProps({ params }) {
return { props: { id: params.id } }
}
export default function Page({ id }) {
return <p>static fallback {id}</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