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 {
parallel_routes,
modules,
global_metadata,
static_siblings,
} = loader_tree;
writeln!(
......@@ -399,7 +400,15 @@ impl AppPageLoaderTreeBuilder {
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(())
}
......
......@@ -201,6 +201,84 @@ struct PlainDirectoryTree {
/// key is e.g. "dashboard", "(dashboard)", "@slot"
pub subdirectories: BTreeMap<RcStr, PlainDirectoryTree>,
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]
......@@ -213,9 +291,12 @@ impl DirectoryTree {
subdirectories.insert(name.clone(), subdirectory.into_plain().owned().await?);
}
let url_tree = build_url_segment_tree_from_subdirs(&subdirectories);
Ok(PlainDirectoryTree {
subdirectories,
modules: self.modules.clone(),
url_tree,
}
.cell())
}
......@@ -392,6 +473,10 @@ pub struct AppPageLoaderTree {
pub parallel_routes: FxIndexMap<RcStr, AppPageLoaderTree>,
pub modules: AppDirModules,
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 {
......@@ -543,6 +628,17 @@ fn is_group_route(name: &str) -> bool {
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> {
name.strip_prefix('@')
}
......@@ -991,7 +1087,8 @@ async fn directory_tree_to_loader_tree(
// the page this loader tree is constructed for
for_app_path: AppPath,
) -> 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(
app_dir,
......@@ -1001,6 +1098,7 @@ async fn directory_tree_to_loader_tree(
app_page,
for_app_path,
AppDirModules::default(),
Some(&plain_tree.url_tree),
)
.await?;
......@@ -1080,6 +1178,7 @@ async fn directory_tree_to_loader_tree_internal(
// the page this loader tree is constructed for
for_app_path: AppPath,
mut parent_modules: AppDirModules,
url_tree: Option<&UrlSegmentTree>,
) -> Result<Option<AppPageLoaderTree>> {
let app_path = AppPath::from(app_page.clone());
......@@ -1139,12 +1238,30 @@ async fn directory_tree_to_loader_tree_internal(
.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 {
page: app_page.clone(),
segment: directory_name.clone(),
parallel_routes: FxIndexMap::default(),
modules: modules.without_leaves(),
global_metadata: global_metadata.to_resolved().await?,
static_siblings,
};
let current_level_is_parallel_route = is_parallel_route(&directory_name);
......@@ -1169,6 +1286,7 @@ async fn directory_tree_to_loader_tree_internal(
..Default::default()
},
global_metadata: global_metadata.to_resolved().await?,
static_siblings: Vec::new(),
},
);
}
......@@ -1188,6 +1306,14 @@ async fn directory_tree_to_loader_tree_internal(
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(
app_dir.clone(),
global_metadata,
......@@ -1196,6 +1322,7 @@ async fn directory_tree_to_loader_tree_internal(
child_app_page.clone(),
for_app_path.clone(),
parent_modules.clone(),
child_url_tree,
))
.await?;
......@@ -1420,6 +1547,7 @@ async fn default_route_tree(
}
},
global_metadata: global_metadata.to_resolved().await?,
static_siblings: Vec::new(),
})
}
......@@ -1662,12 +1790,14 @@ async fn directory_tree_to_entrypoints_internal_untraced(
}
},
global_metadata,
static_siblings: Vec::new(),
}
},
modules: AppDirModules {
..Default::default()
},
global_metadata,
static_siblings: Vec::new(),
},
},
modules: AppDirModules {
......@@ -1690,6 +1820,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
..not_found_root_modules
},
global_metadata,
static_siblings: Vec::new(),
}
.resolved_cell();
......@@ -1728,10 +1859,12 @@ async fn directory_tree_to_entrypoints_internal_untraced(
..Default::default()
},
global_metadata,
static_siblings: Vec::new(),
}
},
modules: AppDirModules::default(),
global_metadata,
static_siblings: Vec::new(),
}
.resolved_cell();
......
......@@ -941,6 +941,7 @@ export async function createEntrypoints(
pagePath: absolutePagePath,
appDir,
appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute),
pageExtensions,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
......@@ -1019,6 +1020,7 @@ export async function createEntrypoints(
pagePath: absolutePagePath,
appDir: appDir!,
appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute),
pageExtensions,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
......
......@@ -6,6 +6,7 @@ type TestLoaderTree = [
segment: string,
parallelRoutes: { [key: string]: TestLoaderTree },
modules: Record<string, unknown>,
staticSiblings: readonly string[] | null,
]
function createLoaderTree(
......@@ -14,7 +15,7 @@ function createLoaderTree(
children?: TestLoaderTree
): TestLoaderTree {
const routes = children ? { ...parallelRoutes, children } : parallelRoutes
return [segment, routes, {}]
return [segment, routes, {}, null]
}
describe('extractPathnameRouteParamSegmentsFromLoaderTree', () => {
......
......@@ -8,6 +8,7 @@ type TestLoaderTree = [
segment: string,
parallelRoutes: { [key: string]: TestLoaderTree },
modules: Record<string, unknown>,
staticSiblings: readonly string[] | null,
]
function createLoaderTree(
......@@ -16,7 +17,7 @@ function createLoaderTree(
children?: TestLoaderTree
): TestLoaderTree {
const routes = children ? { ...parallelRoutes, children } : parallelRoutes
return [segment, routes, {}]
return [segment, routes, {}, null]
}
describe('resolveRouteParamsFromTree', () => {
......
......@@ -686,6 +686,9 @@ export async function handler(
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
optimisticRouting: Boolean(
nextConfig.experimental.optimisticRouting
),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
clientTraceMetadata:
......
......@@ -156,6 +156,7 @@ async function requestHandler(
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
clientTraceMetadata:
......
......@@ -40,6 +40,7 @@ import type { Compilation } from 'webpack'
import { createAppRouteCode } from './create-app-route-code'
import { MissingDefaultParallelRouteError } from '../../../../shared/lib/errors/missing-default-parallel-route-error'
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 { installBindings } from '../../../swc/install-bindings'
......@@ -50,6 +51,9 @@ export type AppLoaderOptions = {
pagePath: string
appDir: string
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
pageExtensions: PageExtensions
assetPrefix: string
......@@ -124,6 +128,9 @@ const normalizeParallelKey = (key: string) =>
const isCatchAllSegment = (segment: string) =>
segment.startsWith('[...') || segment.startsWith('[[...')
const isDynamicSegment = (segment: string) =>
segment.startsWith('[') && segment.endsWith(']')
const isDirectory = async (pathname: string) => {
try {
const stat = await fs.stat(pathname)
......@@ -141,11 +148,13 @@ async function createTreeCodeFromPath(
resolver,
resolveParallelSegments,
hasChildRoutesForSegment,
getStaticSiblingSegments,
metadataResolver,
pageExtensions,
basePath,
collectedDeclarations,
isGlobalNotFoundEnabled,
isDev,
}: {
page: string
resolveDir: DirResolver
......@@ -155,11 +164,13 @@ async function createTreeCodeFromPath(
pathname: string
) => [key: string, segment: string | string[]][]
hasChildRoutesForSegment: (segmentPath: string) => boolean
getStaticSiblingSegments: (segmentPath: string) => string[]
loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: PageExtensions
basePath: string
collectedDeclarations: [string, string][]
isGlobalNotFoundEnabled: boolean
isDev: boolean
}
): Promise<{
treeCode: string
......@@ -535,10 +546,16 @@ async function createTreeCodeFromPath(
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] = `[
'${parallelSegmentKey}',
${subtreeCode},
${modulesCode}
${modulesCode},
${staticSiblingsCode}
]`
}
......@@ -661,6 +678,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
name,
appDir,
appPaths,
allNormalizedAppPaths: allNormalizedAppPathsOption,
pagePath,
pageExtensions,
rootDir,
......@@ -709,6 +727,9 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const normalizedAppPaths =
typeof appPaths === 'string' ? [appPaths] : appPaths || []
// All normalized app paths for computing static siblings across route groups
const allNormalizedAppPaths = allNormalizedAppPathsOption ?? []
const resolveParallelSegments = (
pathname: string
): [string, string | string[]][] => {
......@@ -810,6 +831,91 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
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) => {
return createAbsolutePath(appDir, pathToResolve)
}
......@@ -917,11 +1023,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
metadataResolver,
resolveParallelSegments,
hasChildRoutesForSegment,
getStaticSiblingSegments,
loaderContext: this,
pageExtensions,
basePath,
collectedDeclarations,
isGlobalNotFoundEnabled,
isDev: !!isDev,
})
const isGlobalNotFoundPath =
......@@ -975,11 +1083,13 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
metadataResolver,
resolveParallelSegments,
hasChildRoutesForSegment,
getStaticSiblingSegments,
loaderContext: this,
pageExtensions,
basePath,
collectedDeclarations,
isGlobalNotFoundEnabled,
isDev: !!isDev,
})
}
}
......
......@@ -15,7 +15,7 @@ describe('computeChangedPath', () => {
'(...)stats',
{
children: [
['key', 'github', 'd'],
['key', 'github', 'd', null],
{
children: ['__PAGE__', {}],
},
......@@ -40,7 +40,7 @@ describe('computeChangedPath', () => {
'(...)stats',
{
children: [
['key', 'github', 'd'],
['key', 'github', 'd', null],
{
children: ['__PAGE__', {}],
},
......
......@@ -6,14 +6,14 @@ describe('createRouterCacheKey', () => {
})
it('should support dynamic segment', () => {
expect(createRouterCacheKey(['slug', 'hello-world', 'd'])).toEqual(
expect(createRouterCacheKey(['slug', 'hello-world', 'd', null])).toEqual(
'slug|hello-world|d'
)
})
it('should support catch all segment', () => {
expect(createRouterCacheKey(['slug', 'blog/hello-world', 'c'])).toEqual(
'slug|blog/hello-world|c'
)
expect(
createRouterCacheKey(['slug', 'blog/hello-world', 'c', null])
).toEqual('slug|blog/hello-world|c')
})
})
......@@ -68,7 +68,7 @@ describe('shouldHardNavigate', () => {
'link-hard-push',
{
children: [
['id', '123', 'd'],
['id', '123', 'd', null],
{
children: ['', {}],
},
......@@ -87,14 +87,14 @@ describe('shouldHardNavigate', () => {
'children',
'link-hard-push',
'children',
['id', '123', 'd'],
['id', '123', 'd', null],
[
['id', '123', 'd'],
['id', '123', 'd', null],
{
children: ['', {}],
},
],
[['id', '123', 'd'], {}, null],
[['id', '123', 'd', null], {}, null],
null,
],
]
......@@ -125,7 +125,7 @@ describe('shouldHardNavigate', () => {
'link-hard-push',
{
children: [
['id', '456', 'd'],
['id', '456', 'd', null],
{
children: ['', {}],
},
......@@ -144,14 +144,14 @@ describe('shouldHardNavigate', () => {
'children',
'link-hard-push',
'children',
['id', '123', 'd'],
['id', '123', 'd', null],
[
['id', '123', 'd'],
['id', '123', 'd', null],
{
children: ['', {}],
},
],
[['id', '123', 'd'], {}, null],
[['id', '123', 'd', null], {}, null],
null,
false,
],
......
......@@ -1064,17 +1064,16 @@ function convertTreePrefetchToRouteTree(
slots = {}
for (let parallelRouteKey in prefetchSlots) {
const childPrefetch = prefetchSlots[parallelRouteKey]
const childParamName = childPrefetch.name
const childParamType = childPrefetch.paramType
const childServerSentParamKey = childPrefetch.paramKey
const childSegmentName = childPrefetch.name
const childParam = childPrefetch.param
let childDoesAppearInURL: boolean
let childSegment: FlightRouterStateSegment
let childPartialVaryPath: PartialSegmentVaryPath | null
if (childParamType !== null) {
if (childParam !== null) {
// This segment is parameterized. Get the param from the pathname.
const childParamValue = parseDynamicParamFromURLPart(
childParamType,
childParam.type,
pathnameParts,
pathnamePartsIndex
)
......@@ -1092,8 +1091,8 @@ function convertTreePrefetchToRouteTree(
const childParamKey =
// The server omits this field from the prefetch response when
// cacheComponents is enabled.
childServerSentParamKey !== null
? childServerSentParamKey
childParam.key !== null
? childParam.key
: // If no param key was sent, use the value parsed on the client.
getCacheKeyForDynamicParam(
childParamValue,
......@@ -1104,14 +1103,19 @@ function convertTreePrefetchToRouteTree(
partialVaryPath,
childParamKey
)
childSegment = [childParamName, childParamKey, childParamType]
childSegment = [
childSegmentName,
childParamKey,
childParam.type,
childParam.siblings,
]
childDoesAppearInURL = true
} else {
// This segment does not have a param. Inherit the partial vary path of
// the parent.
childPartialVaryPath = partialVaryPath
childSegment = childParamName
childDoesAppearInURL = doesStaticSegmentAppearInURL(childParamName)
childSegment = childSegmentName
childDoesAppearInURL = doesStaticSegmentAppearInURL(childSegmentName)
}
// Only increment the index if the segment appears in the URL. If it's a
......
......@@ -46,7 +46,12 @@ describe('prepareFlightRouterStateForRequest', () => {
})
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 result = prepareFlightRouterStateForRequest(flightRouterState)
......@@ -266,7 +271,12 @@ describe('prepareFlightRouterStateForRequest', () => {
true,
1,
],
sidebar: [['slug', 'user-123', 'd'], {}, ['/sidebar/url', ''], null],
sidebar: [
['slug', 'user-123', 'd', null],
{},
['/sidebar/url', ''],
null,
],
},
['/main/url', ''],
'inside-shared-layout',
......@@ -300,7 +310,7 @@ describe('prepareFlightRouterStateForRequest', () => {
// Sidebar route (dynamic segment) checks
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[3]).toBeUndefined() // null marker stripped
})
......
......@@ -152,13 +152,14 @@ function fillInFallbackFlightRouterStateImpl(
} else {
const paramName = originalSegment[0]
const paramType = originalSegment[2]
const staticSiblings = originalSegment[3]
const paramValue = parseDynamicParamFromURLPart(
paramType,
pathnameParts,
pathnamePartsIndex
)
const cacheKey = getCacheKeyForDynamicParam(paramValue, renderedSearch)
newSegment = [paramName, cacheKey, paramType]
newSegment = [paramName, cacheKey, paramType, staticSiblings]
doesAppearInURL = true
}
......@@ -250,9 +251,8 @@ function stripClientOnlyDataFromFlightRouterState(
hasLoadingBoundary,
] = flightRouterState
// __PAGE__ segments are always fetched from the server, so there's
// no need to send them up
const cleanedSegment = stripSearchParamsFromPageSegment(segment)
// Strip client-only data from the segment
const cleanedSegment = stripClientOnlyDataFromSegment(segment)
// Recursively process parallel routes
const cleanedParallelRoutes: { [key: string]: FlightRouterState } = {}
......@@ -280,15 +280,21 @@ function stripClientOnlyDataFromFlightRouterState(
}
/**
* Strips search parameters from __PAGE__ segments to prevent sensitive
* client-side data from being sent to the server.
* Strips client-only data from segments:
* - Search parameters from __PAGE__ segments
* - staticSiblings from dynamic segment tuples (only needed for client-side
* prefetch reuse decisions)
*/
function stripSearchParamsFromPageSegment(segment: Segment): Segment {
if (
typeof segment === 'string' &&
segment.startsWith(PAGE_SEGMENT_KEY + '?')
) {
return PAGE_SEGMENT_KEY
function stripClientOnlyDataFromSegment(segment: Segment): Segment {
if (typeof segment === 'string') {
// Strip search params from __PAGE__ segments
if (segment.startsWith(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(
clientParamParsingOrigins:
nextConfig.experimental.clientParamParsingOrigins,
dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,
optimisticRouting: nextConfig.experimental.optimisticRouting ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
......
......@@ -746,7 +746,7 @@ async function resolveMetadataItemsImpl(
const isPage = typeof page !== 'undefined'
// Handle dynamic segment params.
const segmentParam = getDynamicParamFromSegment(segment)
const segmentParam = getDynamicParamFromSegment(tree)
/**
* Create object holding the parent params and current params
*/
......@@ -842,7 +842,7 @@ async function resolveViewportItemsImpl(
const isPage = typeof page !== 'undefined'
// Handle dynamic segment params.
const segmentParam = getDynamicParamFromSegment(segment)
const segmentParam = getDynamicParamFromSegment(tree)
/**
* Create object holding the parent params and current params
*/
......
......@@ -3,8 +3,8 @@ import type { RenderOpts, PreloadCallbacks } from './types'
import type {
ActionResult,
DynamicParamTypesShort,
DynamicSegmentTuple,
FlightRouterState,
Segment,
CacheNodeSeedData,
RSCPayload,
FlightData,
......@@ -219,14 +219,14 @@ import { anySegmentHasRuntimePrefetchEnabled } from './staged-validation'
import { warnOnce } from '../../shared/lib/utils/warn-once'
export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug]
segment: string
// The LoaderTree to extract the dynamic param from
loaderTree: LoaderTree
) => DynamicParam | null
export type DynamicParam = {
param: string
value: string | string[] | null
treeSegment: Segment
treeSegment: DynamicSegmentTuple
type: DynamicParamTypesShort
}
......@@ -385,10 +385,11 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
return [
'',
{
children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents],
children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents, null],
},
// When global-not-found is present, skip layout from components
hasGlobalNotFound ? components : {},
null, // staticSiblings
]
}
......@@ -397,23 +398,25 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
*/
function makeGetDynamicParamFromSegment(
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null
fallbackRouteParams: OpaqueFallbackRouteParams | null,
optimisticRouting: boolean
): GetDynamicParamFromSegment {
return function getDynamicParamFromSegment(
// [slug] / [[slug]] / [...slug]
segment: string
) {
return function getDynamicParamFromSegment(loaderTree: LoaderTree) {
const [segment, , , staticSiblings] = loaderTree
const segmentParam = getSegmentParam(segment)
if (!segmentParam) {
return null
}
const segmentKey = segmentParam.paramName
const dynamicParamType = dynamicParamTypes[segmentParam.paramType]
// Static siblings are only included when optimistic routing is enabled
const siblings = optimisticRouting ? staticSiblings : null
return getDynamicParam(
interpolatedParams,
segmentKey,
dynamicParamType,
fallbackRouteParams
fallbackRouteParams,
siblings
)
}
}
......@@ -2012,7 +2015,8 @@ async function renderToHTMLOrFlightImpl(
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(
interpolatedParams,
fallbackRouteParams
fallbackRouteParams,
renderOpts.experimental.optimisticRouting
)
const isPossibleActionRequest = getIsPossibleServerAction(req)
......
......@@ -40,13 +40,25 @@ export type RootTreePrefetch = {
staleTime: number
}
export type TreePrefetch = {
name: string
paramType: DynamicParamTypesShort | null
export type TreePrefetchParam = {
type: DynamicParamTypesShort
// When cacheComponents is enabled, this field is always null.
// Instead we parse the param on the client, allowing us to omit it from
// 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.
slots: null | {
......@@ -320,27 +332,27 @@ function collectSegmentDataImpl(
}
const segment = route[0]
let name
let paramType: DynamicParamTypesShort | null = null
let paramKey: string | null = null
let name: string
let param: TreePrefetchParam | null
if (typeof segment === 'string') {
name = segment
paramKey = segment
paramType = null
param = null
} else {
name = segment[0]
paramKey = segment[1]
paramType = segment[2] as DynamicParamTypesShort
param = {
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
// tree prefetch.
return {
name,
paramType,
// This value is ommitted from the prefetch response when cacheComponents
// is enabled.
paramKey: isClientParamParsingEnabled ? null : paramKey,
param,
hasRuntimePrefetch,
slots: slotMetadata,
isRootLayout: route[4] === true,
......
......@@ -403,7 +403,7 @@ async function createComponentTreeInternal(
}
// Handle dynamic segment params.
const segmentParam = getDynamicParamFromSegment(segment)
const segmentParam = getDynamicParamFromSegment(tree)
// Create object holding the parent params and current params
let currentParams: Params = parentParams
......@@ -1104,12 +1104,11 @@ function getRootParamsImpl(
getDynamicParamFromSegment: GetDynamicParamFromSegment
): Params {
const {
segment,
modules: { layout },
parallelRoutes,
} = parseLoaderTree(loaderTree)
const segmentParam = getDynamicParamFromSegment(segment)
const segmentParam = getDynamicParamFromSegment(loaderTree)
let currentParams: Params = parentParams
if (segmentParam && segmentParam.value !== null) {
......
......@@ -7,13 +7,14 @@ import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
function createFlightRouterStateFromLoaderTreeImpl(
[segment, parallelRoutes, { layout, loading }]: LoaderTree,
loaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
includeHasLoadingBoundary: boolean,
didFindRootLayout: boolean
): FlightRouterState {
const dynamicParam = getDynamicParamFromSegment(segment)
const [segment, parallelRoutes, { layout, loading }] = loaderTree
const dynamicParam = getDynamicParamFromSegment(loaderTree)
const treeSegment = dynamicParam ? dynamicParam.treeSegment : segment
const segmentTree: FlightRouterState = [
......
......@@ -181,7 +181,8 @@ export function parsePostponedState(
interpolatedParams,
segmentKey,
dynamicParamType,
null
null,
null // staticSiblings not needed for postponed state
)
postponed = postponed.replaceAll(searchValue, value)
......
......@@ -3,27 +3,27 @@ import { assert } from 'next/dist/compiled/superstruct'
const validFixtures = [
[
['a', 'b', 'c'],
['a', 'b', 'c', null],
{
a: [['a', 'b', 'c'], {}],
b: [['a', 'b', 'c'], {}],
a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c', null], {}],
},
],
[
['a', 'b', 'c'],
['a', 'b', 'c', ['sibling1', 'sibling2']],
{
a: [['a', 'b', 'c'], {}],
b: [['a', 'b', 'c'], {}],
a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c', []], {}],
},
null,
null,
true,
],
[
['a', 'b', 'c'],
['a', 'b', 'c', null],
{
a: [['a', 'b', 'c'], {}],
b: [['a', 'b', 'c'], {}],
a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c', null], {}],
},
null,
'refetch',
......@@ -33,14 +33,20 @@ const validFixtures = [
const invalidFixtures = [
// plain wrong
['1', 'b', 'c'],
// invalid enum
// invalid enum (missing 4th element)
[['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
[
['a', 'b', 'c'],
['a', 'b', 'c', null],
{
a: [['a', 'b', 'c'], {}],
b: [['a', 'b', 'c'], {}],
a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c', null], {}],
},
{
invalid: 'invalid',
......@@ -48,10 +54,10 @@ const invalidFixtures = [
],
// invalid isRootLayout
[
['a', 'b', 'c'],
['a', 'b', 'c', null],
{
a: [['a', 'b', 'c'], {}],
b: [['a', 'b', 'c'], {}],
a: [['a', 'b', 'c', null], {}],
b: [['a', 'b', 'c', null], {}],
},
null,
1,
......
......@@ -49,6 +49,10 @@ const segmentSchema = s.union([
s.string(),
// Dynamic param type
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 {
*/
clientParamParsingOrigins: string[] | undefined
dynamicOnHover: boolean
optimisticRouting: boolean
inlineCss: boolean
authInterrupts: boolean
......
......@@ -77,7 +77,7 @@ export async function walkTreeWithFlightRouterState({
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
const segmentParam = getDynamicParamFromSegment(segment)
const segmentParam = getDynamicParamFromSegment(loaderTreeToFilter)
const currentParams =
// Handle null case where dynamic param is optional
segmentParam && segmentParam.value !== null
......
......@@ -562,6 +562,8 @@ export default abstract class Server<
clientParamParsingOrigins:
this.nextConfig.experimental.clientParamParsingOrigins,
dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,
optimisticRouting:
this.nextConfig.experimental.optimisticRouting ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
......
......@@ -195,6 +195,7 @@ export const experimentalSchema = {
caseSensitiveRoutes: z.boolean().optional(),
clientParamParsingOrigins: z.array(z.string()).optional(),
dynamicOnHover: z.boolean().optional(),
optimisticRouting: z.boolean().optional(),
disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(),
cacheComponents: z.boolean().optional(),
......
......@@ -287,6 +287,7 @@ export interface ExperimentalConfig {
*/
clientParamParsingOrigins?: string[]
dynamicOnHover?: boolean
optimisticRouting?: boolean
preloadEntriesOnStart?: boolean
clientRouterFilter?: boolean
clientRouterFilterRedirects?: boolean
......@@ -1669,6 +1670,7 @@ export interface NextConfigRuntime {
| 'serverActions'
| 'staleTimes'
| 'dynamicOnHover'
| 'optimisticRouting'
| 'inlineCss'
| 'authInterrupts'
| 'clientTraceMetadata'
......@@ -1730,6 +1732,7 @@ export function getNextConfigRuntime(
serverActions: ex.serverActions,
staleTimes: ex.staleTimes,
dynamicOnHover: ex.dynamicOnHover,
optimisticRouting: ex.optimisticRouting,
inlineCss: ex.inlineCss,
authInterrupts: ex.authInterrupts,
clientTraceMetadata: ex.clientTraceMetadata,
......
......@@ -1027,6 +1027,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
name: bundlePath,
page,
appPaths: entryData.appPaths,
allNormalizedAppPaths: null, // Not available in dev mode
pagePath: posix.join(
APP_DIR_ALIAS,
relative(
......@@ -1156,6 +1157,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
name: bundlePath,
page,
appPaths: entryData.appPaths,
allNormalizedAppPaths: null, // Not available in dev mode
pagePath,
appDir: this.appDir!,
pageExtensions: this.config.pageExtensions,
......
......@@ -8,6 +8,24 @@ export type LoaderTree = [
segment: string,
parallelRoutes: { [parallelRouterKey: string]: LoaderTree },
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) {
......
......@@ -11,6 +11,7 @@ type TestLoaderTree = [
segment: string,
parallelRoutes: { [key: string]: TestLoaderTree },
modules: Record<string, unknown>,
staticSiblings: readonly string[] | null,
]
function createLoaderTree(
......@@ -19,7 +20,7 @@ function createLoaderTree(
children?: TestLoaderTree
): TestLoaderTree {
const routes = children ? { ...parallelRoutes, children } : parallelRoutes
return [segment, routes, {}]
return [segment, routes, {}, null]
}
/**
......
......@@ -75,21 +75,29 @@ export type DynamicParamTypesShort =
| 'di(..)'
| 'di(...)'
export type Segment =
| string
| [
// Param name
paramName: string,
// Param cache key (almost the same as the value, but arrays are
// concatenated into strings)
// 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
// a string when converted to a a cache key, but that doesn't mean we
// need to store it as that representation.
paramCacheKey: string,
// Dynamic param type
dynamicParamType: DynamicParamTypesShort,
]
// The tuple form of a segment, used for dynamic route params
export type DynamicSegmentTuple = [
// Param name
paramName: string,
// Param cache key (almost the same as the value, but arrays are
// concatenated into strings)
// 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
// a string when converted to a a cache key, but that doesn't mean we
// need to store it as that representation.
paramCacheKey: string,
// Dynamic param type
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
......
......@@ -121,7 +121,8 @@ export function getDynamicParam(
interpolatedParams: Params,
segmentKey: string,
dynamicParamType: DynamicParamTypesShort,
fallbackRouteParams: OpaqueFallbackRouteParams | null
fallbackRouteParams: OpaqueFallbackRouteParams | null,
staticSiblings: readonly string[] | null
): DynamicParam {
let value: string | string[] | undefined = getParamValue(
interpolatedParams,
......@@ -137,7 +138,7 @@ export function getDynamicParam(
param: segmentKey,
value: null,
type: dynamicParamType,
treeSegment: [segmentKey, '', dynamicParamType],
treeSegment: [segmentKey, '', dynamicParamType, staticSiblings],
}
}
......@@ -146,16 +147,18 @@ export function getDynamicParam(
)
}
const paramCacheKey = Array.isArray(value) ? value.join('/') : value
return {
param: segmentKey,
// The value that is passed to user code.
value,
// The value that is rendered in the router tree.
treeSegment: [
segmentKey,
Array.isArray(value) ? value.join('/') : value,
dynamicParamType,
],
// TODO: If the number of static siblings exceeds some threshold (e.g.,
// dozens or hundreds), consider sending a Bloom filter instead of the full
// array to reduce payload size. The client would then use the Bloom filter
// to check membership with a small false positive rate.
treeSegment: [segmentKey, paramCacheKey, dynamicParamType, staticSiblings],
type: dynamicParamType,
}
}
......
......@@ -2,7 +2,7 @@ import { DEFAULT_SEGMENT_KEY } from '../../segment'
import type { LoaderTree } from '../../../../server/lib/app-dir-module'
export function parseLoaderTree(tree: LoaderTree) {
const [segment, parallelRoutes, modules] = tree
const [segment, parallelRoutes, modules, staticSiblings] = tree
const { layout, template } = modules
let { page } = modules
// a __DEFAULT__ segment means that this route didn't match any of the
......@@ -18,5 +18,6 @@ export function parseLoaderTree(tree: LoaderTree) {
/* it can be either layout / template / page */
conventionPath,
parallelRoutes,
staticSiblings,
}
}
......@@ -6,11 +6,13 @@ describe('getSegmentValue', () => {
})
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', () => {
expect(getSegmentValue(['slug', 'blog/hello-world', 'c'])).toEqual(
expect(getSegmentValue(['slug', 'blog/hello-world', 'c', null])).toEqual(
'blog/hello-world'
)
})
......
......@@ -247,7 +247,7 @@ describe('app dir - prefetching', () => {
'prefetch-auto',
{
children: [
['slug', 'vercel', 'd'],
['slug', 'vercel', 'd', null],
{ 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