Unverified Commit d7608f7e authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Fix prerendering of interception routes with generateStaticParams (#85835)

## What

Fixes a bug where interception routes in parallel slots could not be
prerendered using `generateStaticParams`, causing 404 responses when
these routes were accessed directly.

## Why

**The Problem:**

Interception routes like `app/@modal/(.)photo/[id]/page.tsx` could not
be prerendered even when they exported `generateStaticParams`. This was
because the static path generation code only examined "children"
segments in the loader tree, completely missing segments from parallel
routes (like `@modal`) that actually contribute to the pathname.

**Root Cause:**

The previous implementation used `childrenRouteParamSegments` which only
traversed the `children` branch of the loader tree:

```typescript
// OLD: Only looked at children
const childrenRouteParamSegments = [...segments from children only...]

// This missed parallel routes like @modal that have dynamic segments
```

For a route structure like:
```
app/
  [username]/
    page.tsx
  @modal/
    (.)[username]/
      [id]/
        page.tsx  // ← This route's segments were MISSED
```

The build system couldn't discover the `[id]` parameter in the parallel
route because it never traversed that branch of the tree.

## How

**Solution:**

Introduces `extractPathnameSegments()` which properly traverses the
ENTIRE loader tree (not just children) to find ALL segments that
contribute to the pathname:

1. **BFS Traversal**: Explores both `children` AND all parallel route
slots (e.g., `@modal`, `@sidebar`)

2. **Depth Tracking**: Correctly tracks URL depth by:
   - Skipping route groups `(marketing)` - not in URL
   - Skipping parallel markers `@modal` - not in URL
   - Including interception markers `(.)photo` - ARE in URL

3. **Prefix Validation**: Ensures static segments match the target
pathname before including dynamic segments

4. **Complete Parameter Discovery**: Returns all segments that
contribute to pathname construction, regardless of which tree branch
they're in

**Example:**

For `app/@modal/(.)photo/[id]/page.tsx`:
- Old: Missed the `[id]` parameter entirely
- New: Discovers `[id]` and enables prerendering with
`generateStaticParams`

## Changes

**New Module**: `extract-pathname-segments.ts` (192 lines)
- Core algorithm for traversing loader tree and extracting pathname
segments
- Handles complex cases: parallel routes, interception routes, route
groups
- Well-documented with examples and algorithm explanation

**Comprehensive Tests**: `extract-pathname-segments.test.ts` (897 lines)
- Tests for simple cases, nested structures, parallel routes
- Interception route handling in various configurations
- Route group behavior and edge cases
- Depth tracking validation

**Integration**: `static-paths/app.ts`
- Replaced `childrenRouteParamSegments` with `extractPathnameSegments()`
- Updated pathname construction to use segments from parallel routes
- Maintained backward compatibility

**E2E Test**: Added test validating prerendering works for intercepted
routes

## Test Plan

The new E2E test verifies:
```typescript
it('should prerender a dynamic intercepted route', async () => {
  // Verifies build output contains the prerendered interception route
  expect(next.cliOutput).toContain('/(.)john/1')
  // Verifies it doesn't generate the non-intercepted path
  expect(next.cliOutput).not.toContain('/john/1')
})
```

## Impact

**Before**: Interception routes with dynamic segments returned 404 when
accessed directly, even with `generateStaticParams`

**After**: These routes are properly prerendered at build time and
return correct responses
parent fedee7d7
...@@ -927,5 +927,8 @@ ...@@ -927,5 +927,8 @@
"926": "Optional route parameters are not yet supported (\"[%s]\") in route \"%s\".", "926": "Optional route parameters are not yet supported (\"[%s]\") in route \"%s\".",
"927": "No debug targets found", "927": "No debug targets found",
"928": "Unable to get server address", "928": "Unable to get server address",
"929": "No pages or app directory found." "929": "No pages or app directory found.",
"930": "Expected a dynamic route, but got a static route: %s",
"931": "Unexpected empty path segments match for a route \"%s\" with param \"%s\" of type \"%s\"",
"932": "Could not resolve param value for segment: %s"
} }
...@@ -17,9 +17,6 @@ import { ...@@ -17,9 +17,6 @@ import {
getLayoutOrPageModule, getLayoutOrPageModule,
type LoaderTree, type LoaderTree,
} from '../../../server/lib/app-dir-module' } from '../../../server/lib/app-dir-module'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import type { FallbackRouteParam } from '../../static-paths/types'
import { createFallbackRouteParam } from '../../static-paths/utils'
import type { DynamicParamTypes } from '../../../shared/lib/app-router-types' import type { DynamicParamTypes } from '../../../shared/lib/app-router-types'
type GenerateStaticParams = (options: { params?: Params }) => Promise<Params[]> type GenerateStaticParams = (options: { params?: Params }) => Promise<Params[]>
...@@ -63,14 +60,7 @@ export type AppSegment = { ...@@ -63,14 +60,7 @@ export type AppSegment = {
paramType: DynamicParamTypes | undefined paramType: DynamicParamTypes | undefined
filePath: string | undefined filePath: string | undefined
config: AppSegmentConfig | undefined config: AppSegmentConfig | undefined
isDynamicSegment: boolean
generateStaticParams: GenerateStaticParams | undefined generateStaticParams: GenerateStaticParams | undefined
/**
* Whether this segment is a parallel route segment or descends from a
* parallel route segment.
*/
isParallelRouteSegment: boolean | undefined
} }
/** /**
...@@ -82,35 +72,28 @@ export type AppSegment = { ...@@ -82,35 +72,28 @@ export type AppSegment = {
async function collectAppPageSegments(routeModule: AppPageRouteModule) { async function collectAppPageSegments(routeModule: AppPageRouteModule) {
// We keep track of unique segments, since with parallel routes, it's possible // We keep track of unique segments, since with parallel routes, it's possible
// to see the same segment multiple times. // to see the same segment multiple times.
const uniqueSegments = new Map<string, AppSegment>() const segments: AppSegment[] = []
// Queue will store tuples of [loaderTree, currentSegments, isParallelRouteSegment] // Queue will store loader trees.
type QueueItem = [ const queue: LoaderTree[] = [routeModule.userland.loaderTree]
loaderTree: LoaderTree,
currentSegments: AppSegment[],
isParallelRouteSegment: boolean,
]
const queue: QueueItem[] = [[routeModule.userland.loaderTree, [], false]]
while (queue.length > 0) { while (queue.length > 0) {
const [loaderTree, currentSegments, isParallelRouteSegment] = queue.shift()! const loaderTree = queue.shift()!
const [name, parallelRoutes] = loaderTree const [name, parallelRoutes] = loaderTree
// Process current node // Process current node
const { mod: userland, filePath } = await getLayoutOrPageModule(loaderTree) const { mod: userland, filePath } = await getLayoutOrPageModule(loaderTree)
const isClientComponent = userland && isClientReference(userland) const isClientComponent = userland && isClientReference(userland)
const { param: paramName, type: paramType } = getSegmentParam(name) ?? {} const param = getSegmentParam(name)
const segment: AppSegment = { const segment: AppSegment = {
name, name,
paramName, paramName: param?.paramName,
paramType, paramType: param?.paramType,
filePath, filePath,
config: undefined, config: undefined,
isDynamicSegment: !!paramName,
generateStaticParams: undefined, generateStaticParams: undefined,
isParallelRouteSegment,
} }
// Only server components can have app segment configurations // Only server components can have app segment configurations
...@@ -118,43 +101,28 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) { ...@@ -118,43 +101,28 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) {
attach(segment, userland, routeModule.definition.pathname) attach(segment, userland, routeModule.definition.pathname)
} }
// Create a unique key for the segment // If this segment doesn't already exist, then add it to the segments array.
const segmentKey = getSegmentKey(segment) // The list of segments is short so we just use a list traversal to check
if (!uniqueSegments.has(segmentKey)) { // for duplicates and spare us needing to maintain the string key.
uniqueSegments.set(segmentKey, segment) if (
} segments.every(
(s) =>
const updatedSegments = [...currentSegments, segment] s.name !== segment.name ||
s.paramName !== segment.paramName ||
// If this is a page segment, we've reached a leaf node s.paramType !== segment.paramType ||
if (name === PAGE_SEGMENT_KEY) { s.filePath !== segment.filePath
// Add all segments in the current path, preferring non-parallel segments )
updatedSegments.forEach((seg) => { ) {
const key = getSegmentKey(seg) segments.push(segment)
if (!uniqueSegments.has(key)) {
uniqueSegments.set(key, seg)
}
})
} }
// Add all parallel routes to the queue // Add all parallel routes to the queue
for (const parallelRouteKey in parallelRoutes) { for (const parallelRoute of Object.values(parallelRoutes)) {
const parallelRoute = parallelRoutes[parallelRouteKey] queue.push(parallelRoute)
queue.push([
parallelRoute,
updatedSegments,
// A parallel route segment is one that descends from a segment that is
// not children or descends from a parallel route segment.
isParallelRouteSegment || parallelRouteKey !== 'children',
])
} }
} }
return Array.from(uniqueSegments.values()) return segments
}
function getSegmentKey(segment: AppSegment) {
return `${segment.name}-${segment.filePath ?? ''}-${segment.paramName ?? ''}-${segment.isParallelRouteSegment ? 'pr' : 'np'}`
} }
/** /**
...@@ -174,17 +142,15 @@ function collectAppRouteSegments( ...@@ -174,17 +142,15 @@ function collectAppRouteSegments(
// Generate all the segments. // Generate all the segments.
const segments: AppSegment[] = parts.map((name) => { const segments: AppSegment[] = parts.map((name) => {
const { param: paramName, type: paramType } = getSegmentParam(name) ?? {} const param = getSegmentParam(name)
return { return {
name, name,
paramName, paramName: param?.paramName,
paramType, paramType: param?.paramType,
filePath: undefined, filePath: undefined,
isDynamicSegment: !!paramName,
config: undefined, config: undefined,
generateStaticParams: undefined, generateStaticParams: undefined,
isParallelRouteSegment: undefined,
} satisfies AppSegment } satisfies AppSegment
}) })
...@@ -221,55 +187,3 @@ export function collectSegments( ...@@ -221,55 +187,3 @@ export function collectSegments(
'Expected a route module to be one of app route or page' 'Expected a route module to be one of app route or page'
) )
} }
/**
* Collects the fallback route params for a given app page route module. This is
* a variant of the `collectSegments` function that only collects the fallback
* route params without importing anything.
*
* @param routeModule the app page route module
* @returns the fallback route params for the app page route module
*/
export function collectFallbackRouteParams(
routeModule: AppPageRouteModule
): readonly FallbackRouteParam[] {
const uniqueSegments = new Map<string, FallbackRouteParam>()
// Queue will store tuples of [loaderTree, isParallelRouteSegment]
type QueueItem = [loaderTree: LoaderTree, isParallelRouteSegment: boolean]
const queue: QueueItem[] = [[routeModule.userland.loaderTree, false]]
while (queue.length > 0) {
const [loaderTree, isParallelRouteSegment] = queue.shift()!
const [name, parallelRoutes] = loaderTree
// Handle this segment (if it's a dynamic segment param).
const segmentParam = getSegmentParam(name)
if (segmentParam) {
const key = `${name}-${segmentParam.param}-${isParallelRouteSegment ? 'pr' : 'np'}`
if (!uniqueSegments.has(key)) {
uniqueSegments.set(
key,
createFallbackRouteParam(
segmentParam.param,
segmentParam.type,
isParallelRouteSegment
)
)
}
}
// Add all of this segment's parallel routes to the queue.
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
queue.push([
parallelRoute,
// A parallel route segment is one that descends from a segment that is
// not children or descends from a parallel route segment.
isParallelRouteSegment || parallelRouteKey !== 'children',
])
}
}
return Array.from(uniqueSegments.values())
}
...@@ -17,9 +17,9 @@ function collectAppPageRootParamKeys( ...@@ -17,9 +17,9 @@ function collectAppPageRootParamKeys(
const [name, parallelRoutes, modules] = current const [name, parallelRoutes, modules] = current
// If this is a dynamic segment, then we collect the param. // If this is a dynamic segment, then we collect the param.
const param = getSegmentParam(name)?.param const paramName = getSegmentParam(name)?.paramName
if (param) { if (paramName) {
rootParams.push(param) rootParams.push(paramName)
} }
// If this has a layout module, then we've found the root layout because // If this has a layout module, then we've found the root layout because
......
This diff is collapsed.
import type { LoaderTree } from '../../../server/lib/app-dir-module'
import type { Params } from '../../../server/request/params'
import type { DynamicParamTypes } from '../../../shared/lib/app-router-types'
import {
parseAppRouteSegment,
type NormalizedAppRoute,
type NormalizedAppRouteSegment,
} from '../../../shared/lib/router/routes/app'
import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree'
import { resolveParamValue } from '../../../shared/lib/router/utils/resolve-param-value'
/**
* Validates that the static segments in currentPath match the corresponding
* segments in targetSegments. This ensures we only extract dynamic parameters
* that are part of the target pathname structure.
*
* Segments are compared literally - interception markers like "(.)photo" are
* part of the pathname and must match exactly.
*
* @example
* // Matching paths
* currentPath: ['blog', '(.)photo']
* targetSegments: ['blog', '(.)photo', '[id]']
* → Returns true (both static segments match exactly)
*
* @example
* // Non-matching paths
* currentPath: ['blog', '(.)photo']
* targetSegments: ['blog', 'photo', '[id]']
* → Returns false (segments don't match - marker is part of pathname)
*
* @param currentPath - The accumulated path segments from the loader tree
* @param targetSegments - The target pathname split into segments
* @returns true if all static segments match, false otherwise
*/
function validatePrefixMatch(
currentPath: NormalizedAppRouteSegment[],
route: NormalizedAppRoute
): boolean {
for (let i = 0; i < currentPath.length; i++) {
const pathSegment = currentPath[i]
const targetPathSegment = route.segments[i]
// Type mismatch - one is static, one is dynamic
if (pathSegment.type !== targetPathSegment.type) {
return false
}
// One has an interception marker, the other doesn't.
if (
pathSegment.interceptionMarker !== targetPathSegment.interceptionMarker
) {
return false
}
// Both are static but names don't match
if (
pathSegment.type === 'static' &&
targetPathSegment.type === 'static' &&
pathSegment.name !== targetPathSegment.name
) {
return false
}
// Both are dynamic but param names don't match
else if (
pathSegment.type === 'dynamic' &&
targetPathSegment.type === 'dynamic' &&
pathSegment.param.paramType !== targetPathSegment.param.paramType &&
pathSegment.param.paramName !== targetPathSegment.param.paramName
) {
return false
}
}
return true
}
/**
* Extracts pathname route param segments from a loader tree and resolves
* parameter values from static segments in the route.
*
* @param loaderTree - The loader tree structure containing route hierarchy
* @param route - The target route to match against
* @returns Object containing pathname route param segments and resolved params
*/
export function extractPathnameRouteParamSegmentsFromLoaderTree(
loaderTree: LoaderTree,
route: NormalizedAppRoute
): {
pathnameRouteParamSegments: Array<{
readonly name: string
readonly paramName: string
readonly paramType: DynamicParamTypes
}>
params: Params
} {
const pathnameRouteParamSegments: Array<{
readonly name: string
readonly paramName: string
readonly paramType: DynamicParamTypes
}> = []
const params: Params = {}
// BFS traversal with depth and path tracking
const queue: Array<{
tree: LoaderTree
depth: number
currentPath: NormalizedAppRouteSegment[]
}> = [{ tree: loaderTree, depth: 0, currentPath: [] }]
while (queue.length > 0) {
const { tree, depth, currentPath } = queue.shift()!
const { segment, parallelRoutes } = parseLoaderTree(tree)
// Build the path for the current node
let updatedPath = currentPath
let nextDepth = depth
const appSegment = parseAppRouteSegment(segment)
// Only add to path if it's a real segment that appears in the URL
// Route groups and parallel markers don't contribute to URL pathname
if (
appSegment &&
appSegment.type !== 'route-group' &&
appSegment.type !== 'parallel-route'
) {
updatedPath = [...currentPath, appSegment]
nextDepth = depth + 1
}
// Check if this segment has a param and matches the target pathname at this depth
if (appSegment?.type === 'dynamic') {
const { paramName, paramType } = appSegment.param
// Check if this segment is at the correct depth in the target pathname
// A segment matches if:
// 1. There's a dynamic segment at this depth in the pathname
// 2. The parameter names match (e.g., [id] matches [id], not [category])
// 3. The static segments leading up to this point match (prefix check)
if (depth < route.segments.length) {
const targetSegment = route.segments[depth]
// Match if the target pathname has a dynamic segment at this depth
if (targetSegment.type === 'dynamic') {
// Check that parameter names match exactly
// This prevents [category] from matching against /[id]
if (paramName !== targetSegment.param.paramName) {
continue // Different param names, skip this segment
}
// Validate that the path leading up to this dynamic segment matches
// the target pathname. This prevents false matches like extracting
// [slug] from "/news/[slug]" when the tree has "/blog/[slug]"
if (validatePrefixMatch(currentPath, route)) {
pathnameRouteParamSegments.push({
name: segment,
paramName,
paramType,
})
}
}
}
// Resolve parameter value if it's not already known.
if (!params.hasOwnProperty(paramName)) {
const paramValue = resolveParamValue(
paramName,
paramType,
depth,
route,
params
)
if (paramValue !== undefined) {
params[paramName] = paramValue
}
}
}
// Continue traversing all parallel routes to find matching segments
for (const parallelRoute of Object.values(parallelRoutes)) {
queue.push({
tree: parallelRoute,
depth: nextDepth,
currentPath: updatedPath,
})
}
}
return { pathnameRouteParamSegments, params }
}
...@@ -27,12 +27,6 @@ export type FallbackRouteParam = { ...@@ -27,12 +27,6 @@ export type FallbackRouteParam = {
* The type of the param. * The type of the param.
*/ */
readonly paramType: DynamicParamTypes readonly paramType: DynamicParamTypes
/**
* Whether this is a parallel route param or descends from a parallel route
* param.
*/
readonly isParallelRouteParam: boolean
} }
type FallbackPrerenderedRoute = { type FallbackPrerenderedRoute = {
...@@ -41,8 +35,9 @@ type FallbackPrerenderedRoute = { ...@@ -41,8 +35,9 @@ type FallbackPrerenderedRoute = {
readonly encodedPathname: string readonly encodedPathname: string
/** /**
* The fallback route params for the route. This includes both the parallel * The fallback route params for the route. This includes all route parameters
* route params and the non-parallel route params. * that are unknown at build time, from both the main children route and any
* parallel routes.
*/ */
readonly fallbackRouteParams: readonly FallbackRouteParam[] readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined readonly fallbackMode: FallbackMode | undefined
......
This diff is collapsed.
import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { Params } from '../../server/request/params'
import type { AppPageRouteModule } from '../../server/route-modules/app-page/module.compiled'
import type { AppRouteRouteModule } from '../../server/route-modules/app-route/module.compiled'
import { isAppPageRouteModule } from '../../server/route-modules/checks'
import type { DynamicParamTypes } from '../../shared/lib/app-router-types' import type { DynamicParamTypes } from '../../shared/lib/app-router-types'
import {
parseAppRouteSegment,
type NormalizedAppRoute,
} from '../../shared/lib/router/routes/app'
import { parseLoaderTree } from '../../shared/lib/router/utils/parse-loader-tree'
import type { AppSegment } from '../segment-config/app/app-segments'
import { extractPathnameRouteParamSegmentsFromLoaderTree } from './app/extract-pathname-route-param-segments-from-loader-tree'
import { resolveParamValue } from '../../shared/lib/router/utils/resolve-param-value'
import type { FallbackRouteParam } from './types' import type { FallbackRouteParam } from './types'
/** /**
...@@ -33,17 +46,144 @@ export function normalizePathname(pathname: string) { ...@@ -33,17 +46,144 @@ export function normalizePathname(pathname: string) {
} }
/** /**
* Creates a fallback route param. * Extracts segments that contribute to the pathname by traversing the loader tree
* based on the route module type.
* *
* @param paramName - The name of the param. * @param routeModule - The app route module (page or route handler)
* @param isParallelRouteParam - Whether this is a parallel route param or * @param segments - Array of AppSegment objects collected from the route
* descends from a parallel route param. * @param page - The target pathname to match against, INCLUDING interception
* @returns The fallback route param. * markers (e.g., "/blog/[slug]", "/(.)photo/[id]")
* @returns Array of segments with param info that contribute to the pathname
*/ */
export function createFallbackRouteParam( export function extractPathnameRouteParamSegments(
paramName: string, routeModule: AppRouteRouteModule | AppPageRouteModule,
paramType: DynamicParamTypes, segments: readonly Readonly<AppSegment>[],
isParallelRouteParam: boolean route: NormalizedAppRoute
): FallbackRouteParam { ): Array<{
return { paramName, paramType, isParallelRouteParam } readonly name: string
readonly paramName: string
readonly paramType: DynamicParamTypes
}> {
// For AppPageRouteModule, use the loaderTree traversal approach
if (isAppPageRouteModule(routeModule)) {
const { pathnameRouteParamSegments } =
extractPathnameRouteParamSegmentsFromLoaderTree(
routeModule.userland.loaderTree,
route
)
return pathnameRouteParamSegments
}
return extractPathnameRouteParamSegmentsFromSegments(segments)
}
export function extractPathnameRouteParamSegmentsFromSegments(
segments: readonly Readonly<AppSegment>[]
): Array<{
readonly name: string
readonly paramName: string
readonly paramType: DynamicParamTypes
}> {
// TODO: should we consider what values are already present in the page?
// For AppRouteRouteModule, filter the segments array to get the route params
// that contribute to the pathname.
const result: Array<{
readonly name: string
readonly paramName: string
readonly paramType: DynamicParamTypes
}> = []
for (const segment of segments) {
// Skip segments without param info.
if (!segment.paramName || !segment.paramType) continue
// Collect all the route param keys that contribute to the pathname.
result.push({
name: segment.name,
paramName: segment.paramName,
paramType: segment.paramType,
})
}
return result
}
/**
* Resolves all route parameters from the loader tree. This function uses
* tree-based traversal to correctly handle the hierarchical structure of routes
* and accurately determine parameter values based on their depth in the tree.
*
* This processes both regular route parameters (from the main children route) and
* parallel route parameters (from slots like @modal, @sidebar).
*
* Unlike interpolateParallelRouteParams (which has a complete URL at runtime),
* this build-time function determines which route params are unknown.
* The pathname may contain placeholders like [slug], making it incomplete.
*
* @param loaderTree - The loader tree structure containing route hierarchy
* @param params - The current route parameters object (will be mutated)
* @param route - The current route being processed
* @param fallbackRouteParams - Array of fallback route parameters (will be mutated)
*/
export function resolveRouteParamsFromTree(
loaderTree: LoaderTree,
params: Params,
route: NormalizedAppRoute,
fallbackRouteParams: FallbackRouteParam[]
): void {
// Stack-based traversal with depth tracking
const stack: Array<{
tree: LoaderTree
depth: number
}> = [{ tree: loaderTree, depth: 0 }]
while (stack.length > 0) {
const { tree, depth } = stack.pop()!
const { segment, parallelRoutes } = parseLoaderTree(tree)
const appSegment = parseAppRouteSegment(segment)
// If this segment is a route parameter, then we should process it if it's
// not already known and is not already marked as a fallback route param.
if (
appSegment?.type === 'dynamic' &&
!params.hasOwnProperty(appSegment.param.paramName) &&
!fallbackRouteParams.some(
(param) => param.paramName === appSegment.param.paramName
)
) {
const { paramName, paramType } = appSegment.param
const paramValue = resolveParamValue(
paramName,
paramType,
depth,
route,
params
)
if (paramValue !== undefined) {
params[paramName] = paramValue
} else if (paramType !== 'optional-catchall') {
// If we couldn't resolve the param, mark it as a fallback
fallbackRouteParams.push({ paramName, paramType })
}
}
// Calculate next depth - increment if this is not a route group and not empty
let nextDepth = depth
if (
appSegment &&
appSegment.type !== 'route-group' &&
appSegment.type !== 'parallel-route'
) {
nextDepth++
}
// Add all parallel routes to the stack for processing.
for (const parallelRoute of Object.values(parallelRoutes)) {
stack.push({ tree: parallelRoute, depth: nextDepth })
}
}
} }
...@@ -78,6 +78,7 @@ import { formatIssue, isRelevantWarning } from '../shared/lib/turbopack/utils' ...@@ -78,6 +78,7 @@ import { formatIssue, isRelevantWarning } from '../shared/lib/turbopack/utils'
import type { TurbopackResult } from './swc/types' import type { TurbopackResult } from './swc/types'
import type { FunctionsConfigManifest, ManifestRoute } from './index' import type { FunctionsConfigManifest, ManifestRoute } from './index'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { parseAppRoute } from '../shared/lib/router/routes/app'
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
...@@ -870,14 +871,17 @@ export async function isPageStatic({ ...@@ -870,14 +871,17 @@ export async function isPageStatic({
appConfig.revalidate = 0 appConfig.revalidate = 0
} }
const route = parseAppRoute(page, true)
// If the page is dynamic and we're not in edge runtime, then we need to // If the page is dynamic and we're not in edge runtime, then we need to
// build the static paths. The edge runtime doesn't support static // build the static paths. The edge runtime doesn't support static
// paths. // paths.
if (isDynamicRoute(page) && !pathIsEdgeRuntime) { if (route.dynamicSegments.length > 0 && !pathIsEdgeRuntime) {
;({ prerenderedRoutes, fallbackMode: prerenderFallbackMode } = ;({ prerenderedRoutes, fallbackMode: prerenderFallbackMode } =
await buildAppStaticPaths({ await buildAppStaticPaths({
dir, dir,
page, page,
route,
cacheComponents, cacheComponents,
authInterrupts, authInterrupts,
segments, segments,
......
...@@ -159,7 +159,7 @@ function getParamsFromLayoutFilePath({ ...@@ -159,7 +159,7 @@ function getParamsFromLayoutFilePath({
for (const segment of segments) { for (const segment of segments) {
const param = getSegmentParam(segment) const param = getSegmentParam(segment)
if (param !== null) { if (param !== null) {
paramNames.push(param.param) paramNames.push(param.paramName)
} }
} }
return paramNames return paramNames
......
...@@ -408,8 +408,8 @@ function makeGetDynamicParamFromSegment( ...@@ -408,8 +408,8 @@ function makeGetDynamicParamFromSegment(
if (!segmentParam) { if (!segmentParam) {
return null return null
} }
const segmentKey = segmentParam.param const segmentKey = segmentParam.paramName
const dynamicParamType = dynamicParamTypes[segmentParam.type] const dynamicParamType = dynamicParamTypes[segmentParam.paramType]
return getDynamicParam( return getDynamicParam(
interpolatedParams, interpolatedParams,
segmentKey, segmentKey,
......
...@@ -307,5 +307,5 @@ const canSegmentBeOverridden = ( ...@@ -307,5 +307,5 @@ const canSegmentBeOverridden = (
return false return false
} }
return getSegmentParam(existingSegment)?.param === segment[0] return getSegmentParam(existingSegment)?.paramName === segment[0]
} }
...@@ -20,6 +20,7 @@ import { buildPagesStaticPaths } from '../../build/static-paths/pages' ...@@ -20,6 +20,7 @@ import { buildPagesStaticPaths } from '../../build/static-paths/pages'
import { createIncrementalCache } from '../../export/helpers/create-incremental-cache' import { createIncrementalCache } from '../../export/helpers/create-incremental-cache'
import type { AppPageRouteModule } from '../route-modules/app-page/module' import type { AppPageRouteModule } from '../route-modules/app-page/module'
import type { AppRouteRouteModule } from '../route-modules/app-route/module' import type { AppRouteRouteModule } from '../route-modules/app-route/module'
import { parseAppRoute } from '../../shared/lib/router/routes/app'
type RuntimeConfig = { type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined pprConfig: ExperimentalPPRConfig | undefined
...@@ -111,6 +112,13 @@ export async function loadStaticPaths({ ...@@ -111,6 +112,13 @@ export async function loadStaticPaths({
routeModule as AppPageRouteModule | AppRouteRouteModule routeModule as AppPageRouteModule | AppRouteRouteModule
) )
const route = parseAppRoute(pathname, true)
if (route.dynamicSegments.length === 0) {
throw new InvariantError(
`Expected a dynamic route, but got a static route: ${pathname}`
)
}
const isRoutePPREnabled = const isRoutePPREnabled =
isAppPageRouteModule(routeModule) && isAppPageRouteModule(routeModule) &&
checkIsRoutePPREnabled(config.pprConfig) checkIsRoutePPREnabled(config.pprConfig)
...@@ -120,6 +128,7 @@ export async function loadStaticPaths({ ...@@ -120,6 +128,7 @@ export async function loadStaticPaths({
return buildAppStaticPaths({ return buildAppStaticPaths({
dir, dir,
page: pathname, page: pathname,
route,
cacheComponents: config.cacheComponents, cacheComponents: config.cacheComponents,
segments, segments,
distDir, distDir,
......
...@@ -115,7 +115,10 @@ export type NormalizedAppRoute = Omit<AppRoute, 'normalized' | 'segments'> & { ...@@ -115,7 +115,10 @@ export type NormalizedAppRoute = Omit<AppRoute, 'normalized' | 'segments'> & {
} }
export function isNormalizedAppRoute( export function isNormalizedAppRoute(
route: AppRoute route: InterceptionAppRoute
): route is NormalizedInterceptionAppRoute
export function isNormalizedAppRoute(
route: AppRoute | InterceptionAppRoute
): route is NormalizedAppRoute { ): route is NormalizedAppRoute {
return route.normalized return route.normalized
} }
......
export default function Page() { export default function Page() {
return 'intercepted' return 'intercepted'
} }
export async function generateStaticParams() {
return [{ username: 'john', id: '1' }]
}
...@@ -146,6 +146,16 @@ describe('interception-dynamic-segment', () => { ...@@ -146,6 +146,16 @@ describe('interception-dynamic-segment', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('x-nextjs-cache')).toBe('HIT') expect(res.headers.get('x-nextjs-cache')).toBe('HIT')
}) })
it('should prerender a dynamic intercepted route', async () => {
if (process.env.__NEXT_CACHE_COMPONENTS === 'true') {
expect(next.cliOutput).toContain('/(.)[username]/[id]')
expect(next.cliOutput).toContain('/(.)john/[id]')
}
expect(next.cliOutput).toContain('/(.)john/1')
expect(next.cliOutput).not.toContain('/john/1')
})
} }
if (!isNextDev) { if (!isNextDev) {
......
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