Unverified Commit 396fed36 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Remove bailed out SSG routes from the list of SSG (#83861)

### Why?

When SSG, the pages can bail out when detected a dynamic usage. However,
the routes that bailed out were still marked as SSG, which can confuse
the users.

### How?

Remove the bailed-out routes from the SSG routes list. If there are no
more SSG routes for the dynamic route, mark it as dynamic in Build CLI.

#### Before - Has 1, 2, 3, even though they bailed.

```
Route (app)                         Size  First Load JS    
┌ ○ /_not-found                      0 B         114 kB
└ ● /[id]                            0 B         114 kB
    ├ /1
    ├ /2
    └ /3
+ First Load JS shared by all     114 kB
  ├ chunks/29c57ad6b43f6070.js   75.8 kB
  ├ chunks/df142624801412ea.js   24.3 kB
  └ other shared chunks (total)  13.5 kB


○  (Static)  prerendered as static content
●  (SSG)     prerendered as static HTML (uses generateStaticParams)
```

#### After - No longer has 1, 2, 3, and the route is marked as dynamic.

```
Route (app)                         Size  First Load JS    
┌ ○ /_not-found                      0 B         114 kB
└ ƒ /[id]                            0 B         114 kB
+ First Load JS shared by all     114 kB
  ├ chunks/4963d796c068bb13.js   24.3 kB
  ├ chunks/f59bbf014aa0eff6.js   75.8 kB
  └ other shared chunks (total)  13.5 kB


○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand
```

Fixes https://github.com/vercel/next.js/issues/76507
Closes NAR-194

---------
Co-authored-by: 's avatarWyatt Johnson <accounts+github@wyattjoh.ca>
parent 954d40be
......@@ -2811,6 +2811,8 @@ export default async function build(
buildStage: 'static-generation',
})
const hasGSPAndRevalidateZero = new Set<string>()
// we need to trigger automatic exporting when we have
// - static 404/500
// - getStaticProps paths
......@@ -3087,6 +3089,8 @@ export default async function build(
const appConfig = appDefaultConfigs.get(originalAppPath)
if (!appConfig) throw new InvariantError('App config not found')
const ssgPageRoutesSet = new Set(pageInfos.get(page)?.ssgPageRoutes)
let hasRevalidateZero =
appConfig.revalidate === 0 ||
getCacheControl(page).revalidate === 0
......@@ -3282,13 +3286,35 @@ export default async function build(
}
} else {
hasRevalidateZero = true
// we might have determined during prerendering that this page
// used dynamic data
pageInfos.set(route.pathname, {
...(pageInfos.get(route.pathname) as PageInfo),
isSSG: false,
isStatic: false,
})
if (ssgPageRoutesSet.has(route.pathname)) {
const pageInfo = pageInfos.get(page) as PageInfo
// Remove the route from the SSG page routes if it bailed out
// during prerendering.
ssgPageRoutesSet.delete(route.pathname)
// Mark the route as having a GSP and revalidate zero.
if (ssgPageRoutesSet.size === 0) {
hasGSPAndRevalidateZero.delete(page)
} else {
hasGSPAndRevalidateZero.add(page)
}
pageInfos.set(page, {
...pageInfo,
ssgPageRoutes: Array.from(ssgPageRoutesSet),
// If there are no SSG page routes left, then the page is not SSG.
isSSG: ssgPageRoutesSet.size === 0 ? false : pageInfo.isSSG,
})
} else {
// we might have determined during prerendering that this page
// used dynamic data
pageInfos.set(route.pathname, {
...(pageInfos.get(route.pathname) as PageInfo),
isSSG: false,
isStatic: false,
})
}
}
}
......@@ -4167,6 +4193,7 @@ export default async function build(
pageExtensions: config.pageExtensions,
buildManifest,
middlewareManifest,
hasGSPAndRevalidateZero,
})
)
......
......@@ -255,12 +255,14 @@ export async function printTreeView(
pageExtensions,
middlewareManifest,
useStaticPages404,
hasGSPAndRevalidateZero,
}: {
pagesDir?: string
pageExtensions: PageExtensions
buildManifest: BuildManifest
middlewareManifest: MiddlewareManifest
useStaticPages404: boolean
hasGSPAndRevalidateZero: Set<string>
}
) {
// Can be overridden for test purposes to omit the build duration output.
......@@ -373,6 +375,23 @@ export async function printTreeView(
symbol = 'ƒ'
}
if (hasGSPAndRevalidateZero.has(item)) {
usedSymbols.add('ƒ')
messages.push([
`${border} ƒ ${item}${
totalDuration > MIN_DURATION
? ` (${getPrettyDuration(totalDuration)})`
: ''
}`,
showRevalidate && pageInfo?.initialCacheControl
? formatRevalidate(pageInfo.initialCacheControl)
: '',
showExpire && pageInfo?.initialCacheControl
? formatExpire(pageInfo.initialCacheControl)
: '',
])
}
usedSymbols.add(symbol)
messages.push([
......@@ -393,6 +412,8 @@ export async function printTreeView(
const totalRoutes = pageInfo.ssgPageRoutes.length
const contSymbol = i === arr.length - 1 ? ' ' : '├'
// HERE
let routes: { route: string; duration: number; avgDuration?: number }[]
if (pageInfo.ssgPageDurations?.some((d) => d > MIN_DURATION)) {
const previewPages = totalRoutes === 8 ? 8 : Math.min(totalRoutes, 7)
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default async function Page({
params,
searchParams,
}: {
params: Promise<{ id: string }>
searchParams: Promise<{ id: string }>
}) {
const { id } = await params
// Bail out for /ssg-bailout-partial/1 only.
if (id === '1') {
const { id } = await searchParams
return <p>hello world {id}</p>
}
return <p>hello world</p>
}
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ id: string }>
}) {
const { id } = await searchParams
return <p>hello world {id}</p>
}
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export default function Page() {
return <p>hello world</p>
}
export function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
import { nextTestSetup } from 'e2e-utils'
describe('build-output-ssg-bailout', () => {
if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true') {
it.skip('PPR is enabled, will throw instead of bailing out', () => {})
return
}
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
env: {
__NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT: '1',
NEXT_DEBUG_BUILD: '1',
},
})
beforeAll(() => next.build())
// This is available when NEXT_DEBUG_BUILD is set (or --debug flag is used).
it('should show error messages for SSG bailout', async () => {
expect(next.cliOutput).toContain(
'Error: Static generation failed due to dynamic usage on /ssg-bailout/1, reason: `await searchParams`, `searchParams.then`, or similar'
)
expect(next.cliOutput).toContain(
'Error: Static generation failed due to dynamic usage on /ssg-bailout/2, reason: `await searchParams`, `searchParams.then`, or similar'
)
expect(next.cliOutput).toContain(
'Error: Static generation failed due to dynamic usage on /ssg-bailout/3, reason: `await searchParams`, `searchParams.then`, or similar'
)
// Bailed out for /ssg-bailout-partial/1 only.
expect(next.cliOutput).toContain(
'Error: Static generation failed due to dynamic usage on /ssg-bailout-partial/1, reason: `await searchParams`, `searchParams.then`, or similar'
)
})
it('should list SSG pages for pages that did not bail out', async () => {
// - /ssg/[id] is marked (SSG) and has 1,2,3 listed.
// - /ssg-bailout-partial/[id] is marked (SSG) and has 2,3 listed.
// - /ssg-bailout/[id] is marked (Dynamic) and has nothing listed.
expect(getTreeView(next.cliOutput)).toMatchInlineSnapshot(`
"Route (app)
┌ ○ /_not-found
├ ƒ /ssg-bailout-partial/[id]
├ ● /ssg-bailout-partial/[id]
├ ├ /ssg-bailout-partial/2
├ └ /ssg-bailout-partial/3
├ ƒ /ssg-bailout/[id]
└ ● /ssg/[id]
├ /ssg/1
├ /ssg/2
└ /ssg/3
○ (Static) prerendered as static content
● (SSG) prerendered as static HTML (uses generateStaticParams)
ƒ (Dynamic) server-rendered on demand"
`)
})
})
function getTreeView(cliOutput: string): string {
let foundStart = false
const lines: string[] = []
for (const line of cliOutput.split('\n')) {
foundStart ||= line.startsWith('Route ')
if (foundStart) {
lines.push(line)
}
}
return lines.join('\n').trim()
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = 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