Unverified Commit ce0f17ff authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

Support dynamicParams false with Cache Components

parent 62d9b8e0
...@@ -910,7 +910,13 @@ impl ReactServerComponentValidator { ...@@ -910,7 +910,13 @@ impl ReactServerComponentValidator {
r"[\\/](page|layout|route|icon\d?|apple-icon\d?|opengraph-image\d?|twitter-image\d?|sitemap|robots|manifest)\.{ext_pattern}$", r"[\\/](page|layout|route|icon\d?|apple-icon\d?|opengraph-image\d?|twitter-image\d?|sitemap|robots|manifest)\.{ext_pattern}$",
)) ))
.unwrap(); .unwrap();
let is_app_entry = re.is_match(&self.filepath); let entry_match = re.captures(&self.filepath);
let is_app_entry = entry_match.is_some();
let is_metadata_entry = entry_match
.as_ref()
.and_then(|captures| captures.get(1))
.map(|entry| !matches!(entry.as_str(), "page" | "layout" | "route"))
.unwrap_or(false);
if is_app_entry { if is_app_entry {
let mut possibly_invalid_exports: FxIndexMap<Atom, (InvalidExportKind, Span)> = let mut possibly_invalid_exports: FxIndexMap<Atom, (InvalidExportKind, Span)> =
...@@ -949,8 +955,20 @@ impl ReactServerComponentValidator { ...@@ -949,8 +955,20 @@ impl ReactServerComponentValidator {
); );
} }
} }
"dynamicParams" | "dynamic" | "fetchCache" | "revalidate" // Metadata route loaders filter this export, so keep
| "experimental_ppr" // rejecting it there instead of silently ignoring it.
"dynamicParams" if self.cache_components_enabled && is_metadata_entry => {
possibly_invalid_exports.insert(
export_name.clone(),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::CacheComponents,
),
*span,
),
);
}
"dynamic" | "fetchCache" | "revalidate" | "experimental_ppr"
if self.cache_components_enabled => if self.cache_components_enabled =>
{ {
possibly_invalid_exports.insert( possibly_invalid_exports.insert(
......
...@@ -11,13 +11,6 @@ ...@@ -11,13 +11,6 @@
: ^^^^^^^ : ^^^^^^^
3 | export const dynamicParams = false 3 | export const dynamicParams = false
`---- `----
x Route segment config "dynamicParams" is not compatible with `nextConfig.cacheComponents`. Please remove it.
,-[input.js:3:1]
2 | export const dynamic = 'force-dynamic'
3 | export const dynamicParams = false
: ^^^^^^^^^^^^^
4 | export const fetchCache = 'force-no-store'
`----
x Route segment config "fetchCache" is not compatible with `nextConfig.cacheComponents`. Please remove it. x Route segment config "fetchCache" is not compatible with `nextConfig.cacheComponents`. Please remove it.
,-[input.js:4:1] ,-[input.js:4:1]
3 | export const dynamicParams = false 3 | export const dynamicParams = false
......
...@@ -591,15 +591,33 @@ export async function generateStaticParams() { ...@@ -591,15 +591,33 @@ export async function generateStaticParams() {
} }
``` ```
Paths you don't return are still served. Next.js prerenders a static shell for the unknown params and streams the rest at request time. See [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components) for the full prerender-a-subset workflow. By default, paths you don't return are still served. Next.js prerenders a static shell for the unknown params and streams the rest at request time. See [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components) for the full prerender-a-subset workflow.
### `dynamicParams` is not supported ### Use `dynamicParams = false` to reject unknown params
**Delete the export.** With Cache Components enabled, exporting `dynamicParams` fails the build with this error message: Keep `dynamicParams = false` if the values returned by `generateStaticParams` are the complete set of paths that should exist for this deployment:
> Route segment config "dynamicParams" is not compatible with `nextConfig.cacheComponents`. ```tsx filename="app/blog/[slug]/page.tsx" switcher
export const dynamicParams = false
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
return posts.map((post) => ({ slug: post.slug }))
}
```
```jsx filename="app/blog/[slug]/page.js" switcher
export const dynamicParams = false
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
return posts.map((post) => ({ slug: post.slug }))
}
```
Next.js records the complete generated parameter combinations at build time. A request for any other combination returns a hard 404 before the Page component or Route Handler runs and before a fallback shell is sent. Revalidating a generated path can update its content, but does not add new parameter combinations. Add new paths by returning them from `generateStaticParams` in a new deployment.
Params not returned by `generateStaticParams` are rendered on request. If you used `dynamicParams: false` to reject them, call [`notFound()`](/docs/app/api-reference/functions/not-found) in the page when the param doesn't resolve to real data. If unknown params should render on demand, omit `dynamicParams` or set it to `true` and follow the `<Suspense>` guidance below.
### Await `params` inside `<Suspense>` ### Await `params` inside `<Suspense>`
......
...@@ -5,7 +5,7 @@ description: API reference for the dynamicParams route segment config option. ...@@ -5,7 +5,7 @@ description: API reference for the dynamicParams route segment config option.
The `dynamicParams` option allows you to control what happens when a dynamic segment is visited that was not generated with [generateStaticParams](/docs/app/api-reference/functions/generate-static-params). The `dynamicParams` option allows you to control what happens when a dynamic segment is visited that was not generated with [generateStaticParams](/docs/app/api-reference/functions/generate-static-params).
```tsx filename="layout.tsx | page.tsx" switcher ```tsx filename="layout.tsx | page.tsx | route.ts" switcher
export const dynamicParams = true // true | false export const dynamicParams = true // true | false
``` ```
...@@ -19,4 +19,5 @@ export const dynamicParams = true // true | false ...@@ -19,4 +19,5 @@ export const dynamicParams = true // true | false
> **Good to know**: > **Good to know**:
> >
> - This option replaces the `fallback: true | false | blocking` option of `getStaticPaths` in the `pages` directory. > - This option replaces the `fallback: true | false | blocking` option of `getStaticPaths` in the `pages` directory.
> - `dynamicParams` is not available when [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled. > - With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), `false` treats the complete parameter combinations returned by `generateStaticParams` as the allowed paths for that deployment. Other combinations return a 404 before the Page component or Route Handler runs, and no fallback shell is sent.
> - [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) is not called again during revalidation. To add a path to a closed dynamic route, create a new deployment that returns the path from `generateStaticParams`.
const generatedResources = [
{ locale: 'en', slug: 'a' },
{ locale: 'fr', slug: 'b' },
]
export const dynamicParams = false
export function generateStaticParams() {
return generatedResources
}
export async function GET(
_request: Request,
{ params }: { params: Promise<{ locale: string; slug: string }> }
) {
const { locale, slug } = await params
console.log(`[closed-route-handler] ${locale}/${slug}`)
if (
!generatedResources.some(
(resource) => resource.locale === locale && resource.slug === slug
)
) {
throw new Error(`UNKNOWN_CLOSED_HANDLER_RENDERED: ${locale}/${slug}`)
}
return Response.json({ locale, slug })
}
const generatedSlugs = [{ slug: ['one'] }, { slug: ['one', 'two'] }]
export const dynamicParams = false
export function generateStaticParams() {
return generatedSlugs
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string[] }>
}) {
const { slug } = await params
return <p id="catch-all-page">Catch all {slug.join('/')}</p>
}
export function generateStaticParams({
params,
}: {
params: { locale: string }
}) {
return [{ slug: params.locale === 'en' ? 'a' : 'b' }]
}
export default async function Page({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale, slug } = await params
return (
<p id="layout-closed-page">
Layout route {locale}/{slug}
</p>
)
}
export const dynamicParams = false
export function generateStaticParams() {
return [{ locale: 'en' }, { locale: 'fr' }]
}
export default function Layout({ children }: { children: React.ReactNode }) {
return children
}
export default function RootLayout({
children,
}: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export default function NotFound() {
return <p id="closed-route-not-found">This route is not generated</p>
}
const generatedSlugs = [{ slug: [] }, { slug: ['known'] }]
export const dynamicParams = false
export function generateStaticParams() {
return generatedSlugs
}
export default async function Page({
params,
}: {
params: Promise<{ slug?: string[] }>
}) {
const { slug } = await params
return <p id="optional-catch-all-page">Optional {slug?.join('/')}</p>
}
export default function Loading() {
return <p id="closed-route-loading">Loading product</p>
}
const generatedProducts = [
{ locale: 'en', slug: 'a' },
{ locale: 'fr', slug: 'b' },
]
export const dynamicParams = false
export function generateStaticParams() {
return generatedProducts
}
export async function generateMetadata({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale, slug } = await params
console.log(`[closed-route-metadata] ${locale}/${slug}`)
return { title: `${locale}/${slug}` }
}
export default async function Page({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale, slug } = await params
console.log(`[closed-route-page] ${locale}/${slug}`)
if (
!generatedProducts.some(
(product) => product.locale === locale && product.slug === slug
)
) {
throw new Error(`UNKNOWN_CLOSED_ROUTE_RENDERED: ${locale}/${slug}`)
}
return (
<p id="closed-route-page">
Product {locale}/{slug}
</p>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('dynamicParams false with Cache Components', () => {
const { next, isNextStart, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('serves only the exact generated page param tuples', async () => {
for (const pathname of ['/products/en/a', '/products/fr/b']) {
for (let attempt = 0; attempt < 2; attempt++) {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
expect(await response.text()).toContain('id="closed-route-page"')
}
}
const outputIndex = next.cliOutput.length
for (const pathname of ['/products/en/b', '/products/fr/a']) {
for (let attempt = 0; attempt < 2; attempt++) {
const response = await next.fetch(pathname)
const html = await response.text()
expect(response.status).toBe(404)
expect(html).not.toContain('id="closed-route-loading"')
expect(html).not.toContain('id="closed-route-page"')
}
}
const rscResponse = await next.fetch('/products/en/b', {
headers: { rsc: '1' },
})
expect(rscResponse.status).toBe(404)
if (!isNextDeploy) {
const requestOutput = next.cliOutput.slice(outputIndex)
expect(requestOutput).not.toContain('[closed-route-page] en/b')
expect(requestOutput).not.toContain('[closed-route-page] fr/a')
expect(requestOutput).not.toContain('[closed-route-metadata] en/b')
expect(requestOutput).not.toContain('[closed-route-metadata] fr/a')
expect(requestOutput).not.toContain('UNKNOWN_CLOSED_ROUTE_RENDERED')
}
})
it('rejects unknown route handler params before calling GET', async () => {
const knownResponse = await next.fetch('/api/en/a')
expect(knownResponse.status).toBe(200)
expect(await knownResponse.json()).toEqual({ locale: 'en', slug: 'a' })
const outputIndex = next.cliOutput.length
for (let attempt = 0; attempt < 2; attempt++) {
const response = await next.fetch('/api/en/b')
expect(response.status).toBe(404)
}
if (!isNextDeploy) {
const requestOutput = next.cliOutput.slice(outputIndex)
expect(requestOutput).not.toContain('[closed-route-handler] en/b')
expect(requestOutput).not.toContain('UNKNOWN_CLOSED_HANDLER_RENDERED')
}
})
it('closes complete tuples generated across a layout and page', async () => {
for (const pathname of ['/layout-closed/en/a', '/layout-closed/fr/b']) {
expect((await next.fetch(pathname)).status).toBe(200)
}
for (const pathname of ['/layout-closed/en/b', '/layout-closed/fr/a']) {
expect((await next.fetch(pathname)).status).toBe(404)
}
})
it('supports closed catch-all and optional catch-all routes', async () => {
for (const pathname of [
'/catch/one',
'/catch/one/two',
'/optional',
'/optional/known',
]) {
expect((await next.fetch(pathname)).status).toBe(200)
}
for (const pathname of [
'/catch/two',
'/catch/one/three',
'/optional/missing',
]) {
expect((await next.fetch(pathname)).status).toBe(404)
}
})
if (isNextStart) {
it('emits generated tuples and closed dynamic routes in the manifest', async () => {
const manifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
)
expect(manifest.routes).toEqual(
expect.objectContaining({
'/products/en/a': expect.any(Object),
'/products/fr/b': expect.any(Object),
'/api/en/a': expect.any(Object),
'/api/fr/b': expect.any(Object),
'/layout-closed/en/a': expect.any(Object),
'/layout-closed/fr/b': expect.any(Object),
'/catch/one': expect.any(Object),
'/catch/one/two': expect.any(Object),
'/optional': expect.any(Object),
'/optional/known': expect.any(Object),
})
)
for (const route of [
'/products/[locale]/[slug]',
'/api/[locale]/[slug]',
'/layout-closed/[locale]/[slug]',
'/catch/[...slug]',
'/optional/[[...slug]]',
]) {
expect(manifest.dynamicRoutes[route].fallback).toBe(false)
}
})
}
})
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
...@@ -45,10 +45,6 @@ describe('cache-components-segment-configs', () => { ...@@ -45,10 +45,6 @@ describe('cache-components-segment-configs', () => {
'"revalidate" is not compatible with `nextConfig.cacheComponents`. Please remove it.' '"revalidate" is not compatible with `nextConfig.cacheComponents`. Please remove it.'
) )
} else { } else {
expect(next.cliOutput).toContain('./app/dynamic-params/[slug]/page.tsx')
expect(next.cliOutput).toContain(
'"dynamicParams" is not compatible with `nextConfig.cacheComponents`. Please remove it.'
)
expect(next.cliOutput).toContain('./app/dynamic/nested/page.tsx') expect(next.cliOutput).toContain('./app/dynamic/nested/page.tsx')
expect(next.cliOutput).toContain('./app/dynamic/page.tsx') expect(next.cliOutput).toContain('./app/dynamic/page.tsx')
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
...@@ -77,6 +73,9 @@ describe('cache-components-segment-configs', () => { ...@@ -77,6 +73,9 @@ describe('cache-components-segment-configs', () => {
expect(next.cliOutput).toContain('./app/runtime/page.tsx') expect(next.cliOutput).toContain('./app/runtime/page.tsx')
expect(next.cliOutput).toContain('./app/metadata/icon.tsx') expect(next.cliOutput).toContain('./app/metadata/icon.tsx')
expect(next.cliOutput).toContain(
'"dynamicParams" is not compatible with `nextConfig.cacheComponents`. Please remove it.'
)
expect(next.cliOutput).toContain('./app/metadata/apple-icon.tsx') expect(next.cliOutput).toContain('./app/metadata/apple-icon.tsx')
expect(next.cliOutput).toContain('./app/metadata/opengraph-image.tsx') expect(next.cliOutput).toContain('./app/metadata/opengraph-image.tsx')
expect(next.cliOutput).toContain('./app/metadata/twitter-image.tsx') expect(next.cliOutput).toContain('./app/metadata/twitter-image.tsx')
......
export const runtime = 'edge' export const runtime = 'edge'
export const dynamicParams = false
export default function Icon() { export default function Icon() {
return new Response('This metadata route uses `export const runtime`.') return new Response('This metadata route uses `export const runtime`.')
......
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