Unverified Commit 5f480670 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[next-server] fix params duplicate in query after rewrite (#77939)

parent e961a3b9
...@@ -1196,21 +1196,26 @@ export default abstract class Server< ...@@ -1196,21 +1196,26 @@ export default abstract class Server<
parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}` parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}`
} }
// Store a copy of `parsedUrl.query` before calling handleRewrites.
// Since `handleRewrites` might add new queries to `parsedUrl.query`.
const originQueryParams = { ...parsedUrl.query }
const pathnameBeforeRewrite = parsedUrl.pathname const pathnameBeforeRewrite = parsedUrl.pathname
const rewriteParamKeys = Object.keys( const rewriteParamKeys = Object.keys(
utils.handleRewrites(req, parsedUrl) utils.handleRewrites(req, parsedUrl)
) )
const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname
if (didRewrite && parsedUrl.pathname) {
addRequestMeta(req, 'rewroteURL', parsedUrl.pathname)
}
// Create a copy of the query params to avoid mutating the original // Create a copy of the query params to avoid mutating the original
// object. This prevents any overlapping query params that have the // object. This prevents any overlapping query params that have the
// same normalized key from causing issues. // same normalized key from causing issues.
const queryParams = { ...parsedUrl.query } const queryParams = { ...parsedUrl.query }
const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname
if (didRewrite && parsedUrl.pathname) {
addRequestMeta(req, 'rewroteURL', parsedUrl.pathname)
}
const routeParamKeys = new Set<string>()
for (const [key, value] of Object.entries(parsedUrl.query)) { for (const [key, value] of Object.entries(parsedUrl.query)) {
const normalizedKey = normalizeNextQueryParam(key) const normalizedKey = normalizeNextQueryParam(key)
if (!normalizedKey) continue if (!normalizedKey) continue
...@@ -1218,6 +1223,7 @@ export default abstract class Server< ...@@ -1218,6 +1223,7 @@ export default abstract class Server<
// Remove the prefixed key from the query params because we want // Remove the prefixed key from the query params because we want
// to consume it for the dynamic route matcher. // to consume it for the dynamic route matcher.
delete parsedUrl.query[key] delete parsedUrl.query[key]
routeParamKeys.add(normalizedKey)
if (typeof value === 'undefined') continue if (typeof value === 'undefined') continue
...@@ -1371,6 +1377,14 @@ export default abstract class Server< ...@@ -1371,6 +1377,14 @@ export default abstract class Server<
...Object.keys(utils.defaultRouteRegex?.groups || {}), ...Object.keys(utils.defaultRouteRegex?.groups || {}),
]) ])
} }
// Remove the route `params` keys from `parsedUrl.query` if they are
// not in the original query params.
// If it's used in both route `params` and query `searchParams`, it should be kept.
for (const key of routeParamKeys) {
if (!(key in originQueryParams)) {
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)
......
export default async function Page({
params,
searchParams,
}: {
params: Promise<{ domain: string; section: string[] }>
searchParams: Promise<{ [key: string]: string | string[] }>
}) {
const resolvedParams = await params
const resolvedSearchParams = await searchParams
return (
<>
<div>
<h2>Params:</h2>
<pre id="params-value">{JSON.stringify(resolvedParams, null, 2)}</pre>
</div>
<div>
<h2>Search Params:</h2>
<pre id="search-params-value">
{JSON.stringify(resolvedSearchParams, null, 2)}
</pre>
</div>
</>
)
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
async rewrites() {
return [
{
source: '/:path((?!sitemap.xml$).*)',
has: [
{
type: 'host',
value: '(?<subdomain>[^.]+)\\.(?<domain>.*)',
},
],
destination: '/:subdomain/:path*',
},
]
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('rewrite-with-search-params', () => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('should not contain params in search params after rewrite', async () => {
const $ = await next.render$(
'/galleries/123',
{
param: 'value',
},
{
headers: isNextDeploy
? undefined
: {
host: 'vercel-test.vercel.app',
},
}
)
const searchParams = JSON.parse($('#search-params-value').text())
const params = JSON.parse($('#params-value').text())
expect(searchParams).toEqual({
param: 'value',
})
expect(params).toEqual({
domain: expect.stringMatching(/[\w-]+/),
section: ['galleries', '123'],
})
})
})
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