Unverified Commit 834c41ef authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Respect `generateStaticParams` in instant navigation shell (#91316)

When the instant navigation testing cookie is set, the debug static
shell path previously called `getFallbackRouteParams()` which treats all
dynamic segments as fallback params regardless of
`generateStaticParams`. This caused two issues:

- Root params (via `next/root-params`) errored with a
`NEXT_STATIC_GEN_BAILOUT` 500 response because the root layout's param
access returned a hanging promise, which was treated as uncached data
accessed outside of `<Suspense>`.
- Params defined in `generateStaticParams` were incorrectly excluded
from the instant shell, shown behind Suspense fallbacks instead of
resolving.

The fix uses `prerenderInfo?.fallbackRouteParams` from the prerender
manifest instead, which correctly distinguishes between statically known
params (defined in `generateStaticParams`) and unknown params. For
prerendered URLs, the outer guard (`!isPrerendered`) prevents the
fallback path from being entered, so no fallback params are set and all
params resolve normally.

To make this work in dev mode, the dev server now populates
`fallbackRouteParams` in the prerender manifest's dynamic route entries,
which were previously left as `undefined`.

Additionally, the `fallbackParams` request metadata is now overridden
when rendering a debug static shell. Without this override, the staged
rendering would use the smallest set of fallback params across all
prerendered routes (set by `base-server.ts` for dev validation), which
may omit fallback params for the current URL when a different value for
the same param is defined in `generateStaticParams`. The override
ensures the route-specific fallback params are used instead.
parent c1f13e48
......@@ -938,19 +938,29 @@ export async function handler(
: normalizedSrcPage
const fallbackRouteParams =
// If we're in production and we have fallback route params, always
// use them for the fallback shell.
isProduction && prerenderInfo?.fallbackRouteParams
// In production or when debugging the static shell (e.g. instant
// navigation testing), use the prerender manifest's fallback
// route params which correctly identifies which params are
// unknown. Note: in dev, this block is only entered for
// non-prerendered URLs (guarded by the outer condition).
(isProduction || isDebugStaticShell) &&
prerenderInfo?.fallbackRouteParams
? createOpaqueFallbackRouteParams(
prerenderInfo.fallbackRouteParams
)
: // Otherwise, if we're debugging the fallback shell or the
// static shell, then we have to manually generate the
// fallback route params.
isDebugFallbackShell || isDebugStaticShell
: // When debugging the fallback shell, treat all params as
// fallback (simulating the worst-case shell).
isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null
// When rendering a debug static shell, override the fallback
// params on the request so that the staged rendering correctly
// defers params that are not statically known.
if (isDebugStaticShell && fallbackRouteParams) {
addRequestMeta(req, 'fallbackParams', fallbackRouteParams)
}
// We use the response cache here to handle the revalidation and
// management of the fallback shell.
const fallbackResponse = await routeModule.handleResponse({
......@@ -1154,27 +1164,24 @@ export async function handler(
}
const fallbackRouteParams =
// If we're in production and we have fallback route params, then we
// can use the manifest fallback route params if we need to render the
// fallback shell.
isProduction &&
prerenderInfo?.fallbackRouteParams &&
getRequestMeta(req, 'renderFallbackShell')
// In production or when debugging the static shell for a
// non-prerendered URL, use the prerender manifest's fallback route
// params which correctly identifies which params are unknown.
((isProduction && getRequestMeta(req, 'renderFallbackShell')) ||
(isDebugStaticShell && !isPrerendered)) &&
prerenderInfo?.fallbackRouteParams
? createOpaqueFallbackRouteParams(prerenderInfo.fallbackRouteParams)
: // Otherwise, if we're debugging the fallback shell or the static
// shell, then we have to manually generate the fallback route
// params.
isDebugFallbackShell || isDebugStaticShell
: isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null
// For staged dynamic rendering (cached navigations), pass the fallback
// params via request meta so the RequestStore knows which params to defer
// to the runtime stage. We don't pass them as fallbackRouteParams because
// that would replace actual param values with opaque placeholders during
// segment resolution.
// For staged dynamic rendering (Cached Navigations) and debug static
// shell rendering, pass the fallback params via request meta so the
// RequestStore knows which params to defer. We don't pass them as
// fallbackRouteParams because that would replace actual param values
// with opaque placeholders during segment resolution.
if (
isProduction &&
(isProduction || isDebugStaticShell) &&
nextConfig.cacheComponents &&
!isPrerendered &&
prerenderInfo?.fallbackRouteParams
......
......@@ -909,6 +909,14 @@ export default class DevServer extends Server {
existingManifest.routes[staticPath] = {} as any
}
// Find the fallback route from the prerendered routes. This is
// the route whose pathname matches the page pattern (e.g.
// /dynamic-params/[slug]) and has fallback route params describing
// which params are unknown at build time.
const fallbackPrerenderedRoute = prerenderedRoutes?.find(
(route) => route.pathname === pathname
)
existingManifest.dynamicRoutes[pathname] = {
dataRoute: null,
dataRouteRegex: null,
......@@ -917,8 +925,8 @@ export default class DevServer extends Server {
fallbackExpire: undefined,
fallbackHeaders: undefined,
fallbackStatus: undefined,
fallbackRootParams: undefined,
fallbackRouteParams: undefined,
fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,
fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,
fallbackSourceRoute: pathname,
prefetchDataRoute: undefined,
prefetchDataRouteRegex: undefined,
......
import { Suspense } from 'react'
export function generateStaticParams() {
return [{ slug: 'hello' }]
}
export default function DynamicParamsPage({
params,
}: {
......
......@@ -23,9 +23,12 @@ export default function HomePage() {
<Link href="/cookies-page" id="link-to-cookies-page">
Go to cookies page
</Link>
<Link href="/dynamic-params/hello" id="link-to-dynamic-params">
<Link href="/dynamic-params/unknown" id="link-to-dynamic-params">
Go to dynamic params page
</Link>
<Link href="/dynamic-params/hello" id="link-to-static-dynamic-params">
Go to static dynamic params page
</Link>
<Link href="/search-params-page?foo=bar" id="link-to-search-params">
Go to search params page
</Link>
......@@ -36,9 +39,12 @@ export default function HomePage() {
<a href="/cookies-page" id="plain-link-to-cookies-page">
Go to cookies page (MPA)
</a>
<a href="/dynamic-params/hello" id="plain-link-to-dynamic-params">
<a href="/dynamic-params/unknown" id="plain-link-to-dynamic-params">
Go to dynamic params page (MPA)
</a>
<a href="/dynamic-params/hello" id="plain-link-to-static-dynamic-params">
Go to static dynamic params page (MPA)
</a>
<a href="/search-params-page?foo=bar" id="plain-link-to-search-params">
Go to search params page (MPA)
</a>
......
......@@ -6,6 +6,7 @@ const nextConfig = {
experimental: {
// Enable the testing API in production builds for these tests
exposeTestingApiInProductionBuild: true,
instantNavigationDevToolsToggle: true,
},
}
......
import { lang } from 'next/root-params'
import { ReactNode } from 'react'
export async function generateStaticParams() {
return [{ lang: 'en' }]
}
export default async function RootLayout({
children,
}: {
children: ReactNode
}) {
const currentLang = await lang()
return (
<html lang={currentLang}>
<body>
<p data-testid="lang-value">lang: {currentLang}</p>
{children}
</body>
</html>
)
}
export default function HomePage() {
return (
<div>
<h1 data-testid="home-title">Root Params Test</h1>
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: true,
instantNavigationDevToolsToggle: true,
},
}
module.exports = nextConfig
......@@ -22,51 +22,53 @@
* API in production mode for testing purposes.
*/
import { nextTestSetup } from 'e2e-utils'
import { NextInstance, nextTestSetup } from 'e2e-utils'
import { instant } from '@next/playwright'
import type * as Playwright from 'playwright'
import { join } from 'node:path'
/**
* Opens a browser and returns the underlying Playwright Page instance.
*
* We use this pattern so our test assertions look as close as possible to
* what users would write with the actual Playwright helper package. The
* Next.js test infra wraps Playwright with its own BrowserInterface, but
* the Instant Navigation Testing API is designed to work with native Playwright.
*/
async function openPage(
next: NextInstance,
url: string,
options?: { cookies?: Array<{ name: string; value: string }> }
): Promise<Playwright.Page> {
let page: Playwright.Page
await next.browser(url, {
beforePageLoad(p) {
page = p
if (options?.cookies) {
const { hostname } = new URL(next.url)
p.context().addCookies(
options.cookies.map((c) => ({
...c,
domain: hostname,
path: '/',
}))
)
}
},
})
return page!
}
describe('instant-navigation-testing-api', () => {
const { next } = nextTestSetup({
files: __dirname,
files: join(__dirname, 'fixtures', 'default'),
// Skip deployment tests because the exposeTestingApiInProductionBuild flag
// doesn't exist in the production version of Next.js yet
skipDeployment: true,
})
/**
* Opens a browser and returns the underlying Playwright Page instance.
*
* We use this pattern so our test assertions look as close as possible to
* what users would write with the actual Playwright helper package. The
* Next.js test infra wraps Playwright with its own BrowserInterface, but
* the Instant Navigation Testing API is designed to work with native Playwright.
*/
async function openPage(
url: string,
options?: { cookies?: Array<{ name: string; value: string }> }
): Promise<Playwright.Page> {
let page: Playwright.Page
await next.browser(url, {
beforePageLoad(p) {
page = p
if (options?.cookies) {
const { hostname } = new URL(next.url)
p.context().addCookies(
options.cookies.map((c) => ({
...c,
domain: hostname,
path: '/',
}))
)
}
},
})
return page!
}
it('renders prefetched loading shell instantly during navigation', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#link-to-target')
......@@ -92,7 +94,7 @@ describe('instant-navigation-testing-api', () => {
})
it('renders runtime-prefetched content instantly during navigation', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#link-to-runtime-prefetch')
......@@ -132,7 +134,7 @@ describe('instant-navigation-testing-api', () => {
})
it('renders full prefetch content instantly when prefetch={true}', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#link-to-full-prefetch')
......@@ -148,7 +150,7 @@ describe('instant-navigation-testing-api', () => {
})
it('throws when attempting to nest instant scopes', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
// Attempt to acquire the lock again by nesting instant() calls.
......@@ -166,7 +168,7 @@ describe('instant-navigation-testing-api', () => {
})
it('renders static shell on page reload', async () => {
const page = await openPage('/target-page')
const page = await openPage(next, '/target-page')
// Wait for the page to fully load with dynamic content
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
......@@ -195,7 +197,7 @@ describe('instant-navigation-testing-api', () => {
})
it('renders static shell on MPA navigation via plain anchor', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
// Navigate using a plain anchor (triggers full page load)
......@@ -222,7 +224,7 @@ describe('instant-navigation-testing-api', () => {
})
it('reload followed by MPA navigation, both block dynamic data', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
// Reload the page while in instant mode
......@@ -253,7 +255,7 @@ describe('instant-navigation-testing-api', () => {
})
it('successive MPA navigations within instant scope', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
// First MPA navigation: reload
......@@ -304,7 +306,7 @@ describe('instant-navigation-testing-api', () => {
// NOT be present.
describe('runtime params are excluded from instant shell', () => {
it('does not include cookie values in instant shell during client navigation', async () => {
const page = await openPage('/', {
const page = await openPage(next, '/', {
cookies: [{ name: 'testCookie', value: 'hello' }],
})
......@@ -331,7 +333,7 @@ describe('instant-navigation-testing-api', () => {
})
it('does not include dynamic param values in instant shell during client navigation', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#link-to-dynamic-params')
......@@ -352,11 +354,11 @@ describe('instant-navigation-testing-api', () => {
// After exiting instant scope, param value streams in
const paramValue = page.locator('[data-testid="param-value"]')
await paramValue.waitFor({ state: 'visible' })
expect(await paramValue.textContent()).toContain('slug: hello')
expect(await paramValue.textContent()).toContain('slug: unknown')
})
it('does not include search param values in instant shell during client navigation', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#link-to-search-params')
......@@ -385,7 +387,7 @@ describe('instant-navigation-testing-api', () => {
})
it('does not include cookie values in instant shell during page load', async () => {
const page = await openPage('/', {
const page = await openPage(next, '/', {
cookies: [{ name: 'testCookie', value: 'hello' }],
})
......@@ -412,7 +414,7 @@ describe('instant-navigation-testing-api', () => {
})
it('does not include dynamic param values in instant shell during page load', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#plain-link-to-dynamic-params')
......@@ -433,11 +435,11 @@ describe('instant-navigation-testing-api', () => {
// After exiting instant scope, param value streams in
const paramValue = page.locator('[data-testid="param-value"]')
await paramValue.waitFor({ state: 'visible', timeout: 10000 })
expect(await paramValue.textContent()).toContain('slug: hello')
expect(await paramValue.textContent()).toContain('slug: unknown')
})
it('does not include search param values in instant shell during page load', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#plain-link-to-search-params')
......@@ -466,12 +468,56 @@ describe('instant-navigation-testing-api', () => {
})
})
describe('statically generated params are included in instant shell', () => {
it('includes statically generated param values in instant shell during client navigation', async () => {
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#link-to-static-dynamic-params')
// Static page title is visible
const title = page.locator('[data-testid="dynamic-params-title"]')
await title.waitFor({ state: 'visible' })
// Param value IS in the shell (slug 'hello' is in generateStaticParams)
const paramValue = page.locator('[data-testid="param-value"]')
await paramValue.waitFor({ state: 'visible' })
expect(await paramValue.textContent()).toContain('slug: hello')
// Suspense fallback is NOT visible
const fallback = page.locator('[data-testid="params-fallback"]')
expect(await fallback.count()).toBe(0)
})
})
it('includes statically generated param values in instant shell during page load', async () => {
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#plain-link-to-static-dynamic-params')
// Static page title is visible
const title = page.locator('[data-testid="dynamic-params-title"]')
await title.waitFor({ state: 'visible' })
// Param value IS in the shell (slug 'hello' is in generateStaticParams)
const paramValue = page.locator('[data-testid="param-value"]')
await paramValue.waitFor({ state: 'visible' })
expect(await paramValue.textContent()).toContain('slug: hello')
// Suspense fallback is NOT visible
const fallback = page.locator('[data-testid="params-fallback"]')
expect(await fallback.count()).toBe(0)
})
})
})
// In dev mode, hover/intent-based prefetches should not send requests
// that produce stale segment data. If a hover prefetch caches the route
// with resolved runtime data before the instant lock is acquired, params
// will leak into the shell when instant mode is later enabled.
it('does not leak runtime data from hover prefetch into instant shell', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
// Hover over the dynamic params link to trigger an intent prefetch
await page.hover('#link-to-dynamic-params')
......@@ -500,11 +546,11 @@ describe('instant-navigation-testing-api', () => {
// After exiting instant scope, param value streams in
const paramValue = page.locator('[data-testid="param-value"]')
await paramValue.waitFor({ state: 'visible' })
expect(await paramValue.textContent()).toContain('slug: hello')
expect(await paramValue.textContent()).toContain('slug: unknown')
})
it('subsequent navigations after instant scope are not locked', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
// First, do an MPA navigation within an instant scope
await instant(page, async () => {
......@@ -536,7 +582,7 @@ describe('instant-navigation-testing-api', () => {
})
it('throws descriptive error on fresh page without baseURL', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
const freshPage = await page.context().newPage()
try {
let caughtError: Error | undefined
......@@ -591,7 +637,7 @@ describe('instant-navigation-testing-api', () => {
})
it('sets cookie before first navigation when using baseURL', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
const freshPage = await page.context().newPage()
try {
await instant(
......@@ -634,7 +680,7 @@ describe('instant-navigation-testing-api', () => {
})
it('clears cookie after instant scope exits', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await instant(page, async () => {
await page.reload()
......@@ -651,7 +697,7 @@ describe('instant-navigation-testing-api', () => {
})
it('clears cookie even when callback throws', async () => {
const page = await openPage('/')
const page = await openPage(next, '/')
await expect(
instant(page, async () => {
......@@ -667,3 +713,26 @@ describe('instant-navigation-testing-api', () => {
expect(instantCookie).toBeUndefined()
})
})
describe('instant-navigation-testing-api - root params', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', 'root-params'),
skipDeployment: true,
})
it('includes root param in instant shell', async () => {
const page = await openPage(next, '/en')
const langValue = page.locator('[data-testid="lang-value"]')
await langValue.waitFor({ state: 'visible' })
expect(await langValue.textContent()).toContain('lang: en')
await instant(page, async () => {
await page.reload()
// The root param value is still visible (it's statically known)
await langValue.waitFor({ state: 'visible' })
expect(await langValue.textContent()).toContain('lang: en')
})
})
})
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