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

fix: Don't fall through to catch-all when static child subtree doesn't match (#90957)

When matching a URL against the known route trie, if a URL part matches
a static child but the remaining parts don't resolve within that child's
subtree, the algorithm incorrectly falls back to a dynamic catch-all
sibling at the same level. This causes the catch-all to consume the
already-matched static part plus the remaining parts, producing a
synthetic entry for the wrong route.

For example, given routes `/dashboard/settings/profile` and
`/dashboard/[...catchall]`, navigating to `/dashboard/settings/profile`
could incorrectly match the catch-all with params `["settings",
"profile"]` instead of the intended static route.

The fix treats the static child match as authoritative: if a real
(non-placeholder) static child exists but its subtree can't resolve the
remaining URL parts, bail out to server resolution rather than trying
the dynamic sibling. This is safe because it just means an extra network
request for routes whose subtree hasn't been fully discovered.
parent 2c2dd5fe
...@@ -644,8 +644,12 @@ function matchKnownRoutePart( ...@@ -644,8 +644,12 @@ function matchKnownRoutePart(
if (match !== null) { if (match !== null) {
return match return match
} }
// Static child exists but didn't match (e.g., wrong depth). // Static child is a real node (not a placeholder) but its subtree
// Fall through to try dynamic. // didn't match the remaining URL parts. This means the route exists
// in the static subtree but hasn't been fully discovered yet. Do not
// fall through to try the dynamic child — the static match is
// authoritative. Bail out to server resolution.
return null
} }
} }
......
export default function Loading() {
return <div id="loading-message">Loading catchall...</div>
}
import { connection } from 'next/server'
export default async function CatchAllPage({
params,
}: {
params: Promise<{ catchall: string[] }>
}) {
const { catchall } = await params
await connection()
return (
<div id="catchall-page">
<h1 id="catchall-title">Catch All: {catchall.join('/')}</h1>
</div>
)
}
export default function Loading() {
return <div id="loading-message">Loading settings...</div>
}
import { connection } from 'next/server'
import Link from 'next/link'
export default async function SettingsPage() {
await connection()
return (
<div id="settings-page">
<h1 id="settings-title">Settings</h1>
<Link href="/" id="back-link">
Back to home
</Link>
</div>
)
}
export default function Loading() {
return <div id="loading-message">Loading profile...</div>
}
import { connection } from 'next/server'
import Link from 'next/link'
export default async function ProfilePage() {
await connection()
return (
<div id="profile-page">
<h1 id="profile-title">Profile Settings</h1>
<Link href="/" id="back-link">
Back to home
</Link>
</div>
)
}
import { ReactNode, Suspense } from 'react' import { ReactNode, Suspense } from 'react'
import { ParamsHistory } from '../components/params-history' import { RenderedRouteHistory } from '../components/rendered-route-history'
export default function Root({ children }: { children: ReactNode }) { export default function Root({ children }: { children: ReactNode }) {
return ( return (
<html> <html>
<body> <body>
<Suspense fallback={null}> <Suspense fallback={null}>
<ParamsHistory /> <RenderedRouteHistory />
</Suspense> </Suspense>
{children} {children}
</body> </body>
......
...@@ -80,6 +80,29 @@ export default function Home() { ...@@ -80,6 +80,29 @@ export default function Home() {
</li> </li>
</ul> </ul>
<h2>Static Route with Catch-All Sibling</h2>
<p>
Tests that navigating to a sub-route of a static path does not
incorrectly match the catch-all sibling at the parent level.
</p>
<ul>
<li>
<LinkAccordion href="/dashboard/settings">
Dashboard Settings (static route, learns pattern)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dashboard/settings/profile" prefetch={false}>
Profile Settings (sub-route of static, prefetch disabled)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dashboard/anything/here">
Dashboard Catch-All (learns catch-all pattern)
</LinkAccordion>
</li>
</ul>
<h2>Static Sibling Detection</h2> <h2>Static Sibling Detection</h2>
<ul> <ul>
<li> <li>
......
'use client' 'use client'
import { useState } from 'react' import { useState } from 'react'
import { useParams } from 'next/navigation' import { useParams, usePathname, useSearchParams } from 'next/navigation'
type RenderedRouteEntry = {
url: string
params: Record<string, string | string[] | undefined>
}
/** /**
* Accumulates all param values rendered throughout the app's lifetime. * Accumulates every [url, params] pair rendered throughout the app's lifetime.
* Uses the setState-in-render pattern to capture changes synchronously, * Uses the setState-in-render pattern to capture changes synchronously,
* before React commits. This catches any intermediate/wrong params that * before React commits. This catches any intermediate/wrong route state that
* might flash briefly due to incorrect route prediction. * might flash briefly due to incorrect route prediction.
*/ */
export function ParamsHistory() { export function RenderedRouteHistory() {
const params = useParams() const params = useParams()
const paramsJson = JSON.stringify(params) const pathname = usePathname()
const searchParams = useSearchParams()
const search = searchParams.toString()
const url = search ? `${pathname}?${search}` : pathname
const entry: RenderedRouteEntry = { url, params }
const entryJson = JSON.stringify(entry)
const [history, setHistory] = useState<string[]>([paramsJson]) const [history, setHistory] = useState<string[]>([entryJson])
const [prevParams, setPrevParams] = useState(paramsJson) const [prevEntry, setPrevEntry] = useState(entryJson)
// setState-in-render pattern: update state synchronously during render // setState-in-render pattern: update state synchronously during render
// if the params have changed. This captures intermediate states. // if the route state has changed. This captures intermediate states.
if (paramsJson !== prevParams) { if (entryJson !== prevEntry) {
setPrevParams(paramsJson) setPrevEntry(entryJson)
setHistory((prev) => [...prev, paramsJson]) setHistory((prev) => [...prev, entryJson])
} }
return ( return (
<div <div
id="params-history" id="rendered-route-history"
data-history={JSON.stringify(history)} data-history={JSON.stringify(history)}
style={{ style={{
padding: '8px', padding: '8px',
...@@ -37,9 +48,9 @@ export function ParamsHistory() { ...@@ -37,9 +48,9 @@ export function ParamsHistory() {
}} }}
> >
<div style={{ fontWeight: 'bold', marginBottom: '4px' }}> <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
Params History (debug) Rendered Route History (debug)
</div> </div>
<div>Current: {paramsJson}</div> <div>Current: {entryJson}</div>
<div style={{ marginTop: '4px' }}> <div style={{ marginTop: '4px' }}>
History:{' '} History:{' '}
{history.map((h, i) => ( {history.map((h, i) => (
......
...@@ -19,6 +19,19 @@ ...@@ -19,6 +19,19 @@
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import type { Playwright } from 'next-webdriver'
/**
* Reads the rendered route history from the page and returns an array of
* {url, params} objects representing every route state the app rendered.
*/
async function getRenderedRouteHistory(
browser: Playwright
): Promise<Array<{ url: string; params: Record<string, unknown> }>> {
const el = await browser.elementById('rendered-route-history')
const attr = await el.getAttribute('data-history')
return JSON.parse(attr).map((h: string) => JSON.parse(h))
}
describe('optimistic-routing', () => { describe('optimistic-routing', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
...@@ -335,7 +348,7 @@ describe('optimistic-routing', () => { ...@@ -335,7 +348,7 @@ describe('optimistic-routing', () => {
// Step 2: Navigate back to home using browser back button // Step 2: Navigate back to home using browser back button
await browser.back() await browser.back()
await browser.elementById('params-history') await browser.elementById('rendered-route-history')
// Step 3: Navigate to /rewritten/second. // Step 3: Navigate to /rewritten/second.
// This link has prefetch={false}. Even though we've "learned" the route // This link has prefetch={false}. Even though we've "learned" the route
...@@ -356,25 +369,17 @@ describe('optimistic-routing', () => { ...@@ -356,25 +369,17 @@ describe('optimistic-routing', () => {
// Wait for navigation to complete // Wait for navigation to complete
await browser.elementById('actual-page') await browser.elementById('actual-page')
// Verify using params history that no wrong params were rendered. // Verify using rendered route history that no wrong params were rendered.
// The history accumulator captures every params change during render. // If route prediction incorrectly used a cached pattern, we'd see "first"
// If route prediction incorrectly used a pattern, we'd see "first"
// briefly flash before "second". // briefly flash before "second".
const historyEl = await browser.elementById('params-history') expect(await getRenderedRouteHistory(browser)).toEqual([
const historyAttr = await historyEl.getAttribute('data-history') { url: '/', params: {} },
const history: string[] = JSON.parse(historyAttr) { url: '/rewritten/first', params: { slug: 'first' } },
// Back to home
// The history should only contain params from actual navigations, { url: '/', params: {} },
// not any intermediate wrong values from incorrect prediction. // Should go directly to "second" with no intermediate wrong params
// Expected: [{}, {slug: "first"}, {}, {slug: "second"}] { url: '/rewritten/second', params: { slug: 'second' } },
// The {} entries are from the home page. ])
const slugHistory = history
.map((h) => JSON.parse(h))
.filter((p) => p.slug !== undefined)
.map((p) => p.slug)
// We should see exactly [first, second] - no duplicates or wrong values
expect(slugHistory).toEqual(['first', 'second'])
}) })
it('rewrite detection (search params): does not use cached pattern when search params cause different rewrite', async () => { it('rewrite detection (search params): does not use cached pattern when search params cause different rewrite', async () => {
...@@ -405,7 +410,7 @@ describe('optimistic-routing', () => { ...@@ -405,7 +410,7 @@ describe('optimistic-routing', () => {
// Step 2: Go back to home // Step 2: Go back to home
await browser.back() await browser.back()
await browser.elementById('params-history') await browser.elementById('rendered-route-history')
// Step 3: Navigate to /search-rewrite?v=beta. // Step 3: Navigate to /search-rewrite?v=beta.
// This link has prefetch={false} - if the route was incorrectly cached as // This link has prefetch={false} - if the route was incorrectly cached as
...@@ -430,4 +435,73 @@ describe('optimistic-routing', () => { ...@@ -430,4 +435,73 @@ describe('optimistic-routing', () => {
const contentBeta = await browser.elementById('rewrite-content') const contentBeta = await browser.elementById('rewrite-content')
expect(await contentBeta.getAttribute('data-content')).toBe('beta') expect(await contentBeta.getAttribute('data-content')).toBe('beta')
}) })
it('static route with catch-all sibling: does not match sub-route against catch-all', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
// Step 1: Prefetch /dashboard/anything/here to learn the catch-all pattern
// at the "dashboard" trie level.
const revealCatchAll = await browser.elementByCss(
'input[data-link-accordion="/dashboard/anything/here"]'
)
await act(
async () => {
await revealCatchAll.click()
},
{
includes: 'Loading',
}
)
// Step 2: Prefetch /dashboard/settings to populate the static child
// "settings" in the trie at the "dashboard" level. At this point the
// trie knows about the settings page but not its children (like profile).
const revealSettings = await browser.elementByCss(
'input[data-link-accordion="/dashboard/settings"]'
)
await act(
async () => {
await revealSettings.click()
},
{
includes: 'Loading',
}
)
// Step 3: Navigate to /dashboard/settings/profile (prefetch={false}).
// The static child "settings" matches at the dashboard level, but its
// subtree doesn't yet know about "profile". The matcher should treat the
// static match as authoritative and bail out to server resolution rather
// than falling through to the catch-all sibling.
await act(async () => {
const revealProfile = await browser.elementByCss(
'input[data-link-accordion="/dashboard/settings/profile"]'
)
await revealProfile.click()
}, 'no-requests')
const linkProfile = await browser.elementByCss(
'a[href="/dashboard/settings/profile"]'
)
await act(async () => {
await linkProfile.click()
})
// Verify the profile page renders correctly after server resolution.
const profileTitle = await browser.elementById('profile-title')
expect(await profileTitle.text()).toBe('Profile Settings')
// Verify the route history doesn't contain any catch-all param entries.
// If the matcher incorrectly fell through to the catch-all, we'd see
// an entry with catchall=["settings","profile"].
expect(await getRenderedRouteHistory(browser)).toEqual([
{ url: '/', params: {} },
{ url: '/dashboard/settings/profile', params: {} },
])
})
}) })
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