Unverified Commit 3220f1f0 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: use the match result after matching using the matched path header (#77994)

When rendering the page on Vercel, we send the `x-matched-path` header
to indicate which route should be rendered. Sometimes, like in the case
of a middleware rewrite, we will rewrite a path to a statically
generated one. This results in a `x-matched-path` header being equal to
the generated page and not the route with the dynamic path params in it.

This ensures that if we get such a path that we match against that we do
save the result of the path matching as they are valid parameters.

This also fixes a related bug associated with route denormalization
which must occur before the routes i18n is parsed.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

Fixes #77789

---------
Co-authored-by: 's avatarJiwon Choi <devjiwonchoi@gmail.com>
parent c94753cf
......@@ -1131,6 +1131,8 @@ export default abstract class Server<
matchedPath = this.normalize(matchedPath)
const normalizedUrlPath = this.stripNextDataPath(urlPathname)
matchedPath = denormalizePagePath(matchedPath)
// Perform locale detection and normalization.
const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, {
defaultLocale,
......@@ -1151,11 +1153,15 @@ export default abstract class Server<
}
}
// TODO: check if this is needed any more?
matchedPath = denormalizePagePath(matchedPath)
let srcPathname = matchedPath
let pageIsDynamic = isDynamicRoute(srcPathname)
let paramsResult: {
params: ParsedUrlQuery | false
hasValidParams: boolean
} = {
params: false,
hasValidParams: false,
}
if (!pageIsDynamic) {
const match = await this.matchers.match(srcPathname, {
......@@ -1165,8 +1171,15 @@ export default abstract class Server<
// Update the source pathname to the matched page's pathname.
if (match) {
srcPathname = match.definition.pathname
// The page is dynamic if the params are defined.
pageIsDynamic = typeof match.params !== 'undefined'
// The page is dynamic if the params are defined. We know at this
// stage that the matched path is not a static page if the params
// were parsed from the matched path header.
if (typeof match.params !== 'undefined') {
pageIsDynamic = true
paramsResult.params = match.params
paramsResult.hasValidParams = true
}
}
}
......@@ -1236,10 +1249,14 @@ export default abstract class Server<
if (pageIsDynamic) {
let params: ParsedUrlQuery | false = {}
let paramsResult = utils.normalizeDynamicRouteParams(
queryParams,
false
)
// If we don't already have valid params, try to parse them from
// the query params.
if (!paramsResult.hasValidParams) {
paramsResult = utils.normalizeDynamicRouteParams(
queryParams,
false
)
}
// for prerendered ISR paths we attempt parsing the route
// params from the URL directly as route-matches may not
......
import { type Params, expectedParams } from '../../../expected'
export default async function CatchAll({
params,
}: {
params: Promise<Params>
}) {
const received = await params
return <p>{JSON.stringify(received)}</p>
}
export async function generateStaticParams(): Promise<Params[]> {
return [expectedParams]
}
export const dynamic = 'force-dynamic'
import Link from 'next/link'
export default function Home() {
return <Link href="/1/2">Go to /1/2</Link>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export type Params = {
locale: string
rest: string[]
}
export const expectedParams: Params = {
locale: 'en',
rest: ['1', '2'],
}
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
return NextResponse.rewrite(
new URL('/en' + request.nextUrl.pathname, 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).*)',
],
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { expectedParams as expected } from './expected'
describe('ppr-middleware-rewrite-force-dynamic-generate-static-params', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const expectedParams = JSON.stringify(expected)
it('should have correct dynamic params', async () => {
// should be rewritten with /en
const browser = await next.browser('/')
expect(await browser.elementByCss('a').text()).toBe('Go to /1/2')
// navigate to /1/2
await browser.elementByCss('a').click()
// should be rewritten with /en/1/2 with correct params
expect(await browser.elementByCss('p').text()).toBe(expectedParams)
// reloading the page should have the same params
await browser.refresh()
expect(await browser.elementByCss('p').text()).toBe(expectedParams)
})
})
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