Unverified Commit a87a0721 authored by Joshua Hannaford's avatar Joshua Hannaford Committed by GitHub

fix(turbopack) Adjust the way catchall routes are handled when a more specific…

fix(turbopack) Adjust the way catchall routes are handled when a more specific parallel route exists (#81634)

## Improve App Router Route Prioritization

### What?
Fixed a logic bug where we were failing to correctly identify routes as
catchall routes due to treating parallel routes as a completed route
path. This shouldn't happen because parallel routes do not affect the
routing structure.

### How?

- Modified the route selection logic to more clearly prioritize specific
routes over catch-all routes
- Make sure we only count true leaf nodes when determining when to use
the catch-all. Parallel is not a leaf node
- Added a test case to ensure middleware rewrites and redirects work
correctly with both parallel and non-parallel catch-all routes.

Fixes #PACK-4490
parent 65e0b7b7
...@@ -257,17 +257,22 @@ impl AppPage { ...@@ -257,17 +257,22 @@ impl AppPage {
matches!(self.0.last(), Some(PageSegment::PageType(..))) matches!(self.0.last(), Some(PageSegment::PageType(..)))
} }
pub fn is_catchall(&self) -> bool { /// The `PageType` is the last segment for completed pages. We need to find
let segment = if self.is_complete() { /// the last segment that is not a `PageType`, `Group`, or `Parallel`
// The `PageType` is the last segment for completed pages. /// segment, because these do not inform the routing structure.
self.0.iter().nth_back(1) pub fn get_last_routing_segment(&self) -> Option<&PageSegment> {
} else { self.0.iter().rev().find(|segment| {
self.0.last() !matches!(
}; segment,
PageSegment::PageType(_) | PageSegment::Group(_) | PageSegment::Parallel(_)
)
})
}
pub fn is_catchall(&self) -> bool {
matches!( matches!(
segment, self.get_last_routing_segment(),
Some(PageSegment::CatchAll(..) | PageSegment::OptionalCatchAll(..)) Some(PageSegment::CatchAll(_) | PageSegment::OptionalCatchAll(_))
) )
} }
......
import React from 'react'
export default function Page({ params }) {
return (
<h1 id="catch-all">anotherRoute catch-all: {params.slug?.join('/')}</h1>
)
}
import React from 'react'
export default function Page() {
return <h1 id="specific-page">anotherRoute whoops</h1>
}
import React from 'react'
export default function Page() {
return <h1 id="parallel-page">parallel page</h1>
}
import React from 'react'
export default function Layout({ children, parallel }) {
return (
<>
{children}
{parallel}
</>
)
}
import React from 'react'
export default function Page({ params }) {
return <h1 id="catch-all">payment catch-all: {params.slug?.join('/')}</h1>
}
import React from 'react'
export default function Page() {
return <h1 id="specific-page">payment whoops</h1>
}
import React from 'react'
export default function RootLayout({ children }) {
return (
<html>
<head>
<title>Test App</title>
</head>
<body>{children}</body>
</html>
)
}
import React from 'react'
export default function Page() {
return <h1>Root Page</h1>
}
import { nextTestSetup } from 'e2e-utils'
describe('app-dir - middleware rewrite with catch-all and parallel routes', () => {
const { next } = nextTestSetup({
files: __dirname,
})
describe('payment route', () => {
it('should rewrite to the specific page instead of the catch-all with parallel route', async () => {
const browser = await next.browser('/payment/test')
const text = await browser.elementByCss('#specific-page').text()
expect(text).toBe('payment whoops')
expect(await browser.url()).toBe(next.url + '/payment/test')
})
it('should redirect to the specific page instead of the catch-all with parallel route', async () => {
const browser = await next.browser('/payment/test?redirect=true')
const text = await browser.elementByCss('#specific-page').text()
expect(text).toBe('payment whoops')
expect(await browser.url()).toBe(next.url + '/payment/whoops')
})
})
describe('anotherRoute', () => {
it('should rewrite to the specific page instead of the catch-all without parallel route', async () => {
const browser = await next.browser('/anotherRoute/test')
const text = await browser.elementByCss('#specific-page').text()
expect(text).toBe('anotherRoute whoops')
expect(await browser.url()).toBe(next.url + '/anotherRoute/test')
})
it('should redirect to the specific page instead of the catch-all without parallel route', async () => {
const browser = await next.browser('/anotherRoute/test?redirect=true')
const text = await browser.elementByCss('#specific-page').text()
expect(text).toBe('anotherRoute whoops')
expect(await browser.url()).toBe(next.url + '/anotherRoute/whoops')
})
})
})
import { NextResponse } from 'next/server'
export async function middleware(request) {
if (
request.nextUrl.pathname.includes('payment') &&
!request.nextUrl.pathname.includes('whoops')
) {
if (request.nextUrl.searchParams.has('redirect')) {
return NextResponse.redirect(new URL('/payment/whoops', request.url))
}
return NextResponse.rewrite(new URL('/payment/whoops', request.url))
}
if (
request.nextUrl.pathname.includes('anotherRoute') &&
!request.nextUrl.pathname.includes('whoops')
) {
if (request.nextUrl.searchParams.has('redirect')) {
return NextResponse.redirect(new URL('/anotherRoute/whoops', request.url))
}
return NextResponse.rewrite(new URL('/anotherRoute/whoops', request.url))
}
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
}
...@@ -3316,6 +3316,18 @@ ...@@ -3316,6 +3316,18 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/e2e/app-dir/middleware-rewrite-catchall-priority-with-parallel-route/middleware-rewrite-catchall-priority-with-parallel-route.test.js": {
"passed": [
"app-dir - middleware rewrite with catch-all and parallel routes should rewrite to the specific page instead of the catch-all with parallel route",
"app-dir - middleware rewrite with catch-all and parallel routes should redirect to the specific page instead of the catch-all with parallel route",
"app-dir - middleware rewrite with catch-all and parallel routes should rewrite to the specific page instead of the catch-all without parallel route",
"app-dir - middleware rewrite with catch-all and parallel routes should redirect to the specific page instead of the catch-all without parallel route"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/e2e/app-dir/middleware-sitemap/matcher-exclude-sitemap/index.test.ts": { "test/e2e/app-dir/middleware-sitemap/matcher-exclude-sitemap/index.test.ts": {
"passed": [ "passed": [
"middleware-sitemap should not be affected by middleware if sitemap.xml is excluded from the matcher" "middleware-sitemap should not be affected by middleware if sitemap.xml is excluded from the matcher"
...@@ -7165,6 +7165,18 @@ ...@@ -7165,6 +7165,18 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/e2e/app-dir/middleware-rewrite-catchall-priority-with-parallel-route/middleware-rewrite-catchall-priority-with-parallel-route.test.js": {
"passed": [
"app-dir - middleware rewrite with catch-all and parallel routes should rewrite to the specific page instead of the catch-all with parallel route",
"app-dir - middleware rewrite with catch-all and parallel routes should redirect to the specific page instead of the catch-all with parallel route",
"app-dir - middleware rewrite with catch-all and parallel routes should rewrite to the specific page instead of the catch-all without parallel route",
"app-dir - middleware rewrite with catch-all and parallel routes should redirect to the specific page instead of the catch-all without parallel route"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/e2e/app-dir/middleware-sitemap/matcher-exclude-sitemap/index.test.ts": { "test/e2e/app-dir/middleware-sitemap/matcher-exclude-sitemap/index.test.ts": {
"passed": [ "passed": [
"middleware-sitemap should not be affected by middleware if sitemap.xml is excluded from the matcher" "middleware-sitemap should not be affected by middleware if sitemap.xml is excluded from the matcher"
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