Unverified Commit d3de9bce authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Embed static sibling info in route tree (#88692)

This change adds infrastructure for a planned client-side optimization
where the router can infer route structure from previously prefetched
routes, avoiding redundant route tree requests.

When the client prefetches /blog/post-1 and learns the route structure
is /blog/[slug], it could potentially reuse that knowledge for
/blog/post-2 without another server roundtrip. However, if a static
route like /blog/featured exists at the same level, the client needs to
know NOT to apply the dynamic template for that URL.

staticSiblings provides this information. When a dynamic segment like
[slug] has static siblings (e.g., "featured", "archive"), the server
includes them in the prefetch response. The client can then check
whether an incoming URL matches a known static sibling, and if so,
recognize that the previously learned route structure does not apply.
parent fc65fbb0
...@@ -328,6 +328,7 @@ impl AppPageLoaderTreeBuilder { ...@@ -328,6 +328,7 @@ impl AppPageLoaderTreeBuilder {
parallel_routes, parallel_routes,
modules, modules,
global_metadata, global_metadata,
static_siblings,
} = loader_tree; } = loader_tree;
writeln!( writeln!(
...@@ -399,7 +400,15 @@ impl AppPageLoaderTreeBuilder { ...@@ -399,7 +400,15 @@ impl AppPageLoaderTreeBuilder {
self.loader_tree_code += &modules_code; self.loader_tree_code += &modules_code;
write!(self.loader_tree_code, "}}]")?; // Add static siblings for dynamic segments. An empty array means "known
// to have no siblings" which is distinct from not outputting the field
// (unknown). Turbopack always knows all siblings since it builds the full
// directory tree.
write!(
self.loader_tree_code,
"}}, {}]",
StringifyJs(static_siblings)
)?;
Ok(()) Ok(())
} }
......
...@@ -201,6 +201,84 @@ struct PlainDirectoryTree { ...@@ -201,6 +201,84 @@ struct PlainDirectoryTree {
/// key is e.g. "dashboard", "(dashboard)", "@slot" /// key is e.g. "dashboard", "(dashboard)", "@slot"
pub subdirectories: BTreeMap<RcStr, PlainDirectoryTree>, pub subdirectories: BTreeMap<RcStr, PlainDirectoryTree>,
pub modules: AppDirModules, pub modules: AppDirModules,
/// Flattened URL tree with route groups and parallel routes transparent.
pub url_tree: UrlSegmentTree,
}
/// A tree representing the URL segment structure, with route groups and parallel
/// routes flattened out. This provides a unified view of all segments at each URL
/// level, regardless of which route group they're defined in.
///
/// For example, given this directory structure:
///
/// app/
/// ├── (group1)/
/// │ └── products/
/// │ └── sale/
/// └── (group2)/
/// └── products/
/// └── [id]/
///
/// The UrlSegmentTree would be:
///
/// (root)
/// └── products/
/// ├── sale/
/// └── [id]/
///
/// This makes it easy to find all siblings at a given URL level.
#[derive(Clone, Debug, Default, PartialEq, Eq, TraceRawVcs, NonLocalValue, Encode, Decode)]
struct UrlSegmentTree {
pub children: BTreeMap<RcStr, UrlSegmentTree>,
}
impl UrlSegmentTree {
fn static_children(&self) -> Vec<RcStr> {
self.children
.keys()
.filter(|name| !is_dynamic_segment(name))
.cloned()
.collect()
}
fn get_child(&self, segment: &str) -> Option<&UrlSegmentTree> {
self.children.get(segment)
}
}
fn build_url_segment_tree_from_subdirs(
subdirs: &BTreeMap<RcStr, PlainDirectoryTree>,
) -> UrlSegmentTree {
let mut result = UrlSegmentTree::default();
build_url_segment_tree_recursive(subdirs, &mut result);
result
}
/// Recursively builds the URL segment tree by accumulating children at each
/// URL level. Segments from different route groups that share the same URL path
/// are merged together.
///
/// Example: `(group1)/products/sale/` and `(group2)/products/[id]/` both
/// contribute to a single `products/` node containing both `sale/` and `[id]/`.
fn build_url_segment_tree_recursive(
subdirs: &BTreeMap<RcStr, PlainDirectoryTree>,
result: &mut UrlSegmentTree,
) {
for (name, subtree) in subdirs {
if is_url_transparent_segment(name) {
// Transparent segments (route groups, parallel routes) don't create
// a new URL level. Recurse with the same `result` so their children
// are accumulated at the current level.
build_url_segment_tree_recursive(&subtree.subdirectories, result);
} else {
// Non-transparent segments create a new URL level. Get or create a
// child node for this segment, then recurse to accumulate its children.
// Using `or_default()` ensures that if this segment was already added
// from a different route group, we merge into it rather than replace.
let child = result.children.entry(name.clone()).or_default();
build_url_segment_tree_recursive(&subtree.subdirectories, child);
}
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -213,9 +291,12 @@ impl DirectoryTree { ...@@ -213,9 +291,12 @@ impl DirectoryTree {
subdirectories.insert(name.clone(), subdirectory.into_plain().owned().await?); subdirectories.insert(name.clone(), subdirectory.into_plain().owned().await?);
} }
let url_tree = build_url_segment_tree_from_subdirs(&subdirectories);
Ok(PlainDirectoryTree { Ok(PlainDirectoryTree {
subdirectories, subdirectories,
modules: self.modules.clone(), modules: self.modules.clone(),
url_tree,
} }
.cell()) .cell())
} }
...@@ -392,6 +473,10 @@ pub struct AppPageLoaderTree { ...@@ -392,6 +473,10 @@ pub struct AppPageLoaderTree {
pub parallel_routes: FxIndexMap<RcStr, AppPageLoaderTree>, pub parallel_routes: FxIndexMap<RcStr, AppPageLoaderTree>,
pub modules: AppDirModules, pub modules: AppDirModules,
pub global_metadata: ResolvedVc<GlobalMetadata>, pub global_metadata: ResolvedVc<GlobalMetadata>,
/// For dynamic segments, contains the list of static sibling segments that
/// exist at the same URL path level. Used by the client router to determine
/// if a prefetch can be reused.
pub static_siblings: Vec<RcStr>,
} }
impl AppPageLoaderTree { impl AppPageLoaderTree {
...@@ -543,6 +628,17 @@ fn is_group_route(name: &str) -> bool { ...@@ -543,6 +628,17 @@ fn is_group_route(name: &str) -> bool {
name.starts_with('(') && name.ends_with(')') name.starts_with('(') && name.ends_with(')')
} }
/// Returns true if this segment is "transparent" from a URL perspective.
/// Route groups like `(marketing)` and parallel routes like `@modal` exist in
/// the file system but don't contribute to the URL path.
fn is_url_transparent_segment(name: &str) -> bool {
is_group_route(name) || is_parallel_route(name)
}
fn is_dynamic_segment(name: &str) -> bool {
name.starts_with('[') && name.ends_with(']')
}
fn match_parallel_route(name: &str) -> Option<&str> { fn match_parallel_route(name: &str) -> Option<&str> {
name.strip_prefix('@') name.strip_prefix('@')
} }
...@@ -991,7 +1087,8 @@ async fn directory_tree_to_loader_tree( ...@@ -991,7 +1087,8 @@ async fn directory_tree_to_loader_tree(
// the page this loader tree is constructed for // the page this loader tree is constructed for
for_app_path: AppPath, for_app_path: AppPath,
) -> Result<Vc<AppPageLoaderTreeOption>> { ) -> Result<Vc<AppPageLoaderTreeOption>> {
let plain_tree = &*directory_tree.into_plain().await?; let plain_tree_vc = directory_tree.into_plain();
let plain_tree = &*plain_tree_vc.await?;
let tree = directory_tree_to_loader_tree_internal( let tree = directory_tree_to_loader_tree_internal(
app_dir, app_dir,
...@@ -1001,6 +1098,7 @@ async fn directory_tree_to_loader_tree( ...@@ -1001,6 +1098,7 @@ async fn directory_tree_to_loader_tree(
app_page, app_page,
for_app_path, for_app_path,
AppDirModules::default(), AppDirModules::default(),
Some(&plain_tree.url_tree),
) )
.await?; .await?;
...@@ -1080,6 +1178,7 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1080,6 +1178,7 @@ async fn directory_tree_to_loader_tree_internal(
// the page this loader tree is constructed for // the page this loader tree is constructed for
for_app_path: AppPath, for_app_path: AppPath,
mut parent_modules: AppDirModules, mut parent_modules: AppDirModules,
url_tree: Option<&UrlSegmentTree>,
) -> Result<Option<AppPageLoaderTree>> { ) -> Result<Option<AppPageLoaderTree>> {
let app_path = AppPath::from(app_page.clone()); let app_path = AppPath::from(app_page.clone());
...@@ -1139,12 +1238,30 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1139,12 +1238,30 @@ async fn directory_tree_to_loader_tree_internal(
.await?; .await?;
} }
// For dynamic segments like [id], find all static siblings at the same URL level.
// This is used by the client to determine if a prefetch can be reused when
// navigating between routes that share the same parent layout.
let static_siblings: Vec<RcStr> = if is_dynamic_segment(&directory_name) {
url_tree
.map(|t| {
t.static_children()
.into_iter()
.filter(|s| s != &directory_name)
.collect()
})
.unwrap_or_default()
} else {
// Static segments don't need sibling info - only dynamic segments use it
Vec::new()
};
let mut tree = AppPageLoaderTree { let mut tree = AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: directory_name.clone(), segment: directory_name.clone(),
parallel_routes: FxIndexMap::default(), parallel_routes: FxIndexMap::default(),
modules: modules.without_leaves(), modules: modules.without_leaves(),
global_metadata: global_metadata.to_resolved().await?, global_metadata: global_metadata.to_resolved().await?,
static_siblings,
}; };
let current_level_is_parallel_route = is_parallel_route(&directory_name); let current_level_is_parallel_route = is_parallel_route(&directory_name);
...@@ -1169,6 +1286,7 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1169,6 +1286,7 @@ async fn directory_tree_to_loader_tree_internal(
..Default::default() ..Default::default()
}, },
global_metadata: global_metadata.to_resolved().await?, global_metadata: global_metadata.to_resolved().await?,
static_siblings: Vec::new(),
}, },
); );
} }
...@@ -1188,6 +1306,14 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1188,6 +1306,14 @@ async fn directory_tree_to_loader_tree_internal(
illegal_path_error = Some(e); illegal_path_error = Some(e);
} }
// Root/transparent segments don't consume a URL level; others descend.
let child_url_tree: Option<&UrlSegmentTree> =
if directory_name.is_empty() || is_url_transparent_segment(&directory_name) {
url_tree
} else {
url_tree.and_then(|t| t.get_child(&directory_name))
};
let subtree = Box::pin(directory_tree_to_loader_tree_internal( let subtree = Box::pin(directory_tree_to_loader_tree_internal(
app_dir.clone(), app_dir.clone(),
global_metadata, global_metadata,
...@@ -1196,6 +1322,7 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1196,6 +1322,7 @@ async fn directory_tree_to_loader_tree_internal(
child_app_page.clone(), child_app_page.clone(),
for_app_path.clone(), for_app_path.clone(),
parent_modules.clone(), parent_modules.clone(),
child_url_tree,
)) ))
.await?; .await?;
...@@ -1420,6 +1547,7 @@ async fn default_route_tree( ...@@ -1420,6 +1547,7 @@ async fn default_route_tree(
} }
}, },
global_metadata: global_metadata.to_resolved().await?, global_metadata: global_metadata.to_resolved().await?,
static_siblings: Vec::new(),
}) })
} }
...@@ -1662,12 +1790,14 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1662,12 +1790,14 @@ async fn directory_tree_to_entrypoints_internal_untraced(
} }
}, },
global_metadata, global_metadata,
static_siblings: Vec::new(),
} }
}, },
modules: AppDirModules { modules: AppDirModules {
..Default::default() ..Default::default()
}, },
global_metadata, global_metadata,
static_siblings: Vec::new(),
}, },
}, },
modules: AppDirModules { modules: AppDirModules {
...@@ -1690,6 +1820,7 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1690,6 +1820,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
..not_found_root_modules ..not_found_root_modules
}, },
global_metadata, global_metadata,
static_siblings: Vec::new(),
} }
.resolved_cell(); .resolved_cell();
...@@ -1728,10 +1859,12 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1728,10 +1859,12 @@ async fn directory_tree_to_entrypoints_internal_untraced(
..Default::default() ..Default::default()
}, },
global_metadata, global_metadata,
static_siblings: Vec::new(),
} }
}, },
modules: AppDirModules::default(), modules: AppDirModules::default(),
global_metadata, global_metadata,
static_siblings: Vec::new(),
} }
.resolved_cell(); .resolved_cell();
......
...@@ -941,6 +941,7 @@ export async function createEntrypoints( ...@@ -941,6 +941,7 @@ export async function createEntrypoints(
pagePath: absolutePagePath, pagePath: absolutePagePath,
appDir, appDir,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute),
pageExtensions, pageExtensions,
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
...@@ -1019,6 +1020,7 @@ export async function createEntrypoints( ...@@ -1019,6 +1020,7 @@ export async function createEntrypoints(
pagePath: absolutePagePath, pagePath: absolutePagePath,
appDir: appDir!, appDir: appDir!,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute),
pageExtensions, pageExtensions,
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
......
...@@ -6,6 +6,7 @@ type TestLoaderTree = [ ...@@ -6,6 +6,7 @@ type TestLoaderTree = [
segment: string, segment: string,
parallelRoutes: { [key: string]: TestLoaderTree }, parallelRoutes: { [key: string]: TestLoaderTree },
modules: Record<string, unknown>, modules: Record<string, unknown>,
staticSiblings: readonly string[] | null,
] ]
function createLoaderTree( function createLoaderTree(
...@@ -14,7 +15,7 @@ function createLoaderTree( ...@@ -14,7 +15,7 @@ function createLoaderTree(
children?: TestLoaderTree children?: TestLoaderTree
): TestLoaderTree { ): TestLoaderTree {
const routes = children ? { ...parallelRoutes, children } : parallelRoutes const routes = children ? { ...parallelRoutes, children } : parallelRoutes
return [segment, routes, {}] return [segment, routes, {}, null]
} }
describe('extractPathnameRouteParamSegmentsFromLoaderTree', () => { describe('extractPathnameRouteParamSegmentsFromLoaderTree', () => {
......
...@@ -8,6 +8,7 @@ type TestLoaderTree = [ ...@@ -8,6 +8,7 @@ type TestLoaderTree = [
segment: string, segment: string,
parallelRoutes: { [key: string]: TestLoaderTree }, parallelRoutes: { [key: string]: TestLoaderTree },
modules: Record<string, unknown>, modules: Record<string, unknown>,
staticSiblings: readonly string[] | null,
] ]
function createLoaderTree( function createLoaderTree(
...@@ -16,7 +17,7 @@ function createLoaderTree( ...@@ -16,7 +17,7 @@ function createLoaderTree(
children?: TestLoaderTree children?: TestLoaderTree
): TestLoaderTree { ): TestLoaderTree {
const routes = children ? { ...parallelRoutes, children } : parallelRoutes const routes = children ? { ...parallelRoutes, children } : parallelRoutes
return [segment, routes, {}] return [segment, routes, {}, null]
} }
describe('resolveRouteParamsFromTree', () => { describe('resolveRouteParamsFromTree', () => {
......
...@@ -686,6 +686,9 @@ export async function handler( ...@@ -686,6 +686,9 @@ export async function handler(
expireTime: nextConfig.expireTime, expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes, staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover), dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
optimisticRouting: Boolean(
nextConfig.experimental.optimisticRouting
),
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts), authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
clientTraceMetadata: clientTraceMetadata:
......
...@@ -156,6 +156,7 @@ async function requestHandler( ...@@ -156,6 +156,7 @@ async function requestHandler(
expireTime: nextConfig.expireTime, expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes, staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover), dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts), authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
clientTraceMetadata: clientTraceMetadata:
......
...@@ -40,6 +40,7 @@ import type { Compilation } from 'webpack' ...@@ -40,6 +40,7 @@ import type { Compilation } from 'webpack'
import { createAppRouteCode } from './create-app-route-code' import { createAppRouteCode } from './create-app-route-code'
import { MissingDefaultParallelRouteError } from '../../../../shared/lib/errors/missing-default-parallel-route-error' import { MissingDefaultParallelRouteError } from '../../../../shared/lib/errors/missing-default-parallel-route-error'
import { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes' import { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes'
import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'
import { normalizePathSep } from '../../../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../../../shared/lib/page-path/normalize-path-sep'
import { installBindings } from '../../../swc/install-bindings' import { installBindings } from '../../../swc/install-bindings'
...@@ -50,6 +51,9 @@ export type AppLoaderOptions = { ...@@ -50,6 +51,9 @@ export type AppLoaderOptions = {
pagePath: string pagePath: string
appDir: string appDir: string
appPaths: readonly string[] | null appPaths: readonly string[] | null
// All normalized app paths across the entire app, used for computing
// static siblings for dynamic segments
allNormalizedAppPaths: readonly string[] | null
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
pageExtensions: PageExtensions pageExtensions: PageExtensions
assetPrefix: string assetPrefix: string
...@@ -124,6 +128,9 @@ const normalizeParallelKey = (key: string) => ...@@ -124,6 +128,9 @@ const normalizeParallelKey = (key: string) =>
const isCatchAllSegment = (segment: string) => const isCatchAllSegment = (segment: string) =>
segment.startsWith('[...') || segment.startsWith('[[...') segment.startsWith('[...') || segment.startsWith('[[...')
const isDynamicSegment = (segment: string) =>
segment.startsWith('[') && segment.endsWith(']')
const isDirectory = async (pathname: string) => { const isDirectory = async (pathname: string) => {
try { try {
const stat = await fs.stat(pathname) const stat = await fs.stat(pathname)
...@@ -141,11 +148,13 @@ async function createTreeCodeFromPath( ...@@ -141,11 +148,13 @@ async function createTreeCodeFromPath(
resolver, resolver,
resolveParallelSegments, resolveParallelSegments,
hasChildRoutesForSegment, hasChildRoutesForSegment,
getStaticSiblingSegments,
metadataResolver, metadataResolver,
pageExtensions, pageExtensions,
basePath, basePath,
collectedDeclarations, collectedDeclarations,
isGlobalNotFoundEnabled, isGlobalNotFoundEnabled,
isDev,
}: { }: {
page: string page: string
resolveDir: DirResolver resolveDir: DirResolver
...@@ -155,11 +164,13 @@ async function createTreeCodeFromPath( ...@@ -155,11 +164,13 @@ async function createTreeCodeFromPath(
pathname: string pathname: string
) => [key: string, segment: string | string[]][] ) => [key: string, segment: string | string[]][]
hasChildRoutesForSegment: (segmentPath: string) => boolean hasChildRoutesForSegment: (segmentPath: string) => boolean
getStaticSiblingSegments: (segmentPath: string) => string[]
loaderContext: webpack.LoaderContext<AppLoaderOptions> loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: PageExtensions pageExtensions: PageExtensions
basePath: string basePath: string
collectedDeclarations: [string, string][] collectedDeclarations: [string, string][]
isGlobalNotFoundEnabled: boolean isGlobalNotFoundEnabled: boolean
isDev: boolean
} }
): Promise<{ ): Promise<{
treeCode: string treeCode: string
...@@ -535,10 +546,16 @@ async function createTreeCodeFromPath( ...@@ -535,10 +546,16 @@ async function createTreeCodeFromPath(
subtreeCode = pageSubtreeCode subtreeCode = pageSubtreeCode
} }
// Compute static siblings for dynamic segments. In dev mode, routes are
// compiled on-demand so we don't know all siblings; pass null.
const staticSiblingsCode = isDev
? 'null'
: `${JSON.stringify(getStaticSiblingSegments(parallelSegmentPath))}`
props[normalizedParallelKey] = `[ props[normalizedParallelKey] = `[
'${parallelSegmentKey}', '${parallelSegmentKey}',
${subtreeCode}, ${subtreeCode},
${modulesCode} ${modulesCode},
${staticSiblingsCode}
]` ]`
} }
...@@ -661,6 +678,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -661,6 +678,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
name, name,
appDir, appDir,
appPaths, appPaths,
allNormalizedAppPaths: allNormalizedAppPathsOption,
pagePath, pagePath,
pageExtensions, pageExtensions,
rootDir, rootDir,
...@@ -709,6 +727,9 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -709,6 +727,9 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const normalizedAppPaths = const normalizedAppPaths =
typeof appPaths === 'string' ? [appPaths] : appPaths || [] typeof appPaths === 'string' ? [appPaths] : appPaths || []
// All normalized app paths for computing static siblings across route groups
const allNormalizedAppPaths = allNormalizedAppPathsOption ?? []
const resolveParallelSegments = ( const resolveParallelSegments = (
pathname: string pathname: string
): [string, string | string[]][] => { ): [string, string | string[]][] => {
...@@ -810,6 +831,91 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -810,6 +831,91 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
return false return false
} }
/**
* For a given segment path (in file system space, e.g., "(group)/products/[id]"),
* find all static sibling segments at the same URL path level.
*
* This accounts for route groups - siblings may exist in different parts of the
* file system tree but at the same URL level.
*
* For example:
* /app/(marketing)/products/sale/page.tsx -> /products/sale
* /app/(shop)/products/[id]/page.tsx -> /products/[id]
*
* When called with "(shop)/products/[id]", this would return ['sale'].
*
* TODO: This function, along with resolveParallelSegments and
* hasChildRoutesForSegment, repeatedly scans normalizedAppPaths. A more
* optimal approach would build an intermediate tree structure first
* (representing the URL namespace with route groups collapsed), then derive
* all this information in a single pass. The Turbopack implementation
* already uses a more tree-oriented approach (DirectoryTree ->
* AppPageLoaderTree), so this is less urgent to refactor given Turbopack is
* the canonical implementation going forward.
*/
const getStaticSiblingSegments = (segmentPath: string): string[] => {
// Normalize the current path to URL space
// Add a trailing /page so normalizeAppPath strips it properly
const currentUrlPath = normalizeAppPath(segmentPath + '/page')
const currentUrlSegments = currentUrlPath.split('/').filter(Boolean)
// If the path is empty (root level), there are no siblings
if (currentUrlSegments.length === 0) {
return []
}
const currentSegment = currentUrlSegments[currentUrlSegments.length - 1]
const parentUrlPath =
currentUrlSegments.length === 1
? '/'
: '/' + currentUrlSegments.slice(0, -1).join('/')
// The URL level at which we're looking for siblings (0-indexed)
const siblingLevel = currentUrlSegments.length - 1
// Only compute siblings for dynamic segments
if (!isDynamicSegment(currentSegment)) {
return []
}
// Use a Set to avoid duplicates (multiple paths may share the same sibling segment)
const siblings = new Set<string>()
for (const appPath of allNormalizedAppPaths) {
// Normalize each path to URL space (strip route groups, parallel routes, and /page suffix)
const urlPath = normalizeAppPath(appPath)
const urlSegments = urlPath.split('/').filter(Boolean)
// Path must have at least enough segments to reach the sibling level
if (urlSegments.length <= siblingLevel) {
continue
}
// Check if the parent path matches (all segments before the sibling level)
const pathParent =
siblingLevel === 0
? '/'
: '/' + urlSegments.slice(0, siblingLevel).join('/')
if (pathParent !== parentUrlPath) {
continue
}
// Get the segment at the same level as the current segment
const segmentAtLevel = urlSegments[siblingLevel]
// Check if this is a sibling: different segment and static
if (
segmentAtLevel !== currentSegment &&
!isDynamicSegment(segmentAtLevel)
) {
siblings.add(segmentAtLevel)
}
}
return Array.from(siblings)
}
const resolveDir: DirResolver = (pathToResolve) => { const resolveDir: DirResolver = (pathToResolve) => {
return createAbsolutePath(appDir, pathToResolve) return createAbsolutePath(appDir, pathToResolve)
} }
...@@ -917,11 +1023,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -917,11 +1023,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
metadataResolver, metadataResolver,
resolveParallelSegments, resolveParallelSegments,
hasChildRoutesForSegment, hasChildRoutesForSegment,
getStaticSiblingSegments,
loaderContext: this, loaderContext: this,
pageExtensions, pageExtensions,
basePath, basePath,
collectedDeclarations, collectedDeclarations,
isGlobalNotFoundEnabled, isGlobalNotFoundEnabled,
isDev: !!isDev,
}) })
const isGlobalNotFoundPath = const isGlobalNotFoundPath =
...@@ -975,11 +1083,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -975,11 +1083,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
metadataResolver, metadataResolver,
resolveParallelSegments, resolveParallelSegments,
hasChildRoutesForSegment, hasChildRoutesForSegment,
getStaticSiblingSegments,
loaderContext: this, loaderContext: this,
pageExtensions, pageExtensions,
basePath, basePath,
collectedDeclarations, collectedDeclarations,
isGlobalNotFoundEnabled, isGlobalNotFoundEnabled,
isDev: !!isDev,
}) })
} }
} }
......
...@@ -15,7 +15,7 @@ describe('computeChangedPath', () => { ...@@ -15,7 +15,7 @@ describe('computeChangedPath', () => {
'(...)stats', '(...)stats',
{ {
children: [ children: [
['key', 'github', 'd'], ['key', 'github', 'd', null],
{ {
children: ['__PAGE__', {}], children: ['__PAGE__', {}],
}, },
...@@ -40,7 +40,7 @@ describe('computeChangedPath', () => { ...@@ -40,7 +40,7 @@ describe('computeChangedPath', () => {
'(...)stats', '(...)stats',
{ {
children: [ children: [
['key', 'github', 'd'], ['key', 'github', 'd', null],
{ {
children: ['__PAGE__', {}], children: ['__PAGE__', {}],
}, },
......
...@@ -6,14 +6,14 @@ describe('createRouterCacheKey', () => { ...@@ -6,14 +6,14 @@ describe('createRouterCacheKey', () => {
}) })
it('should support dynamic segment', () => { it('should support dynamic segment', () => {
expect(createRouterCacheKey(['slug', 'hello-world', 'd'])).toEqual( expect(createRouterCacheKey(['slug', 'hello-world', 'd', null])).toEqual(
'slug|hello-world|d' 'slug|hello-world|d'
) )
}) })
it('should support catch all segment', () => { it('should support catch all segment', () => {
expect(createRouterCacheKey(['slug', 'blog/hello-world', 'c'])).toEqual( expect(
'slug|blog/hello-world|c' createRouterCacheKey(['slug', 'blog/hello-world', 'c', null])
) ).toEqual('slug|blog/hello-world|c')
}) })
}) })
...@@ -68,7 +68,7 @@ describe('shouldHardNavigate', () => { ...@@ -68,7 +68,7 @@ describe('shouldHardNavigate', () => {
'link-hard-push', 'link-hard-push',
{ {
children: [ children: [
['id', '123', 'd'], ['id', '123', 'd', null],
{ {
children: ['', {}], children: ['', {}],
}, },
...@@ -87,14 +87,14 @@ describe('shouldHardNavigate', () => { ...@@ -87,14 +87,14 @@ describe('shouldHardNavigate', () => {
'children', 'children',
'link-hard-push', 'link-hard-push',
'children', 'children',
['id', '123', 'd'], ['id', '123', 'd', null],
[ [
['id', '123', 'd'], ['id', '123', 'd', null],
{ {
children: ['', {}], children: ['', {}],
}, },
], ],
[['id', '123', 'd'], {}, null], [['id', '123', 'd', null], {}, null],
null, null,
], ],
] ]
...@@ -125,7 +125,7 @@ describe('shouldHardNavigate', () => { ...@@ -125,7 +125,7 @@ describe('shouldHardNavigate', () => {
'link-hard-push', 'link-hard-push',
{ {
children: [ children: [
['id', '456', 'd'], ['id', '456', 'd', null],
{ {
children: ['', {}], children: ['', {}],
}, },
...@@ -144,14 +144,14 @@ describe('shouldHardNavigate', () => { ...@@ -144,14 +144,14 @@ describe('shouldHardNavigate', () => {
'children', 'children',
'link-hard-push', 'link-hard-push',
'children', 'children',
['id', '123', 'd'], ['id', '123', 'd', null],
[ [
['id', '123', 'd'], ['id', '123', 'd', null],
{ {
children: ['', {}], children: ['', {}],
}, },
], ],
[['id', '123', 'd'], {}, null], [['id', '123', 'd', null], {}, null],
null, null,
false, false,
], ],
......
...@@ -1064,17 +1064,16 @@ function convertTreePrefetchToRouteTree( ...@@ -1064,17 +1064,16 @@ function convertTreePrefetchToRouteTree(
slots = {} slots = {}
for (let parallelRouteKey in prefetchSlots) { for (let parallelRouteKey in prefetchSlots) {
const childPrefetch = prefetchSlots[parallelRouteKey] const childPrefetch = prefetchSlots[parallelRouteKey]
const childParamName = childPrefetch.name const childSegmentName = childPrefetch.name
const childParamType = childPrefetch.paramType const childParam = childPrefetch.param
const childServerSentParamKey = childPrefetch.paramKey
let childDoesAppearInURL: boolean let childDoesAppearInURL: boolean
let childSegment: FlightRouterStateSegment let childSegment: FlightRouterStateSegment
let childPartialVaryPath: PartialSegmentVaryPath | null let childPartialVaryPath: PartialSegmentVaryPath | null
if (childParamType !== null) { if (childParam !== null) {
// This segment is parameterized. Get the param from the pathname. // This segment is parameterized. Get the param from the pathname.
const childParamValue = parseDynamicParamFromURLPart( const childParamValue = parseDynamicParamFromURLPart(
childParamType, childParam.type,
pathnameParts, pathnameParts,
pathnamePartsIndex pathnamePartsIndex
) )
...@@ -1092,8 +1091,8 @@ function convertTreePrefetchToRouteTree( ...@@ -1092,8 +1091,8 @@ function convertTreePrefetchToRouteTree(
const childParamKey = const childParamKey =
// The server omits this field from the prefetch response when // The server omits this field from the prefetch response when
// cacheComponents is enabled. // cacheComponents is enabled.
childServerSentParamKey !== null childParam.key !== null
? childServerSentParamKey ? childParam.key
: // If no param key was sent, use the value parsed on the client. : // If no param key was sent, use the value parsed on the client.
getCacheKeyForDynamicParam( getCacheKeyForDynamicParam(
childParamValue, childParamValue,
...@@ -1104,14 +1103,19 @@ function convertTreePrefetchToRouteTree( ...@@ -1104,14 +1103,19 @@ function convertTreePrefetchToRouteTree(
partialVaryPath, partialVaryPath,
childParamKey childParamKey
) )
childSegment = [childParamName, childParamKey, childParamType] childSegment = [
childSegmentName,
childParamKey,
childParam.type,
childParam.siblings,
]
childDoesAppearInURL = true childDoesAppearInURL = true
} else { } else {
// This segment does not have a param. Inherit the partial vary path of // This segment does not have a param. Inherit the partial vary path of
// the parent. // the parent.
childPartialVaryPath = partialVaryPath childPartialVaryPath = partialVaryPath
childSegment = childParamName childSegment = childSegmentName
childDoesAppearInURL = doesStaticSegmentAppearInURL(childParamName) childDoesAppearInURL = doesStaticSegmentAppearInURL(childSegmentName)
} }
// Only increment the index if the segment appears in the URL. If it's a // Only increment the index if the segment appears in the URL. If it's a
......
...@@ -46,7 +46,12 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -46,7 +46,12 @@ describe('prepareFlightRouterStateForRequest', () => {
}) })
it('should preserve dynamic segments', () => { it('should preserve dynamic segments', () => {
const dynamicSegment: [string, string, 'd'] = ['slug', 'test-value', 'd'] const dynamicSegment: [string, string, 'd', null] = [
'slug',
'test-value',
'd',
null,
]
const flightRouterState: FlightRouterState = [dynamicSegment, {}] const flightRouterState: FlightRouterState = [dynamicSegment, {}]
const result = prepareFlightRouterStateForRequest(flightRouterState) const result = prepareFlightRouterStateForRequest(flightRouterState)
...@@ -266,7 +271,12 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -266,7 +271,12 @@ describe('prepareFlightRouterStateForRequest', () => {
true, true,
1, 1,
], ],
sidebar: [['slug', 'user-123', 'd'], {}, ['/sidebar/url', ''], null], sidebar: [
['slug', 'user-123', 'd', null],
{},
['/sidebar/url', ''],
null,
],
}, },
['/main/url', ''], ['/main/url', ''],
'inside-shared-layout', 'inside-shared-layout',
...@@ -300,7 +310,7 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -300,7 +310,7 @@ describe('prepareFlightRouterStateForRequest', () => {
// Sidebar route (dynamic segment) checks // Sidebar route (dynamic segment) checks
const sidebarRoute = decoded[1].sidebar const sidebarRoute = decoded[1].sidebar
expect(sidebarRoute[0]).toEqual(['slug', 'user-123', 'd']) // dynamic segment preserved expect(sidebarRoute[0]).toEqual(['slug', 'user-123', 'd', null]) // dynamic segment preserved
expect(sidebarRoute[2]).toBeUndefined() // URL stripped expect(sidebarRoute[2]).toBeUndefined() // URL stripped
expect(sidebarRoute[3]).toBeUndefined() // null marker stripped expect(sidebarRoute[3]).toBeUndefined() // null marker stripped
}) })
......
...@@ -152,13 +152,14 @@ function fillInFallbackFlightRouterStateImpl( ...@@ -152,13 +152,14 @@ function fillInFallbackFlightRouterStateImpl(
} else { } else {
const paramName = originalSegment[0] const paramName = originalSegment[0]
const paramType = originalSegment[2] const paramType = originalSegment[2]
const staticSiblings = originalSegment[3]
const paramValue = parseDynamicParamFromURLPart( const paramValue = parseDynamicParamFromURLPart(
paramType, paramType,
pathnameParts, pathnameParts,
pathnamePartsIndex pathnamePartsIndex
) )
const cacheKey = getCacheKeyForDynamicParam(paramValue, renderedSearch) const cacheKey = getCacheKeyForDynamicParam(paramValue, renderedSearch)
newSegment = [paramName, cacheKey, paramType] newSegment = [paramName, cacheKey, paramType, staticSiblings]
doesAppearInURL = true doesAppearInURL = true
} }
...@@ -250,9 +251,8 @@ function stripClientOnlyDataFromFlightRouterState( ...@@ -250,9 +251,8 @@ function stripClientOnlyDataFromFlightRouterState(
hasLoadingBoundary, hasLoadingBoundary,
] = flightRouterState ] = flightRouterState
// __PAGE__ segments are always fetched from the server, so there's // Strip client-only data from the segment
// no need to send them up const cleanedSegment = stripClientOnlyDataFromSegment(segment)
const cleanedSegment = stripSearchParamsFromPageSegment(segment)
// Recursively process parallel routes // Recursively process parallel routes
const cleanedParallelRoutes: { [key: string]: FlightRouterState } = {} const cleanedParallelRoutes: { [key: string]: FlightRouterState } = {}
...@@ -280,15 +280,21 @@ function stripClientOnlyDataFromFlightRouterState( ...@@ -280,15 +280,21 @@ function stripClientOnlyDataFromFlightRouterState(
} }
/** /**
* Strips search parameters from __PAGE__ segments to prevent sensitive * Strips client-only data from segments:
* client-side data from being sent to the server. * - Search parameters from __PAGE__ segments
* - staticSiblings from dynamic segment tuples (only needed for client-side
* prefetch reuse decisions)
*/ */
function stripSearchParamsFromPageSegment(segment: Segment): Segment { function stripClientOnlyDataFromSegment(segment: Segment): Segment {
if ( if (typeof segment === 'string') {
typeof segment === 'string' && // Strip search params from __PAGE__ segments
segment.startsWith(PAGE_SEGMENT_KEY + '?') if (segment.startsWith(PAGE_SEGMENT_KEY + '?')) {
) { return PAGE_SEGMENT_KEY
return PAGE_SEGMENT_KEY }
return segment
} }
return segment // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]
// Strip staticSiblings (4th element) since server doesn't need it
const [paramName, paramCacheKey, paramType] = segment
return [paramName, paramCacheKey, paramType, null]
} }
...@@ -395,6 +395,7 @@ async function exportAppImpl( ...@@ -395,6 +395,7 @@ async function exportAppImpl(
clientParamParsingOrigins: clientParamParsingOrigins:
nextConfig.experimental.clientParamParsingOrigins, nextConfig.experimental.clientParamParsingOrigins,
dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false, dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,
optimisticRouting: nextConfig.experimental.optimisticRouting ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false, inlineCss: nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts, authInterrupts: !!nextConfig.experimental.authInterrupts,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
......
...@@ -746,7 +746,7 @@ async function resolveMetadataItemsImpl( ...@@ -746,7 +746,7 @@ async function resolveMetadataItemsImpl(
const isPage = typeof page !== 'undefined' const isPage = typeof page !== 'undefined'
// Handle dynamic segment params. // Handle dynamic segment params.
const segmentParam = getDynamicParamFromSegment(segment) const segmentParam = getDynamicParamFromSegment(tree)
/** /**
* Create object holding the parent params and current params * Create object holding the parent params and current params
*/ */
...@@ -842,7 +842,7 @@ async function resolveViewportItemsImpl( ...@@ -842,7 +842,7 @@ async function resolveViewportItemsImpl(
const isPage = typeof page !== 'undefined' const isPage = typeof page !== 'undefined'
// Handle dynamic segment params. // Handle dynamic segment params.
const segmentParam = getDynamicParamFromSegment(segment) const segmentParam = getDynamicParamFromSegment(tree)
/** /**
* Create object holding the parent params and current params * Create object holding the parent params and current params
*/ */
......
...@@ -3,8 +3,8 @@ import type { RenderOpts, PreloadCallbacks } from './types' ...@@ -3,8 +3,8 @@ import type { RenderOpts, PreloadCallbacks } from './types'
import type { import type {
ActionResult, ActionResult,
DynamicParamTypesShort, DynamicParamTypesShort,
DynamicSegmentTuple,
FlightRouterState, FlightRouterState,
Segment,
CacheNodeSeedData, CacheNodeSeedData,
RSCPayload, RSCPayload,
FlightData, FlightData,
...@@ -219,14 +219,14 @@ import { anySegmentHasRuntimePrefetchEnabled } from './staged-validation' ...@@ -219,14 +219,14 @@ import { anySegmentHasRuntimePrefetchEnabled } from './staged-validation'
import { warnOnce } from '../../shared/lib/utils/warn-once' import { warnOnce } from '../../shared/lib/utils/warn-once'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // The LoaderTree to extract the dynamic param from
segment: string loaderTree: LoaderTree
) => DynamicParam | null ) => DynamicParam | null
export type DynamicParam = { export type DynamicParam = {
param: string param: string
value: string | string[] | null value: string | string[] | null
treeSegment: Segment treeSegment: DynamicSegmentTuple
type: DynamicParamTypesShort type: DynamicParamTypesShort
} }
...@@ -385,10 +385,11 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { ...@@ -385,10 +385,11 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
return [ return [
'', '',
{ {
children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents], children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents, null],
}, },
// When global-not-found is present, skip layout from components // When global-not-found is present, skip layout from components
hasGlobalNotFound ? components : {}, hasGlobalNotFound ? components : {},
null, // staticSiblings
] ]
} }
...@@ -397,23 +398,25 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { ...@@ -397,23 +398,25 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
*/ */
function makeGetDynamicParamFromSegment( function makeGetDynamicParamFromSegment(
interpolatedParams: Params, interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null,
optimisticRouting: boolean
): GetDynamicParamFromSegment { ): GetDynamicParamFromSegment {
return function getDynamicParamFromSegment( return function getDynamicParamFromSegment(loaderTree: LoaderTree) {
// [slug] / [[slug]] / [...slug] const [segment, , , staticSiblings] = loaderTree
segment: string
) {
const segmentParam = getSegmentParam(segment) const segmentParam = getSegmentParam(segment)
if (!segmentParam) { if (!segmentParam) {
return null return null
} }
const segmentKey = segmentParam.paramName const segmentKey = segmentParam.paramName
const dynamicParamType = dynamicParamTypes[segmentParam.paramType] const dynamicParamType = dynamicParamTypes[segmentParam.paramType]
// Static siblings are only included when optimistic routing is enabled
const siblings = optimisticRouting ? staticSiblings : null
return getDynamicParam( return getDynamicParam(
interpolatedParams, interpolatedParams,
segmentKey, segmentKey,
dynamicParamType, dynamicParamType,
fallbackRouteParams fallbackRouteParams,
siblings
) )
} }
} }
...@@ -2012,7 +2015,8 @@ async function renderToHTMLOrFlightImpl( ...@@ -2012,7 +2015,8 @@ async function renderToHTMLOrFlightImpl(
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment( const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(
interpolatedParams, interpolatedParams,
fallbackRouteParams fallbackRouteParams,
renderOpts.experimental.optimisticRouting
) )
const isPossibleActionRequest = getIsPossibleServerAction(req) const isPossibleActionRequest = getIsPossibleServerAction(req)
......
...@@ -40,13 +40,25 @@ export type RootTreePrefetch = { ...@@ -40,13 +40,25 @@ export type RootTreePrefetch = {
staleTime: number staleTime: number
} }
export type TreePrefetch = { export type TreePrefetchParam = {
name: string type: DynamicParamTypesShort
paramType: DynamicParamTypesShort | null
// When cacheComponents is enabled, this field is always null. // When cacheComponents is enabled, this field is always null.
// Instead we parse the param on the client, allowing us to omit it from // Instead we parse the param on the client, allowing us to omit it from
// the prefetch response and increase its cacheability. // the prefetch response and increase its cacheability.
paramKey: string | null key: string | null
// Static sibling segments at the same URL level. Used by the client
// router to determine if a prefetch can be reused when navigating to
// a static sibling of a dynamic route. For example, if the route is
// /products/[id] and there's also /products/sale, then siblings
// would be ['sale']. null means the siblings are unknown (e.g. in
// webpack dev mode).
siblings: readonly string[] | null
}
export type TreePrefetch = {
name: string
// Only present for parameterized (dynamic) segments.
param: TreePrefetchParam | null
// Child segments. // Child segments.
slots: null | { slots: null | {
...@@ -320,27 +332,27 @@ function collectSegmentDataImpl( ...@@ -320,27 +332,27 @@ function collectSegmentDataImpl(
} }
const segment = route[0] const segment = route[0]
let name let name: string
let paramType: DynamicParamTypesShort | null = null let param: TreePrefetchParam | null
let paramKey: string | null = null
if (typeof segment === 'string') { if (typeof segment === 'string') {
name = segment name = segment
paramKey = segment param = null
paramType = null
} else { } else {
name = segment[0] name = segment[0]
paramKey = segment[1] param = {
paramType = segment[2] as DynamicParamTypesShort type: segment[2],
// This value is omitted from the prefetch response when cacheComponents
// is enabled.
key: isClientParamParsingEnabled ? null : segment[1],
siblings: segment[3],
}
} }
// Metadata about the segment. Sent to the client as part of the // Metadata about the segment. Sent to the client as part of the
// tree prefetch. // tree prefetch.
return { return {
name, name,
paramType, param,
// This value is ommitted from the prefetch response when cacheComponents
// is enabled.
paramKey: isClientParamParsingEnabled ? null : paramKey,
hasRuntimePrefetch, hasRuntimePrefetch,
slots: slotMetadata, slots: slotMetadata,
isRootLayout: route[4] === true, isRootLayout: route[4] === true,
......
...@@ -403,7 +403,7 @@ async function createComponentTreeInternal( ...@@ -403,7 +403,7 @@ async function createComponentTreeInternal(
} }
// Handle dynamic segment params. // Handle dynamic segment params.
const segmentParam = getDynamicParamFromSegment(segment) const segmentParam = getDynamicParamFromSegment(tree)
// Create object holding the parent params and current params // Create object holding the parent params and current params
let currentParams: Params = parentParams let currentParams: Params = parentParams
...@@ -1104,12 +1104,11 @@ function getRootParamsImpl( ...@@ -1104,12 +1104,11 @@ function getRootParamsImpl(
getDynamicParamFromSegment: GetDynamicParamFromSegment getDynamicParamFromSegment: GetDynamicParamFromSegment
): Params { ): Params {
const { const {
segment,
modules: { layout }, modules: { layout },
parallelRoutes, parallelRoutes,
} = parseLoaderTree(loaderTree) } = parseLoaderTree(loaderTree)
const segmentParam = getDynamicParamFromSegment(segment) const segmentParam = getDynamicParamFromSegment(loaderTree)
let currentParams: Params = parentParams let currentParams: Params = parentParams
if (segmentParam && segmentParam.value !== null) { if (segmentParam && segmentParam.value !== null) {
......
...@@ -7,13 +7,14 @@ import type { GetDynamicParamFromSegment } from './app-render' ...@@ -7,13 +7,14 @@ import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment' import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
function createFlightRouterStateFromLoaderTreeImpl( function createFlightRouterStateFromLoaderTreeImpl(
[segment, parallelRoutes, { layout, loading }]: LoaderTree, loaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any, searchParams: any,
includeHasLoadingBoundary: boolean, includeHasLoadingBoundary: boolean,
didFindRootLayout: boolean didFindRootLayout: boolean
): FlightRouterState { ): FlightRouterState {
const dynamicParam = getDynamicParamFromSegment(segment) const [segment, parallelRoutes, { layout, loading }] = loaderTree
const dynamicParam = getDynamicParamFromSegment(loaderTree)
const treeSegment = dynamicParam ? dynamicParam.treeSegment : segment const treeSegment = dynamicParam ? dynamicParam.treeSegment : segment
const segmentTree: FlightRouterState = [ const segmentTree: FlightRouterState = [
......
...@@ -181,7 +181,8 @@ export function parsePostponedState( ...@@ -181,7 +181,8 @@ export function parsePostponedState(
interpolatedParams, interpolatedParams,
segmentKey, segmentKey,
dynamicParamType, dynamicParamType,
null null,
null // staticSiblings not needed for postponed state
) )
postponed = postponed.replaceAll(searchValue, value) postponed = postponed.replaceAll(searchValue, value)
......
...@@ -3,27 +3,27 @@ import { assert } from 'next/dist/compiled/superstruct' ...@@ -3,27 +3,27 @@ import { assert } from 'next/dist/compiled/superstruct'
const validFixtures = [ const validFixtures = [
[ [
['a', 'b', 'c'], ['a', 'b', 'c', null],
{ {
a: [['a', 'b', 'c'], {}], a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c'], {}], b: [['a', 'b', 'c', null], {}],
}, },
], ],
[ [
['a', 'b', 'c'], ['a', 'b', 'c', ['sibling1', 'sibling2']],
{ {
a: [['a', 'b', 'c'], {}], a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c'], {}], b: [['a', 'b', 'c', []], {}],
}, },
null, null,
null, null,
true, true,
], ],
[ [
['a', 'b', 'c'], ['a', 'b', 'c', null],
{ {
a: [['a', 'b', 'c'], {}], a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c'], {}], b: [['a', 'b', 'c', null], {}],
}, },
null, null,
'refetch', 'refetch',
...@@ -33,14 +33,20 @@ const validFixtures = [ ...@@ -33,14 +33,20 @@ const validFixtures = [
const invalidFixtures = [ const invalidFixtures = [
// plain wrong // plain wrong
['1', 'b', 'c'], ['1', 'b', 'c'],
// invalid enum // invalid enum (missing 4th element)
[['a', 'b', 'foo'], {}], [['a', 'b', 'foo'], {}],
// invalid enum (with 4th element)
[['a', 'b', 'foo', null], {}],
// invalid staticSiblings (not an array)
[['a', 'b', 'c', 'not-an-array'], {}],
// invalid staticSiblings (array with non-strings)
[['a', 'b', 'c', [1, 2]], {}],
// invalid url // invalid url
[ [
['a', 'b', 'c'], ['a', 'b', 'c', null],
{ {
a: [['a', 'b', 'c'], {}], a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c'], {}], b: [['a', 'b', 'c', null], {}],
}, },
{ {
invalid: 'invalid', invalid: 'invalid',
...@@ -48,10 +54,10 @@ const invalidFixtures = [ ...@@ -48,10 +54,10 @@ const invalidFixtures = [
], ],
// invalid isRootLayout // invalid isRootLayout
[ [
['a', 'b', 'c'], ['a', 'b', 'c', null],
{ {
a: [['a', 'b', 'c'], {}], a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c'], {}], b: [['a', 'b', 'c', null], {}],
}, },
null, null,
1, 1,
......
...@@ -49,6 +49,10 @@ const segmentSchema = s.union([ ...@@ -49,6 +49,10 @@ const segmentSchema = s.union([
s.string(), s.string(),
// Dynamic param type // Dynamic param type
dynamicParamTypesSchema, dynamicParamTypesSchema,
// Static siblings at the same URL level. Used by the client router to
// determine if a prefetch can be reused when navigating to a static
// sibling of a dynamic route. null means siblings are unknown.
s.nullable(s.array(s.string())),
]), ]),
]) ])
...@@ -155,6 +159,7 @@ export interface RenderOptsPartial { ...@@ -155,6 +159,7 @@ export interface RenderOptsPartial {
*/ */
clientParamParsingOrigins: string[] | undefined clientParamParsingOrigins: string[] | undefined
dynamicOnHover: boolean dynamicOnHover: boolean
optimisticRouting: boolean
inlineCss: boolean inlineCss: boolean
authInterrupts: boolean authInterrupts: boolean
......
...@@ -77,7 +77,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -77,7 +77,7 @@ export async function walkTreeWithFlightRouterState({
rootLayoutIncluded || rootLayoutAtThisLevel rootLayoutIncluded || rootLayoutAtThisLevel
// Because this function walks to a deeper point in the tree to start rendering we have to track the dynamic parameters up to the point where rendering starts // Because this function walks to a deeper point in the tree to start rendering we have to track the dynamic parameters up to the point where rendering starts
const segmentParam = getDynamicParamFromSegment(segment) const segmentParam = getDynamicParamFromSegment(loaderTreeToFilter)
const currentParams = const currentParams =
// Handle null case where dynamic param is optional // Handle null case where dynamic param is optional
segmentParam && segmentParam.value !== null segmentParam && segmentParam.value !== null
......
...@@ -562,6 +562,8 @@ export default abstract class Server< ...@@ -562,6 +562,8 @@ export default abstract class Server<
clientParamParsingOrigins: clientParamParsingOrigins:
this.nextConfig.experimental.clientParamParsingOrigins, this.nextConfig.experimental.clientParamParsingOrigins,
dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false, dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,
optimisticRouting:
this.nextConfig.experimental.optimisticRouting ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false, inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts, authInterrupts: !!this.nextConfig.experimental.authInterrupts,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
......
...@@ -195,6 +195,7 @@ export const experimentalSchema = { ...@@ -195,6 +195,7 @@ export const experimentalSchema = {
caseSensitiveRoutes: z.boolean().optional(), caseSensitiveRoutes: z.boolean().optional(),
clientParamParsingOrigins: z.array(z.string()).optional(), clientParamParsingOrigins: z.array(z.string()).optional(),
dynamicOnHover: z.boolean().optional(), dynamicOnHover: z.boolean().optional(),
optimisticRouting: z.boolean().optional(),
disableOptimizedLoading: z.boolean().optional(), disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(), disablePostcssPresetEnv: z.boolean().optional(),
cacheComponents: z.boolean().optional(), cacheComponents: z.boolean().optional(),
......
...@@ -287,6 +287,7 @@ export interface ExperimentalConfig { ...@@ -287,6 +287,7 @@ export interface ExperimentalConfig {
*/ */
clientParamParsingOrigins?: string[] clientParamParsingOrigins?: string[]
dynamicOnHover?: boolean dynamicOnHover?: boolean
optimisticRouting?: boolean
preloadEntriesOnStart?: boolean preloadEntriesOnStart?: boolean
clientRouterFilter?: boolean clientRouterFilter?: boolean
clientRouterFilterRedirects?: boolean clientRouterFilterRedirects?: boolean
...@@ -1669,6 +1670,7 @@ export interface NextConfigRuntime { ...@@ -1669,6 +1670,7 @@ export interface NextConfigRuntime {
| 'serverActions' | 'serverActions'
| 'staleTimes' | 'staleTimes'
| 'dynamicOnHover' | 'dynamicOnHover'
| 'optimisticRouting'
| 'inlineCss' | 'inlineCss'
| 'authInterrupts' | 'authInterrupts'
| 'clientTraceMetadata' | 'clientTraceMetadata'
...@@ -1730,6 +1732,7 @@ export function getNextConfigRuntime( ...@@ -1730,6 +1732,7 @@ export function getNextConfigRuntime(
serverActions: ex.serverActions, serverActions: ex.serverActions,
staleTimes: ex.staleTimes, staleTimes: ex.staleTimes,
dynamicOnHover: ex.dynamicOnHover, dynamicOnHover: ex.dynamicOnHover,
optimisticRouting: ex.optimisticRouting,
inlineCss: ex.inlineCss, inlineCss: ex.inlineCss,
authInterrupts: ex.authInterrupts, authInterrupts: ex.authInterrupts,
clientTraceMetadata: ex.clientTraceMetadata, clientTraceMetadata: ex.clientTraceMetadata,
......
...@@ -1027,6 +1027,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1027,6 +1027,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
name: bundlePath, name: bundlePath,
page, page,
appPaths: entryData.appPaths, appPaths: entryData.appPaths,
allNormalizedAppPaths: null, // Not available in dev mode
pagePath: posix.join( pagePath: posix.join(
APP_DIR_ALIAS, APP_DIR_ALIAS,
relative( relative(
...@@ -1156,6 +1157,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1156,6 +1157,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
name: bundlePath, name: bundlePath,
page, page,
appPaths: entryData.appPaths, appPaths: entryData.appPaths,
allNormalizedAppPaths: null, // Not available in dev mode
pagePath, pagePath,
appDir: this.appDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
......
...@@ -8,6 +8,24 @@ export type LoaderTree = [ ...@@ -8,6 +8,24 @@ export type LoaderTree = [
segment: string, segment: string,
parallelRoutes: { [parallelRouterKey: string]: LoaderTree }, parallelRoutes: { [parallelRouterKey: string]: LoaderTree },
modules: AppDirModules, modules: AppDirModules,
/**
* At build time, for each dynamic segment, we compute the list of static
* sibling segments that exist at the same URL path level. This is used by
* the client router to determine if a prefetch can be reused.
*
* For example, given the following file structure:
* /app/(group1)/products/sale/page.tsx -> /products/sale
* /app/(group2)/products/[id]/page.tsx -> /products/[id]
*
* The [id] segment would have staticSiblings: ['sale']
*
* This accounts for route groups, which may place sibling routes in
* different parts of the file system tree but at the same URL level.
*
* A value of `null` means the static siblings are unknown (e.g., in webpack
* dev mode where routes are compiled on-demand).
*/
staticSiblings: readonly string[] | null,
] ]
export async function getLayoutOrPageModule(loaderTree: LoaderTree) { export async function getLayoutOrPageModule(loaderTree: LoaderTree) {
......
...@@ -11,6 +11,7 @@ type TestLoaderTree = [ ...@@ -11,6 +11,7 @@ type TestLoaderTree = [
segment: string, segment: string,
parallelRoutes: { [key: string]: TestLoaderTree }, parallelRoutes: { [key: string]: TestLoaderTree },
modules: Record<string, unknown>, modules: Record<string, unknown>,
staticSiblings: readonly string[] | null,
] ]
function createLoaderTree( function createLoaderTree(
...@@ -19,7 +20,7 @@ function createLoaderTree( ...@@ -19,7 +20,7 @@ function createLoaderTree(
children?: TestLoaderTree children?: TestLoaderTree
): TestLoaderTree { ): TestLoaderTree {
const routes = children ? { ...parallelRoutes, children } : parallelRoutes const routes = children ? { ...parallelRoutes, children } : parallelRoutes
return [segment, routes, {}] return [segment, routes, {}, null]
} }
/** /**
......
...@@ -75,21 +75,29 @@ export type DynamicParamTypesShort = ...@@ -75,21 +75,29 @@ export type DynamicParamTypesShort =
| 'di(..)' | 'di(..)'
| 'di(...)' | 'di(...)'
export type Segment = // The tuple form of a segment, used for dynamic route params
| string export type DynamicSegmentTuple = [
| [ // Param name
// Param name paramName: string,
paramName: string, // Param cache key (almost the same as the value, but arrays are
// Param cache key (almost the same as the value, but arrays are // concatenated into strings)
// concatenated into strings) // TODO: We should change this to just be the value. Currently we convert
// TODO: We should change this to just be the value. Currently we convert // it back to a value when passing to useParams. It only needs to be
// it back to a value when passing to useParams. It only needs to be // a string when converted to a a cache key, but that doesn't mean we
// a string when converted to a a cache key, but that doesn't mean we // need to store it as that representation.
// need to store it as that representation. paramCacheKey: string,
paramCacheKey: string, // Dynamic param type
// Dynamic param type dynamicParamType: DynamicParamTypesShort,
dynamicParamType: DynamicParamTypesShort, // Static sibling segments at the same URL level. Used by the client
] // router to determine if a prefetch can be reused when navigating to
// a static sibling of a dynamic route. For example, if the route is
// /products/[id] and there's also /products/sale, then staticSiblings
// would be ['sale']. null means the siblings are unknown (e.g. in
// webpack dev mode).
staticSiblings: readonly string[] | null,
]
export type Segment = string | DynamicSegmentTuple
/** /**
* Router state * Router state
......
...@@ -121,7 +121,8 @@ export function getDynamicParam( ...@@ -121,7 +121,8 @@ export function getDynamicParam(
interpolatedParams: Params, interpolatedParams: Params,
segmentKey: string, segmentKey: string,
dynamicParamType: DynamicParamTypesShort, dynamicParamType: DynamicParamTypesShort,
fallbackRouteParams: OpaqueFallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null,
staticSiblings: readonly string[] | null
): DynamicParam { ): DynamicParam {
let value: string | string[] | undefined = getParamValue( let value: string | string[] | undefined = getParamValue(
interpolatedParams, interpolatedParams,
...@@ -137,7 +138,7 @@ export function getDynamicParam( ...@@ -137,7 +138,7 @@ export function getDynamicParam(
param: segmentKey, param: segmentKey,
value: null, value: null,
type: dynamicParamType, type: dynamicParamType,
treeSegment: [segmentKey, '', dynamicParamType], treeSegment: [segmentKey, '', dynamicParamType, staticSiblings],
} }
} }
...@@ -146,16 +147,18 @@ export function getDynamicParam( ...@@ -146,16 +147,18 @@ export function getDynamicParam(
) )
} }
const paramCacheKey = Array.isArray(value) ? value.join('/') : value
return { return {
param: segmentKey, param: segmentKey,
// The value that is passed to user code. // The value that is passed to user code.
value, value,
// The value that is rendered in the router tree. // The value that is rendered in the router tree.
treeSegment: [ // TODO: If the number of static siblings exceeds some threshold (e.g.,
segmentKey, // dozens or hundreds), consider sending a Bloom filter instead of the full
Array.isArray(value) ? value.join('/') : value, // array to reduce payload size. The client would then use the Bloom filter
dynamicParamType, // to check membership with a small false positive rate.
], treeSegment: [segmentKey, paramCacheKey, dynamicParamType, staticSiblings],
type: dynamicParamType, type: dynamicParamType,
} }
} }
......
...@@ -2,7 +2,7 @@ import { DEFAULT_SEGMENT_KEY } from '../../segment' ...@@ -2,7 +2,7 @@ import { DEFAULT_SEGMENT_KEY } from '../../segment'
import type { LoaderTree } from '../../../../server/lib/app-dir-module' import type { LoaderTree } from '../../../../server/lib/app-dir-module'
export function parseLoaderTree(tree: LoaderTree) { export function parseLoaderTree(tree: LoaderTree) {
const [segment, parallelRoutes, modules] = tree const [segment, parallelRoutes, modules, staticSiblings] = tree
const { layout, template } = modules const { layout, template } = modules
let { page } = modules let { page } = modules
// a __DEFAULT__ segment means that this route didn't match any of the // a __DEFAULT__ segment means that this route didn't match any of the
...@@ -18,5 +18,6 @@ export function parseLoaderTree(tree: LoaderTree) { ...@@ -18,5 +18,6 @@ export function parseLoaderTree(tree: LoaderTree) {
/* it can be either layout / template / page */ /* it can be either layout / template / page */
conventionPath, conventionPath,
parallelRoutes, parallelRoutes,
staticSiblings,
} }
} }
...@@ -6,11 +6,13 @@ describe('getSegmentValue', () => { ...@@ -6,11 +6,13 @@ describe('getSegmentValue', () => {
}) })
it('should support dynamic segment', () => { it('should support dynamic segment', () => {
expect(getSegmentValue(['slug', 'hello-world', 'd'])).toEqual('hello-world') expect(getSegmentValue(['slug', 'hello-world', 'd', null])).toEqual(
'hello-world'
)
}) })
it('should support catch all segment', () => { it('should support catch all segment', () => {
expect(getSegmentValue(['slug', 'blog/hello-world', 'c'])).toEqual( expect(getSegmentValue(['slug', 'blog/hello-world', 'c', null])).toEqual(
'blog/hello-world' 'blog/hello-world'
) )
}) })
......
...@@ -247,7 +247,7 @@ describe('app dir - prefetching', () => { ...@@ -247,7 +247,7 @@ describe('app dir - prefetching', () => {
'prefetch-auto', 'prefetch-auto',
{ {
children: [ children: [
['slug', 'vercel', 'd'], ['slug', 'vercel', 'd', null],
{ children: ['__PAGE__', {}] }, { children: ['__PAGE__', {}] },
], ],
}, },
......
export default function SalePage() {
return (
<p id="sale-page" data-testid="sale-page">
Sale page (static sibling)
</p>
)
}
export default function Loading() {
return <div>Loading...</div>
}
export default function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
return (
<p id="product-page" data-testid="product-page">
Product page (dynamic route)
</p>
)
}
export default function Loading() {
return <div>Loading...</div>
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div id="category-page">
<h1>Category: {slug}</h1>
<p>Dynamic category page</p>
</div>
)
}
export default function LaptopsLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div data-laptops-layout>
<div>Laptops Layout</div>
{children}
</div>
)
}
export default function Page() {
return (
<div id="laptops-page">
<h1>Laptops</h1>
<p>Deeply nested static sibling with multiple layouts</p>
</div>
)
}
export default function ComputersLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div data-computers-layout>
<div>Computers Layout</div>
{children}
</div>
)
}
export default function ElectronicsLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div data-electronics-layout>
<div>Electronics Layout</div>
{children}
</div>
)
}
export default function Loading() {
return <div>Loading...</div>
}
export default function PanelItemPage({
params,
}: {
params: Promise<{ id: string }>
}) {
return (
<p id="panel-item-page" data-testid="panel-item-page">
Panel item (dynamic in parallel route)
</p>
)
}
export default function PanelDefault() {
return (
<p id="panel-default" data-testid="panel-default">
Panel default
</p>
)
}
export default function PanelSettingsPage() {
return (
<p id="panel-settings-page" data-testid="panel-settings-page">
Panel settings (static sibling in parallel route)
</p>
)
}
export default function DashboardDefault() {
return <p>Dashboard default</p>
}
import { ReactNode } from 'react'
export default function DashboardLayout({
children,
panel,
}: {
children: ReactNode
panel: ReactNode
}) {
return (
<div>
<div id="children">{children}</div>
<div id="panel">{panel}</div>
</div>
)
}
export default function DashboardPage() {
return <p>Dashboard home</p>
}
export default function Loading() {
return <div>Loading...</div>
}
export default function ItemPage({
params,
}: {
params: Promise<{ id: string }>
}) {
return (
<p id="item-page" data-testid="item-page">
Item page (dynamic route)
</p>
)
}
export default function FeaturedPage() {
return (
<p id="featured-page" data-testid="featured-page">
Featured items (static sibling)
</p>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main id="home-page">
<h1>Static Siblings Test</h1>
<section>
<h2>About</h2>
<p>
This test verifies that when a dynamic route has static siblings at
the same URL level, the client can correctly navigate to the static
sibling even after the dynamic route has been visited/prefetched.
</p>
<h3>Manual testing instructions</h3>
<ol>
<li>Click the checkbox next to a dynamic route to reveal it</li>
<li>Click the revealed link to navigate to the dynamic route</li>
<li>Use the browser back button to return to this page</li>
<li>Click the static sibling link (which has prefetch=false)</li>
<li>Verify the static sibling page renders, not the dynamic route</li>
</ol>
<p>
The key behavior being tested: when navigating to a URL that matches
both a dynamic route (e.g., /products/[id]) and a static route (e.g.,
/products/sale), the static route should take precedence. The route
tree delivered by the server includes information about static
siblings to facilitate this behavior.
</p>
</section>
<hr />
<section id="cross-route-group-test">
<h2>Cross-Route-Group Siblings</h2>
<p>/products/sale vs /products/[id] (in different route groups)</p>
<div>
<LinkAccordion href="/products/123">
Dynamic route: /products/123
</LinkAccordion>
</div>
<div>
<Link href="/products/sale" prefetch={false} id="link-to-sale">
Static sibling: /products/sale
</Link>
</div>
</section>
<section id="same-directory-test">
<h2>Same-Directory Siblings</h2>
<p>/items/featured vs /items/[id] (in the same directory)</p>
<div>
<LinkAccordion href="/items/456">
Dynamic route: /items/456
</LinkAccordion>
</div>
<div>
<Link href="/items/featured" prefetch={false} id="link-to-featured">
Static sibling: /items/featured
</Link>
</div>
</section>
<section id="parallel-route-test">
<h2>Parallel Route Siblings</h2>
<p>/dashboard/settings vs /dashboard/[id] (in @panel parallel route)</p>
<div>
<LinkAccordion href="/dashboard/789">
Dynamic route: /dashboard/789
</LinkAccordion>
</div>
<div>
<Link
href="/dashboard/settings"
prefetch={false}
id="link-to-settings"
>
Static sibling: /dashboard/settings
</Link>
</div>
</section>
<section id="deeply-nested-test">
<h2>Deeply Nested Static Siblings</h2>
<p>
/categories/electronics/computers/laptops vs /categories/[slug]
(static sibling with multiple layouts along its path)
</p>
<div>
<LinkAccordion href="/categories/phones">
Dynamic route: /categories/phones
</LinkAccordion>
</div>
<div>
<Link
href="/categories/electronics/computers/laptops"
prefetch={false}
id="link-to-laptops"
>
Static sibling: /categories/electronics/computers/laptops
</Link>
</div>
</section>
</main>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: boolean
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
optimisticRouting: true,
},
}
module.exports = nextConfig
/**
* Static Siblings Tests
*
* When a dynamic route like /products/[id] exists alongside a static route
* like /products/sale at the same URL level, these are called "static
* siblings." The static route should always take precedence when navigating
* to its exact URL.
*
* Test approach:
* 1. RSC payload tests (prod only): Verify that information about static
* siblings is included in the server response. Skipped in dev because
* webpack compiles routes on-demand and only knows about visited routes.
* (Turbopack doesn't have this limitation since it builds the full
* directory tree from the file system.)
* TODO: Replace with end-to-end tests once client behavior is implemented.
*
* 2. Navigation tests (dev and prod): Navigate to the dynamic route first,
* then go back and click the static sibling link (with prefetch={false}).
* Verify the static page renders correctly.
*
* The navigation flow ensures the client has seen the dynamic route before
* attempting to navigate to the sibling. This simulates real-world usage
* where a user might visit or prefetch a dynamic route, then later navigate
* to a static sibling URL.
*/
import { nextTestSetup } from 'e2e-utils'
// TODO: These imports are only needed for the temporary RSC payload tests.
// Remove once client behavior is implemented.
import {
NEXT_RSC_UNION_QUERY,
RSC_HEADER,
} from 'next/dist/client/components/app-router-headers'
describe('static-siblings', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
// TODO: This helper is only needed for the temporary RSC payload tests.
// Remove once client behavior is implemented.
async function fetchRscResponse(url: string): Promise<string> {
const response = await next.fetch(`${url}?${NEXT_RSC_UNION_QUERY}`, {
headers: {
[RSC_HEADER]: '1',
},
})
return response.text()
}
// RSC payload tests are skipped in dev because with webpack, routes are
// compiled on-demand, so sibling information may not be available until all
// routes have been visited. (Turbopack doesn't have this limitation.)
describe('cross-route-group siblings', () => {
// TODO: Replace with end-to-end test once client behavior is implemented
if (!isNextDev) {
it('should include static sibling info in the server response', async () => {
// The static sibling 'sale' is in a different route group than [id]
const rscPayload = await fetchRscResponse('/products/123')
expect(rscPayload).toContain('"sale"')
})
}
it('should navigate to static sibling after visiting dynamic route', async () => {
const browser = await next.browser('/')
// Step 1: Navigate to the dynamic route first to "discover" it
const accordion = await browser.elementByCss(
'input[data-link-accordion="/products/123"]'
)
await accordion.click()
const dynamicLink = await browser.elementByCss('a[href="/products/123"]')
await dynamicLink.click()
// Verify we're on the dynamic route
const dynamicText = await browser.elementByCss('#product-page').text()
expect(dynamicText).toBe('Product page (dynamic route)')
// Step 2: Navigate back to the home page
await browser.back()
await browser.elementByCss('#home-page')
// Step 3: Navigate to the static sibling with prefetch={false}
const staticLink = await browser.elementByCss('#link-to-sale')
await staticLink.click()
// Verify the static sibling page rendered
const staticText = await browser.elementByCss('#sale-page').text()
expect(staticText).toBe('Sale page (static sibling)')
})
})
describe('same-directory siblings', () => {
// TODO: Replace with end-to-end test once client behavior is implemented
if (!isNextDev) {
it('should include static sibling info in the server response', async () => {
// The static sibling 'featured' is in the same directory as [id]
const rscPayload = await fetchRscResponse('/items/123')
expect(rscPayload).toContain('"featured"')
})
}
it('should navigate to static sibling after visiting dynamic route', async () => {
const browser = await next.browser('/')
// Step 1: Navigate to the dynamic route first to "discover" it
const accordion = await browser.elementByCss(
'input[data-link-accordion="/items/456"]'
)
await accordion.click()
const dynamicLink = await browser.elementByCss('a[href="/items/456"]')
await dynamicLink.click()
// Verify we're on the dynamic route
const dynamicText = await browser.elementByCss('#item-page').text()
expect(dynamicText).toBe('Item page (dynamic route)')
// Step 2: Navigate back to the home page
await browser.back()
await browser.elementByCss('#home-page')
// Step 3: Navigate to the static sibling with prefetch={false}
const staticLink = await browser.elementByCss('#link-to-featured')
await staticLink.click()
// Verify the static sibling page rendered
const staticText = await browser.elementByCss('#featured-page').text()
expect(staticText).toBe('Featured items (static sibling)')
})
})
describe('parallel route siblings', () => {
// TODO: Replace with end-to-end test once client behavior is implemented
if (!isNextDev) {
it('should include static sibling info in the server response', async () => {
// The static sibling 'settings' is in a parallel route slot
const rscPayload = await fetchRscResponse('/dashboard/123')
expect(rscPayload).toContain('"settings"')
})
}
it('should navigate to static sibling after visiting dynamic route', async () => {
const browser = await next.browser('/')
// Step 1: Navigate to the dynamic route first to "discover" it
const accordion = await browser.elementByCss(
'input[data-link-accordion="/dashboard/789"]'
)
await accordion.click()
const dynamicLink = await browser.elementByCss('a[href="/dashboard/789"]')
await dynamicLink.click()
// Verify we're on the dynamic route
const dynamicText = await browser.elementByCss('#panel-item-page').text()
expect(dynamicText).toBe('Panel item (dynamic in parallel route)')
// Step 2: Navigate back to the home page
await browser.back()
await browser.elementByCss('#home-page')
// Step 3: Navigate to the static sibling with prefetch={false}
const staticLink = await browser.elementByCss('#link-to-settings')
await staticLink.click()
// Verify the static sibling page rendered
const staticText = await browser
.elementByCss('#panel-settings-page')
.text()
expect(staticText).toBe(
'Panel settings (static sibling in parallel route)'
)
})
})
describe('deeply nested siblings', () => {
// TODO: Replace with end-to-end test once client behavior is implemented
if (!isNextDev) {
it('should include static sibling info in the server response', async () => {
// The static sibling 'electronics' is deeply nested with multiple layouts
const rscPayload = await fetchRscResponse('/categories/phones')
expect(rscPayload).toContain('"electronics"')
// Nested segments inside 'electronics' should NOT be leaked as siblings
expect(rscPayload).not.toContain('"computers"')
expect(rscPayload).not.toContain('"laptops"')
})
}
it('should navigate to static sibling after visiting dynamic route', async () => {
const browser = await next.browser('/')
// Step 1: Navigate to the dynamic route first to "discover" it
const accordion = await browser.elementByCss(
'input[data-link-accordion="/categories/phones"]'
)
await accordion.click()
const dynamicLink = await browser.elementByCss(
'a[href="/categories/phones"]'
)
await dynamicLink.click()
// Verify we're on the dynamic route
const dynamicText = await browser.elementByCss('#category-page').text()
expect(dynamicText).toContain('Dynamic category page')
// Step 2: Navigate back to the home page
await browser.back()
await browser.elementByCss('#home-page')
// Step 3: Navigate to the deeply nested static sibling with prefetch={false}
const staticLink = await browser.elementByCss('#link-to-laptops')
await staticLink.click()
// Verify the static sibling page rendered with all its layouts
const staticText = await browser.elementByCss('#laptops-page').text()
expect(staticText).toContain('Laptops')
// Verify the nested layouts are present
const electronicsLayout = await browser.elementByCss(
'[data-electronics-layout]'
)
expect(electronicsLayout).toBeTruthy()
const computersLayout = await browser.elementByCss(
'[data-computers-layout]'
)
expect(computersLayout).toBeTruthy()
const laptopsLayout = await browser.elementByCss('[data-laptops-layout]')
expect(laptopsLayout).toBeTruthy()
})
})
})
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