Unverified Commit 2491b7ea authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: overlapping query and param names should not conflict (#76177)

When the query parameters overlap with the params, previously we mutated
the value. This ensures we only mutate a copy which is safe to mutate
and preserves the initial search parameters along with the route
parameters.

<!-- 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 #

-->
parent 357361bc
...@@ -1198,25 +1198,30 @@ export default abstract class Server< ...@@ -1198,25 +1198,30 @@ export default abstract class Server<
} }
const pathnameBeforeRewrite = parsedUrl.pathname const pathnameBeforeRewrite = parsedUrl.pathname
const rewriteParams = utils.handleRewrites(req, parsedUrl) const rewriteParamKeys = Object.keys(
const rewriteParamKeys = Object.keys(rewriteParams) utils.handleRewrites(req, parsedUrl)
)
const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname
if (didRewrite && parsedUrl.pathname) { if (didRewrite && parsedUrl.pathname) {
addRequestMeta(req, 'rewroteURL', parsedUrl.pathname) addRequestMeta(req, 'rewroteURL', parsedUrl.pathname)
} }
// Normalize all the query params to remove the prefixes. // Create a copy of the query params to avoid mutating the original
const routeParamKeys = new Set<string>() // object. This prevents any overlapping query params that have the
for (const [key, value] of Object.entries(parsedUrl.query)) { // same normalized key from causing issues.
if (typeof value === 'undefined') continue const queryParams = { ...parsedUrl.query }
for (const [key, value] of Object.entries(parsedUrl.query)) {
const normalizedKey = normalizeNextQueryParam(key) const normalizedKey = normalizeNextQueryParam(key)
if (normalizedKey) { if (!normalizedKey) continue
parsedUrl.query[normalizedKey] = value
routeParamKeys.add(normalizedKey) // Remove the prefixed key from the query params because we want
delete parsedUrl.query[key] // to consume it for the dynamic route matcher.
} delete parsedUrl.query[key]
if (typeof value === 'undefined') continue
queryParams[normalizedKey] = value
} }
// interpolate dynamic params and normalize URL if needed // interpolate dynamic params and normalize URL if needed
...@@ -1224,7 +1229,7 @@ export default abstract class Server< ...@@ -1224,7 +1229,7 @@ export default abstract class Server<
let params: ParsedUrlQuery | false = {} let params: ParsedUrlQuery | false = {}
let paramsResult = utils.normalizeDynamicRouteParams( let paramsResult = utils.normalizeDynamicRouteParams(
parsedUrl.query, queryParams,
false false
) )
...@@ -1303,7 +1308,7 @@ export default abstract class Server< ...@@ -1303,7 +1308,7 @@ export default abstract class Server<
// from the route matches but ignore missing optional params. // from the route matches but ignore missing optional params.
if (!paramsResult.hasValidParams) { if (!paramsResult.hasValidParams) {
paramsResult = utils.normalizeDynamicRouteParams( paramsResult = utils.normalizeDynamicRouteParams(
parsedUrl.query, queryParams,
true true
) )
...@@ -1364,9 +1369,6 @@ export default abstract class Server< ...@@ -1364,9 +1369,6 @@ export default abstract class Server<
...Object.keys(utils.defaultRouteRegex?.groups || {}), ...Object.keys(utils.defaultRouteRegex?.groups || {}),
]) ])
} }
for (const key of routeParamKeys) {
delete parsedUrl.query[key]
}
parsedUrl.pathname = matchedPath parsedUrl.pathname = matchedPath
url.pathname = parsedUrl.pathname url.pathname = parsedUrl.pathname
finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl) finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)
......
...@@ -564,7 +564,7 @@ describe('Required Server Files', () => { ...@@ -564,7 +564,7 @@ describe('Required Server Files', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/optional-ssp', '/optional-ssp',
{ rest: '', another: 'value' }, { nxtPrest: '', another: 'value' },
{ {
headers: { headers: {
'x-matched-path': '/optional-ssp/[[...rest]]', 'x-matched-path': '/optional-ssp/[[...rest]]',
...@@ -601,7 +601,7 @@ describe('Required Server Files', () => { ...@@ -601,7 +601,7 @@ describe('Required Server Files', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/api/optional', '/api/optional',
{ rest: '', another: 'value' }, { nxtPrest: '', another: 'value' },
{ {
headers: { headers: {
'x-matched-path': '/api/optional/[[...rest]]', 'x-matched-path': '/api/optional/[[...rest]]',
......
export default function Page({ searchParams, params }) {
return (
<dl>
<dt>params.key</dt>
<dd data-params>{params.key}</dd>
<dt>searchParams.key</dt>
<dd data-searchParams>{searchParams.key}</dd>
</dl>
)
}
...@@ -304,4 +304,22 @@ describe('required server files app router', () => { ...@@ -304,4 +304,22 @@ describe('required server files app router', () => {
expect(res.headers.get('x-next-cache-tags')).toBeFalsy() expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
} }
}) })
it('should not override params with query params', async () => {
const res = await fetchViaHTTP(
appPort,
'/search/[key]',
{ key: 'searchParams', nxtPkey: 'params' },
{
headers: {
'x-matched-path': '/search/[key]',
},
}
)
const html = await res.text()
const $ = cheerio.load(html)
expect($('dd[data-params]').text()).toBe('params')
expect($('dd[data-searchParams]').text()).toBe('searchParams')
})
}) })
...@@ -1104,7 +1104,7 @@ describe('required server files', () => { ...@@ -1104,7 +1104,7 @@ describe('required server files', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/optional-ssp', '/optional-ssp',
{ rest: '', another: 'value' }, { nxtPrest: '', another: 'value' },
{ {
headers: { headers: {
'x-matched-path': '/optional-ssp/[[...rest]]', 'x-matched-path': '/optional-ssp/[[...rest]]',
...@@ -1123,7 +1123,7 @@ describe('required server files', () => { ...@@ -1123,7 +1123,7 @@ describe('required server files', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/optional-ssg', '/optional-ssg',
{ rest: '', another: 'value' }, { nxtPrest: '', another: 'value' },
{ {
headers: { headers: {
'x-matched-path': '/optional-ssg/[[...rest]]', 'x-matched-path': '/optional-ssg/[[...rest]]',
...@@ -1244,7 +1244,7 @@ describe('required server files', () => { ...@@ -1244,7 +1244,7 @@ describe('required server files', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/api/optional', '/api/optional',
{ rest: '', another: 'value' }, { nxtPrest: '', another: 'value' },
{ {
headers: { headers: {
'x-matched-path': '/api/optional/[[...rest]]', 'x-matched-path': '/api/optional/[[...rest]]',
......
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