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

Relax default.tsx validation for parallel routes leaf segments (#84767)

### What?

Relaxes the overly strict `default.tsx` validation for parallel routes
to only require the file when it's actually needed (non-leaf segments
with routable children).

### Why?

The initial validation for parallel routes required `default.tsx` files
for all parallel route slots to prevent a specific issue: when
navigating to child routes, missing `default.tsx` files could cause
silent 404s in slot content, creating a confusing user experience.

However, this validation was **too strict** - it required `default.tsx`
even in cases where it wasn't actually necessary:

1. **Leaf segments** (routes with no child routes) - There are no child
routes to navigate to, so the 404 issue cannot occur
2. **Route groups** - These are organizational folders and aren't
routable themselves
3. **Catch-all parameters** - The matched segments are dynamic parameter
values, not actual child route segments

This caused false positive build errors for valid parallel route
configurations that don't have the underlying navigational issue.

NAR-448
parent c2863c87
......@@ -896,15 +896,24 @@ impl Issue for MissingDefaultParallelRouteIssue {
#[turbo_tasks::function]
async fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(
StyledString::Text(
format!(
"The parallel route slot \"@{}\" is missing a default.js file. When using \
parallel routes, each slot must have a default.js file to serve as a \
fallback.\n\nCreate a default.js file at: {}/@{}/default.js",
self.slot_name, self.app_page, self.slot_name
)
.into(),
)
StyledString::Stack(vec![
StyledString::Text(
format!(
"The parallel route slot \"@{}\" is missing a default.js file. When using \
parallel routes, each slot must have a default.js file to serve as a \
fallback.",
self.slot_name
)
.into(),
),
StyledString::Text(
format!(
"Create a default.js file at: {}/@{}/default.js",
self.app_page, self.slot_name
)
.into(),
),
])
.resolved_cell(),
))
}
......@@ -940,6 +949,32 @@ fn page_path_except_parallel(loader_tree: &AppPageLoaderTree) -> Option<AppPage>
None
}
/// Checks if a directory tree has child routes (non-parallel, non-group routes).
/// Leaf segments don't need default.js because there are no child routes
/// that could cause the parallel slot to unmatch.
fn has_child_routes(directory_tree: &PlainDirectoryTree) -> bool {
for (name, subdirectory) in &directory_tree.subdirectories {
// Skip parallel routes (start with '@')
if is_parallel_route(name) {
continue;
}
// Skip route groups, but check if they have pages inside
if is_group_route(name) {
// Recursively check if the group has child routes
if has_child_routes(subdirectory) {
return true;
}
continue;
}
// If we get here, it's a regular route segment (child route)
return true;
}
false
}
async fn check_duplicate(
duplicate: &mut FxHashMap<AppPath, AppPage>,
loader_tree: &AppPageLoaderTree,
......@@ -1200,9 +1235,20 @@ async fn directory_tree_to_loader_tree_internal(
// /[...catchAll]/@slot - is_inside_catchall = true (skip validation) ✓
// /@slot/[...catchAll] - is_inside_catchall = false (require default) ✓
// The catch-all provides fallback behavior, so default.js is not required.
//
// Also skip validation if this is a leaf segment (no child routes).
// Leaf segments don't need default.js because there are no child routes
// that could cause the parallel slot to unmatch. For example:
// /repo-overview/@slot/page with no child routes - is_leaf_segment = true (skip
// validation) ✓ /repo-overview/@slot/page with
// /repo-overview/child/page - is_leaf_segment = false (require default) ✓
// This also handles route groups correctly by filtering them out.
let is_leaf_segment = !has_child_routes(directory_tree);
if key != "children"
&& subdirectory.modules.default.is_none()
&& !is_inside_catchall
&& !is_leaf_segment
{
missing_default_parallel_route_issue(
app_dir.clone(),
......@@ -1275,10 +1321,14 @@ async fn directory_tree_to_loader_tree_internal(
let is_inside_catchall = app_page.is_catchall();
// Check if this is a leaf segment (no child routes).
let is_leaf_segment = !has_child_routes(directory_tree);
// Only emit the issue if this is not the children slot and there's no default
// component. The children slot is implicit and doesn't require a default.js
// file. Also skip validation if the slot is UNDER a catch-all route.
if default.is_none() && key != "children" && !is_inside_catchall {
// file. Also skip validation if the slot is UNDER a catch-all route or if
// this is a leaf segment (no child routes).
if default.is_none() && key != "children" && !is_inside_catchall && !is_leaf_segment {
missing_default_parallel_route_issue(
app_dir.clone(),
app_page.clone(),
......
......@@ -135,6 +135,7 @@ async function createTreeCodeFromPath(
resolveDir,
resolver,
resolveParallelSegments,
hasChildRoutesForSegment,
metadataResolver,
pageExtensions,
basePath,
......@@ -148,6 +149,7 @@ async function createTreeCodeFromPath(
resolveParallelSegments: (
pathname: string
) => [key: string, segment: string | string[]][]
hasChildRoutesForSegment: (segmentPath: string) => boolean
loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: PageExtensions
basePath: string
......@@ -560,9 +562,23 @@ async function createTreeCodeFromPath(
// /@slot/[...catchAll] - isInsideCatchAll = false (require default) ✓
// The catch-all provides fallback behavior, so default.js is not required.
const isInsideCatchAll = segments.some(isCatchAllSegment)
if (!isInsideCatchAll) {
// Check if this is a leaf segment (no child routes).
// Leaf segments don't need default.js because there are no child routes
// that could cause the parallel slot to unmatch. For example:
// /repo-overview/@slot/page with no child routes - isLeafSegment = true (skip validation) ✓
// /repo-overview/@slot/page with /repo-overview/child/page - isLeafSegment = false (require default) ✓
// This also handles route groups correctly by filtering them out.
const isLeafSegment = !hasChildRoutesForSegment(segmentPath)
if (!isInsideCatchAll && !isLeafSegment) {
// Replace internal webpack alias with user-facing directory name
const userFacingPath = fullSegmentPath.replace(
APP_DIR_ALIAS,
'app'
)
throw new MissingDefaultParallelRouteError(
fullSegmentPath,
userFacingPath,
adjacentParallelSegment
)
}
......@@ -726,6 +742,44 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
return Object.entries(matched)
}
const hasChildRoutesForSegment = (segmentPath: string): boolean => {
const pathPrefix = segmentPath ? `${segmentPath}/` : ''
for (const appPath of normalizedAppPaths) {
if (appPath.startsWith(pathPrefix)) {
const rest = appPath.slice(pathPrefix.length).split('/')
// Filter out route groups to get the actual route segments
// Route groups (e.g., "(group)") don't contribute to the URL path
const routeSegments = rest.filter((segment) => !isGroupSegment(segment))
// If it's just 'page' at this level, skip (not a child route)
if (routeSegments.length === 1 && routeSegments[0] === 'page') {
continue
}
// If the first segment (after filtering route groups) is a parallel route, skip
if (routeSegments[0]?.startsWith('@')) {
continue
}
// If we have more than just 'page', then there are child routes
// Examples:
// ['child', 'page'] -> true (has child route)
// ['page'] -> false (already filtered above)
// ['grandchild', 'deeper', 'page'] -> true (has nested child routes)
if (
routeSegments.length > 1 ||
(routeSegments.length === 1 && routeSegments[0] !== 'page')
) {
return true
}
}
}
return false
}
const resolveDir: DirResolver = (pathToResolve) => {
return createAbsolutePath(appDir, pathToResolve)
}
......@@ -832,6 +886,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
resolver,
metadataResolver,
resolveParallelSegments,
hasChildRoutesForSegment,
loaderContext: this,
pageExtensions,
basePath,
......@@ -889,6 +944,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
resolver,
metadataResolver,
resolveParallelSegments,
hasChildRoutesForSegment,
loaderContext: this,
pageExtensions,
basePath,
......
......@@ -8,5 +8,9 @@ export class MissingDefaultParallelRouteError extends Error {
)
this.name = 'MissingDefaultParallelRouteError'
// This error is meant to interrupt the server start/build process
// but the stack trace isn't meaningful, as it points to internal code.
this.stack = undefined
}
}
# Build Error Scenarios
This fixture contains scenarios that **SHOULD throw `MissingDefaultParallelRouteError`** during build.
## Why These Should Error
All scenarios in this fixture have:
1. ✅ Parallel routes (slots starting with `@`)
2. ❌ **NO** `default.tsx` files for those parallel routes
3. ✅ **Child routes** that make these **non-leaf segments**
The presence of child routes means `default.tsx` files are required for the parallel slots.
---
## Scenario 1: Non-Leaf Segment with Children
**Path:** `/with-children`
```
app/with-children/
├── @header/
│ └── page.tsx ← Has page.tsx
│ ❌ NO default.tsx! ← Missing default.tsx
├── @sidebar/
│ └── page.tsx ← Has page.tsx
│ ❌ NO default.tsx! ← Missing default.tsx
├── layout.tsx ← Uses @header and @sidebar
├── page.tsx ← Parent page
└── child/
└── page.tsx ← ⚠️ CHILD ROUTE EXISTS!
```
**Expected Error:**
```
MissingDefaultParallelRouteError:
Missing required default.js file for parallel route at /with-children/@header
The parallel route slot "@header" is missing a default.js file.
```
**Why it errors:**
- When navigating from `/with-children` to `/with-children/child`, the routing system needs to know what to render for the `@header` and `@sidebar` slots
- Since `/with-children/child` doesn't define these parallel routes, Next.js looks for `default.tsx` files
- No `default.tsx` files exist → ERROR!
---
## Scenario 2: Non-Leaf with Route Groups and Children
**Path:** `/with-groups-and-children`
```
app/with-groups-and-children/(dashboard)/(overview)/
├── @analytics/
│ └── page.tsx ← Has page.tsx
│ ❌ NO default.tsx! ← Missing default.tsx
├── @metrics/
│ └── page.tsx ← Has page.tsx
│ ❌ NO default.tsx! ← Missing default.tsx
├── layout.tsx ← Uses @analytics and @metrics
├── page.tsx ← Parent page
└── nested/
└── page.tsx ← ⚠️ CHILD ROUTE EXISTS!
```
**Route Groups:** `(dashboard)` and `(overview)` don't affect the URL
**Expected Error:**
```
MissingDefaultParallelRouteError:
Missing required default.js file for parallel route at /with-groups-and-children/(dashboard)/(overview)/@analytics
The parallel route slot "@analytics" is missing a default.js file.
```
**Why it errors:**
- Even with route groups, the segment has a child route (`/nested`)
- The `hasChildRoutesForSegment()` helper correctly:
1. Filters out route groups `(dashboard)` and `(overview)`
2. Detects the `nested/page.tsx` child route
3. Identifies this as a **non-leaf segment**
- No `default.tsx` files exist → ERROR!
---
## How to Fix These Errors
To make these scenarios build successfully, add `default.tsx` files:
### For Scenario 1:
```tsx
// app/with-children/@header/default.tsx
export default function HeaderDefault() {
return <div>Header Fallback</div>
}
// app/with-children/@sidebar/default.tsx
export default function SidebarDefault() {
return <div>Sidebar Fallback</div>
}
```
### For Scenario 2:
```tsx
// app/with-groups-and-children/(dashboard)/(overview)/@analytics/default.tsx
export default function AnalyticsDefault() {
return <div>Analytics Fallback</div>
}
// app/with-groups-and-children/(dashboard)/(overview)/@metrics/default.tsx
export default function MetricsDefault() {
return <div>Metrics Fallback</div>
}
```
---
## Contrast with `no-build-error` Fixture
The `no-build-error` fixture has similar parallel routes but:
- ❌ **NO child routes** (leaf segments)
- ✅ `default.tsx` files are **NOT required**
This fixture (build-error) has:
- ✅ **Child routes exist** (non-leaf segments)
- ❌ `default.tsx` files **ARE required** but missing → **ERROR!**
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Build Error Scenarios Test</h1>
<p>
These routes SHOULD cause MissingDefaultParallelRouteError because they
have parallel routes without default.tsx files AND have child routes.
</p>
<nav>
<ul>
<li>
<Link href="/with-children">
Non-Leaf Segment with Children (SHOULD ERROR)
</Link>
</li>
<li>
<Link href="/with-groups-and-children">
Non-Leaf with Route Groups and Children (SHOULD ERROR)
</Link>
</li>
</ul>
</nav>
</div>
)
}
export default function HeaderSlot() {
return (
<div>
<h3>Header Slot (Parent)</h3>
<p>This is the @header parallel route</p>
</div>
)
}
export default function ChildPage() {
return (
<div>
<h2>Child Page</h2>
<p>
This child route exists, which means the parent segment is NOT a leaf.
</p>
<p>
ERROR: The @header and @sidebar slots should have default.tsx files!
</p>
</div>
)
}
export default function WithChildrenLayout({
children,
header,
}: {
children: React.ReactNode
header: React.ReactNode
}) {
return (
<div>
<div className="header">{header}</div>
<div className="container">
<div className="main">{children}</div>
</div>
</div>
)
}
import Link from 'next/link'
export default function WithChildrenPage() {
return (
<div>
<h2>Parent Page</h2>
<p>This is a NON-leaf segment with child routes.</p>
<nav>
<Link href="/with-children/child">Go to Child</Link>
</nav>
</div>
)
}
export default function MetricsSlot() {
return (
<div>
<h4>Metrics Slot (Parent)</h4>
<p>This is the @metrics parallel route with route groups</p>
</div>
)
}
export default function GroupedWithChildrenLayout({
children,
metrics,
}: {
children: React.ReactNode
metrics: React.ReactNode
}) {
return (
<div>
<h2>Parent with Route Groups</h2>
<div className="grouped-container">
<div className="main">{children}</div>
<div className="metrics">{metrics}</div>
</div>
</div>
)
}
export default function NestedPage() {
return (
<div>
<h3>Nested Child Page</h3>
<p>
This child route exists under a path with route groups, making the
parent a non-leaf segment.
</p>
<p>
ERROR: The @analytics and @metrics slots should have default.tsx files!
</p>
<p>
Even though the parent has route groups, the hasChildRoutesForSegment
helper correctly filters them out and detects this nested child route.
</p>
</div>
)
}
import Link from 'next/link'
export default function GroupedParentPage() {
return (
<div>
<h3>Parent with Route Groups</h3>
<p>
This segment has route groups (dashboard) and (overview), but it's NOT a
leaf because child routes exist.
</p>
<nav>
<Link href="/with-groups-and-children/nested">Go to Nested</Link>
</nav>
</div>
)
}
import NotRoutableComponent from './not/routable/component'
export default function FooterSlot() {
return (
<div>
<h3>Catch-All Footer Slot</h3>
<p>This is the @footer parallel route in a catch-all segment</p>
<NotRoutableComponent />
</div>
)
}
export default function HeaderSlot() {
return (
<div>
<h3>Catch-All Header Slot</h3>
<p>This is the @header parallel route in a catch-all segment</p>
</div>
)
}
export default function CatchAllLayout({
children,
header,
footer,
}: {
children: React.ReactNode
header: React.ReactNode
footer: React.ReactNode
}) {
return (
<div className="catch-all-container">
<div className="header">{header}</div>
<div className="main">{children}</div>
<div className="footer">{footer}</div>
</div>
)
}
export default async function CatchAllPage({
params,
}: {
params: Promise<{ slug: string[] }>
}) {
const { slug } = await params
return (
<div>
<h2>Catch-All Leaf Segment Page</h2>
<p>This is a catch-all route with parallel routes but NO child routes.</p>
<p className="slug-info">Current path: /{slug.join('/')}</p>
<p>
No default.tsx files are required for @header or @footer because there
are no child routes to navigate to.
</p>
</div>
)
}
export async function generateStaticParams() {
return [{ slug: ['a', 'b', 'c'] }]
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function HeaderSlot() {
return (
<div>
<h3>Header Slot</h3>
<p>This is the @header parallel route</p>
</div>
)
}
export default function MetricsSlot() {
return (
<div>
<h3>Metrics Slot</h3>
<p>This is the @metrics parallel route</p>
</div>
)
}
export default function SidebarSlot() {
return (
<div>
<h3>Sidebar Slot</h3>
<p>This is the @sidebar parallel route</p>
</div>
)
}
export default function LeafLayout({
children,
header,
sidebar,
metrics,
}: {
children: React.ReactNode
header: React.ReactNode
sidebar: React.ReactNode
metrics: React.ReactNode
}) {
return (
<div>
<div className="header">{header}</div>
<div className="container">
<div className="sidebar">{sidebar}</div>
<div className="main">
{children}
<div className="metrics">{metrics}</div>
</div>
</div>
</div>
)
}
export default function LeafPage() {
return (
<div>
<h2>Leaf Segment Page</h2>
<p>This is a leaf segment with parallel routes but NO child routes.</p>
<p>
No default.tsx files are required for @header, @sidebar, or @metrics
because there are no child routes to navigate to.
</p>
</div>
)
}
export default function AnalyticsSlot() {
return (
<div>
<h4>Analytics Slot</h4>
<p>This is the @analytics parallel route within route groups</p>
</div>
)
}
export default function ReportsSlot() {
return (
<div>
<h4>Reports Slot</h4>
<p>This is the @reports parallel route within route groups</p>
</div>
)
}
export default function GroupedLeafLayout({
children,
analytics,
reports,
}: {
children: React.ReactNode
analytics: React.ReactNode
reports: React.ReactNode
}) {
return (
<div>
<h2>Leaf with Route Groups</h2>
<div className="grouped-container">
<div className="analytics">{analytics}</div>
<div className="main">{children}</div>
<div className="reports">{reports}</div>
</div>
</div>
)
}
export default function GroupedLeafPage() {
return (
<div>
<h3>Grouped Leaf Segment Page</h3>
<p>
This demonstrates a leaf segment with route groups (dashboard) and
(sections).
</p>
<p>
Even though the path includes route groups, the logic correctly
identifies this as a leaf segment because route groups don't contribute
to routing.
</p>
<p>No default.tsx required for @analytics or @reports!</p>
</div>
)
}
export default function NoChildrenOtherPage() {
return <div>No Children Other Page</div>
}
export default function NoChildrenDefault() {
return <div>No Children Default</div>
}
export default function NoChildrenLayout({
children,
slot,
}: {
children: React.ReactNode
slot: React.ReactNode
}) {
return (
<>
<div id="slot">{slot}</div>
<div id="children">{children}</div>
</>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Parallel Routes Leaf Segments Test</h1>
<nav>
<ul>
<li>
<Link href="/leaf-segment">Leaf Segment (No Default Required)</Link>
</li>
<li>
<Link href="/leaf-with-groups">
Leaf with Route Groups (No Default Required)
</Link>
</li>
</ul>
</nav>
</div>
)
}
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import { assertHasRedbox, retry } from 'next-test-utils'
describe('parallel-routes-leaf-segments-build-error', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'build-error'),
skipStart: true,
skipDeployment: true,
})
if (skipped) {
it.skip('skip test', () => {})
return
}
if (isNextDev) {
beforeAll(() => next.start())
} else {
beforeAll(async () => {
try {
await next.build()
} catch {
// Expect build error
}
})
}
describe('Non-leaf segment with child routes', () => {
it('should throw MissingDefaultParallelRouteError for @header slot', async () => {
if (isNextDev) {
const browser = await next.browser('/with-children/child')
await assertHasRedbox(browser)
await retry(async () => {
const logs = await browser.log()
expect(logs).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: expect.stringContaining(
'/with-children/@header/default.js'
),
}),
])
)
})
} else {
await retry(() => {
expect(next.cliOutput).toContain('/with-children/@header/default.js')
})
}
})
})
describe('Non-leaf segment with route groups and child routes', () => {
it('should throw MissingDefaultParallelRouteError for parallel slots', async () => {
if (isNextDev) {
const browser = await next.browser('/with-groups-and-children/nested')
await assertHasRedbox(browser)
await retry(async () => {
const logs = await browser.log()
expect(logs).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: expect.stringContaining(
'/with-groups-and-children/(dashboard)/(overview)/@metrics/default.js'
),
}),
])
)
})
} else {
await retry(() => {
expect(next.cliOutput).toContain(
'/with-groups-and-children/(dashboard)/(overview)/@metrics/default.js'
)
})
}
})
})
})
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
describe('parallel-routes-leaf-segments-no-build-error', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'no-build-error'),
})
it('should build successfully without default.tsx for leaf segments', async () => {
// This test verifies that the build does not throw
// MissingDefaultParallelRouteError for leaf segments
expect(next.cliOutput).not.toContain('MissingDefaultParallelRouteError')
})
afterAll(() => {
if (next.cliOutput.includes('MissingDefaultParallelRouteError')) {
throw new Error('MissingDefaultParallelRouteError was thrown')
}
})
describe('leaf segment without child routes', () => {
it('should render the leaf segment page with all parallel slots', async () => {
const $ = await next.render$('/leaf-segment')
// Verify main page content
expect($('h2').text()).toBe('Leaf Segment Page')
expect($('.main p').first().text()).toContain(
'This is a leaf segment with parallel routes but NO child routes'
)
// Verify all parallel slots render
expect($('.header h3').text()).toBe('Header Slot')
expect($('.sidebar h3').text()).toBe('Sidebar Slot')
expect($('.metrics h3').text()).toBe('Metrics Slot')
})
})
describe('leaf segment with route groups', () => {
it('should render leaf segment with route groups and parallel slots', async () => {
const $ = await next.render$('/leaf-with-groups')
// Verify main page content
expect($('h3').first().text()).toBe('Grouped Leaf Segment Page')
// Verify route groups are handled correctly
expect($('p').first().text()).toContain('route groups')
// Verify parallel slots render
expect($('.analytics h4').text()).toBe('Analytics Slot')
expect($('.reports h4').text()).toBe('Reports Slot')
})
})
describe('leaf segment with catch-all parameter', () => {
it('should render catch-all segment with multiple path segments', async () => {
const $ = await next.render$('/catch-all-with-parallel/a/b/c')
// Verify main page content
expect($('h2').text()).toBe('Catch-All Leaf Segment Page')
// Verify the slug captures all segments
expect($('.slug-info').text()).toBe('Current path: /a/b/c')
// Verify parallel slots still render correctly
expect($('.header h3').text()).toBe('Catch-All Header Slot')
expect($('.footer h3').text()).toBe('Catch-All Footer Slot')
})
})
describe('no children slot', () => {
it('should render the no children slot', async () => {
const $ = await next.render$('/no-children/other')
expect($('#slot').text()).toBe('No Children Other Page')
expect($('#children').text()).toBe('No Children Default')
})
})
})
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