Unverified Commit 7d7a8fc3 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Normalize serverless asPath value (#15914)

Since we now use query parameters to pass dynamic route params while routing on Vercel, this makes sure we normalize the request URL before populating the `asPath`

Fixes: https://github.com/vercel/next.js/issues/15879
parent 405e42e4
...@@ -66,12 +66,16 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -66,12 +66,16 @@ const nextServerlessLoader: loader.Loader = function () {
JSON.parse(previewProps) as __ApiPreviewProps JSON.parse(previewProps) as __ApiPreviewProps
) )
const defaultRouteRegex = pageIsDynamicRoute
? `
const defaultRouteRegex = getRouteRegex("${page}")
`
: ''
const collectDynamicRouteParams = pageIsDynamicRoute const collectDynamicRouteParams = pageIsDynamicRoute
? ` ? `
function collectDynamicRouteParams(query) { function collectDynamicRouteParams(query) {
const routeRegex = getRouteRegex("${page}") return Object.keys(defaultRouteRegex.groups)
return Object.keys(routeRegex.groups)
.reduce((prev, key) => { .reduce((prev, key) => {
let value = query[key] let value = query[key]
...@@ -80,7 +84,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -80,7 +84,7 @@ const nextServerlessLoader: loader.Loader = function () {
// non-provided optional values should be undefined so normalize // non-provided optional values should be undefined so normalize
// them to undefined // them to undefined
} }
if(routeRegex.groups[key].optional && !value) { if(defaultRouteRegex.groups[key].optional && !value) {
value = undefined value = undefined
delete query[key] delete query[key]
} }
...@@ -92,7 +96,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -92,7 +96,7 @@ const nextServerlessLoader: loader.Loader = function () {
if ( if (
value && value &&
typeof value === 'string' && typeof value === 'string' &&
routeRegex.groups[key].repeat defaultRouteRegex.groups[key].repeat
) { ) {
value = value.split('/') value = value.split('/')
} }
...@@ -211,11 +215,14 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -211,11 +215,14 @@ const nextServerlessLoader: loader.Loader = function () {
runtimeConfigSetter runtimeConfigSetter
} }
${dynamicRouteImports} ${dynamicRouteImports}
const { parse } = require('url') const { parse: parseUrl } = require('url')
const { apiResolver } = require('next/dist/next-server/server/api-utils') const { apiResolver } = require('next/dist/next-server/server/api-utils')
${rewriteImports} ${rewriteImports}
${dynamicRouteMatcher} ${dynamicRouteMatcher}
${defaultRouteRegex}
${collectDynamicRouteParams} ${collectDynamicRouteParams}
${handleRewrites} ${handleRewrites}
...@@ -227,7 +234,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -227,7 +234,7 @@ const nextServerlessLoader: loader.Loader = function () {
// We need to trust the dynamic route params from the proxy // We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values // to ensure we are using the correct values
const trustQuery = req.headers['${vercelHeader}'] const trustQuery = req.headers['${vercelHeader}']
const parsedUrl = handleRewrites(parse(req.url, true)) const parsedUrl = handleRewrites(parseUrl(req.url, true))
${handleBasePath} ${handleBasePath}
...@@ -279,7 +286,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -279,7 +286,7 @@ const nextServerlessLoader: loader.Loader = function () {
// this needs to be called first so its available for any other imports // this needs to be called first so its available for any other imports
runtimeConfigSetter runtimeConfigSetter
} }
const {parse} = require('url') const {parse: parseUrl, format: formatUrl} = require('url')
const {parse: parseQs} = require('querystring') const {parse: parseQs} = require('querystring')
const { renderToHTML } = require('next/dist/next-server/server/render'); const { renderToHTML } = require('next/dist/next-server/server/render');
const { tryGetPreviewData } = require('next/dist/next-server/server/api-utils'); const { tryGetPreviewData } = require('next/dist/next-server/server/api-utils');
...@@ -308,6 +315,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -308,6 +315,7 @@ const nextServerlessLoader: loader.Loader = function () {
export const unstable_getServerProps = ComponentInfo['unstable_getServerProp' + 's'] export const unstable_getServerProps = ComponentInfo['unstable_getServerProp' + 's']
${dynamicRouteMatcher} ${dynamicRouteMatcher}
${defaultRouteRegex}
${collectDynamicRouteParams} ${collectDynamicRouteParams}
${handleRewrites} ${handleRewrites}
...@@ -340,7 +348,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -340,7 +348,7 @@ const nextServerlessLoader: loader.Loader = function () {
// We need to trust the dynamic route params from the proxy // We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values // to ensure we are using the correct values
const trustQuery = !getStaticProps && req.headers['${vercelHeader}'] const trustQuery = !getStaticProps && req.headers['${vercelHeader}']
const parsedUrl = handleRewrites(parse(req.url, true)) const parsedUrl = handleRewrites(parseUrl(req.url, true))
${handleBasePath} ${handleBasePath}
...@@ -429,6 +437,18 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -429,6 +437,18 @@ const nextServerlessLoader: loader.Loader = function () {
// if provided from worker or params if we're parsing them here // if provided from worker or params if we're parsing them here
renderOpts.params = _params || params renderOpts.params = _params || params
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (trustQuery) {
const _parsedUrl = parseUrl(req.url, true)
delete _parsedUrl.search
for (const param of Object.keys(defaultRouteRegex.groups)) {
delete _parsedUrl.query[param]
}
req.url = formatUrl(_parsedUrl)
}
const isFallback = parsedUrl.query.__nextFallback const isFallback = parsedUrl.query.__nextFallback
const previewData = tryGetPreviewData(req, res, options.previewProps) const previewData = tryGetPreviewData(req, res, options.previewProps)
...@@ -467,7 +487,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -467,7 +487,7 @@ const nextServerlessLoader: loader.Loader = function () {
return result return result
} catch (err) { } catch (err) {
if (!parsedUrl) { if (!parsedUrl) {
parsedUrl = parse(req.url, true) parsedUrl = parseUrl(req.url, true)
} }
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
......
import { useRouter } from 'next/router'
export async function getServerSideProps({ query }) { export async function getServerSideProps({ query }) {
return { return {
props: { props: {
...@@ -16,6 +18,7 @@ export default function Page(props) { ...@@ -16,6 +18,7 @@ export default function Page(props) {
: `[${props.query.optionalName.join('|')}]`} : `[${props.query.optionalName.join('|')}]`}
</div> </div>
<div id="keys">{JSON.stringify(Object.keys(props.query))}</div> <div id="keys">{JSON.stringify(Object.keys(props.query))}</div>
<div id="asPath">{useRouter().asPath}</div>
</> </>
) )
} }
import { useRouter } from 'next/router'
export async function getServerSideProps({ query }) { export async function getServerSideProps({ query }) {
return { return {
props: { props: {
...@@ -16,6 +18,7 @@ export default function Page(props) { ...@@ -16,6 +18,7 @@ export default function Page(props) {
: `[${props.query.optionalName.join('|')}]`} : `[${props.query.optionalName.join('|')}]`}
</div> </div>
<div id="keys">{JSON.stringify(Object.keys(props.query))}</div> <div id="keys">{JSON.stringify(Object.keys(props.query))}</div>
<div id="asPath">{useRouter().asPath}</div>
</> </>
) )
} }
...@@ -375,18 +375,23 @@ describe('Dynamic Optional Routing', () => { ...@@ -375,18 +375,23 @@ describe('Dynamic Optional Routing', () => {
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#route').text()).toBe('top level route param: undefined') expect($('#route').text()).toBe('top level route param: undefined')
expect($('#keys').text()).toBe('[]') expect($('#keys').text()).toBe('[]')
expect($('#asPath').text()).toBe('/')
}) })
it('should render top level optional catch-all one level', async () => { it('should render top level optional catch-all one level', async () => {
const html = await render('/hello', { optionalName: 'hello' }) const html = await render('/hello', { optionalName: 'hello' })
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#route').text()).toBe('top level route param: [hello]') expect($('#route').text()).toBe('top level route param: [hello]')
expect($('#keys').text()).toBe('["optionalName"]')
expect($('#asPath').text()).toBe('/hello')
}) })
it('should render top level optional catch-all two levels', async () => { it('should render top level optional catch-all two levels', async () => {
const html = await render('/hello/world', { optionalName: 'hello/world' }) const html = await render('/hello/world', { optionalName: 'hello/world' })
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#route').text()).toBe('top level route param: [hello|world]') expect($('#route').text()).toBe('top level route param: [hello|world]')
expect($('#keys').text()).toBe('["optionalName"]')
expect($('#asPath').text()).toBe('/hello/world')
}) })
it('should render nested optional catch-all root', async () => { it('should render nested optional catch-all root', async () => {
...@@ -394,12 +399,15 @@ describe('Dynamic Optional Routing', () => { ...@@ -394,12 +399,15 @@ describe('Dynamic Optional Routing', () => {
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#route').text()).toBe('nested route param: undefined') expect($('#route').text()).toBe('nested route param: undefined')
expect($('#keys').text()).toBe('[]') expect($('#keys').text()).toBe('[]')
expect($('#asPath').text()).toBe('/nested')
}) })
it('should render nested optional catch-all one level', async () => { it('should render nested optional catch-all one level', async () => {
const html = await render('/nested/hello', { optionalName: 'hello' }) const html = await render('/nested/hello', { optionalName: 'hello' })
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#route').text()).toBe('nested route param: [hello]') expect($('#route').text()).toBe('nested route param: [hello]')
expect($('#keys').text()).toBe('["optionalName"]')
expect($('#asPath').text()).toBe('/nested/hello')
}) })
it('should render nested optional catch-all two levels', async () => { it('should render nested optional catch-all two levels', async () => {
...@@ -408,6 +416,8 @@ describe('Dynamic Optional Routing', () => { ...@@ -408,6 +416,8 @@ describe('Dynamic Optional Routing', () => {
}) })
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#route').text()).toBe('nested route param: [hello|world]') expect($('#route').text()).toBe('nested route param: [hello|world]')
expect($('#keys').text()).toBe('["optionalName"]')
expect($('#asPath').text()).toBe('/nested/hello/world')
}) })
it('should render optional catch-all api root', async () => { it('should render optional catch-all api root', async () => {
......
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