Unverified Commit dd6a0898 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Normalize missing optional value on Vercel (#15593)

This updates collecting dynamic route params on Vercel to make sure that missing optional dynamic routes are undefined. Additional tests for this mode have also been added to ensure the params are being collected properly

Closes: https://github.com/vercel/next.js/issues/15579
parent 3ffef602
...@@ -80,16 +80,31 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -80,16 +80,31 @@ const nextServerlessLoader: loader.Loader = function () {
.reduce((prev, key) => { .reduce((prev, key) => {
let value = query[key] let value = query[key]
${
''
// non-provided optional values should be undefined so normalize
// them to undefined
}
if(routeRegex.groups[key].optional && !value) {
value = undefined
delete query[key]
}
${ ${
'' ''
// query values from the proxy aren't already split into arrays // query values from the proxy aren't already split into arrays
// so make sure to normalize catch-all values // so make sure to normalize catch-all values
} }
if (routeRegex.groups[key].repeat) { if (
value &&
typeof value === 'string' &&
routeRegex.groups[key].repeat
) {
value = value.split('/') value = value.split('/')
} }
if (value) {
prev[key] = value prev[key] = value
}
return prev return prev
}, {}) }, {})
} }
......
...@@ -23,7 +23,7 @@ export type __ApiPreviewProps = { ...@@ -23,7 +23,7 @@ export type __ApiPreviewProps = {
export async function apiResolver( export async function apiResolver(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
params: any, query: any,
resolverModule: any, resolverModule: any,
apiContext: __ApiPreviewProps, apiContext: __ApiPreviewProps,
propagateError: boolean, propagateError: boolean,
...@@ -45,7 +45,7 @@ export async function apiResolver( ...@@ -45,7 +45,7 @@ export async function apiResolver(
// Parsing of cookies // Parsing of cookies
setLazyProp({ req: apiReq }, 'cookies', getCookieParser(req)) setLazyProp({ req: apiReq }, 'cookies', getCookieParser(req))
// Parsing query string // Parsing query string
setLazyProp({ req: apiReq, params }, 'query', getQueryParser(req)) apiReq.query = query
// Parsing preview data // Parsing preview data
setLazyProp({ req: apiReq }, 'previewData', () => setLazyProp({ req: apiReq }, 'previewData', () =>
tryGetPreviewData(req, res, apiContext) tryGetPreviewData(req, res, apiContext)
......
...@@ -12,7 +12,7 @@ const server = http.createServer((req, res) => { ...@@ -12,7 +12,7 @@ const server = http.createServer((req, res) => {
return render('/gssp.js') return render('/gssp.js')
} }
default: { default: {
res.statusCode(404) res.statusCode = 404
return res.end('404') return res.end('404')
} }
} }
......
...@@ -8,11 +8,14 @@ export async function getServerSideProps({ query }) { ...@@ -8,11 +8,14 @@ export async function getServerSideProps({ query }) {
export default function Page(props) { export default function Page(props) {
return ( return (
<>
<div id="route"> <div id="route">
top level route param:{' '} top level route param:{' '}
{props.query.optionalName === undefined {props.query.optionalName === undefined
? 'undefined' ? 'undefined'
: `[${props.query.optionalName.join('|')}]`} : `[${props.query.optionalName.join('|')}]`}
</div> </div>
<div id="keys">{JSON.stringify(Object.keys(props.query))}</div>
</>
) )
} }
...@@ -8,11 +8,14 @@ export async function getServerSideProps({ query }) { ...@@ -8,11 +8,14 @@ export async function getServerSideProps({ query }) {
export default function Page(props) { export default function Page(props) {
return ( return (
<>
<div id="route"> <div id="route">
nested route param:{' '} nested route param:{' '}
{props.query.optionalName === undefined {props.query.optionalName === undefined
? 'undefined' ? 'undefined'
: `[${props.query.optionalName.join('|')}]`} : `[${props.query.optionalName.join('|')}]`}
</div> </div>
<div id="keys">{JSON.stringify(Object.keys(props.query))}</div>
</>
) )
} }
const path = require('path')
const http = require('http')
const url = require('url')
const server = http.createServer((req, res) => {
const render = async (page) => {
const mod = require(`./${path.join('.next/serverless/pages/', page)}`)
try {
return await (mod.render || mod.default || mod)(req, res)
} catch (err) {
res.statusCode = 500
return res.end('internal error')
}
}
const { pathname } = url.parse(req.url)
switch (pathname) {
case '/api/post':
case '/api/post/hello':
case '/api/post/hello/world': {
return render('/api/post/[[...slug]].js')
}
case '/nested':
case '/nested/hello':
case '/nested/hello/world': {
return render('/nested/[[...optionalName]].js')
}
case '/':
case '/hello':
case '/hello/world': {
return render('/[[...optionalName]].js')
}
default: {
res.statusCode = 404
return res.end('404')
}
}
})
const port = process.env.PORT || 3000
server.listen(port, () => {
console.log('ready on', port)
})
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
nextStart, nextStart,
renderViaHTTP, renderViaHTTP,
check, check,
initNextServerScript,
} from 'next-test-utils' } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
...@@ -322,7 +323,7 @@ describe('Dynamic Optional Routing', () => { ...@@ -322,7 +323,7 @@ describe('Dynamic Optional Routing', () => {
origNextConfig = await fs.readFile(nextConfig, 'utf8') origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
`module.exports = { target: 'serverless' }` `module.exports = { target: 'experimental-serverless-trace' }`
) )
await nextBuild(appDir) await nextBuild(appDir)
...@@ -336,4 +337,95 @@ describe('Dynamic Optional Routing', () => { ...@@ -336,4 +337,95 @@ describe('Dynamic Optional Routing', () => {
}) })
runTests() runTests()
}) })
describe('raw serverless mode', () => {
let origNextConfig
beforeAll(async () => {
origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
`module.exports = { target: 'experimental-serverless-trace' }`
)
await nextBuild(appDir)
appPort = await findPort()
app = await initNextServerScript(join(appDir, 'server.js'), /ready on/, {
...process.env,
PORT: appPort,
})
})
afterAll(async () => {
await fs.writeFile(nextConfig, origNextConfig)
await killApp(app)
})
const render = (path, query) => {
return fetchViaHTTP(appPort, path, query, {
headers: {
// force relying on query values
'x-vercel-id': 'hi',
},
}).then((res) => res.text())
}
it('should render top level optional catch-all root', async () => {
const html = await render('/', { optionalName: '' })
const $ = cheerio.load(html)
expect($('#route').text()).toBe('top level route param: undefined')
expect($('#keys').text()).toBe('[]')
})
it('should render top level optional catch-all one level', async () => {
const html = await render('/hello', { optionalName: 'hello' })
const $ = cheerio.load(html)
expect($('#route').text()).toBe('top level route param: [hello]')
})
it('should render top level optional catch-all two levels', async () => {
const html = await render('/hello/world', { optionalName: 'hello/world' })
const $ = cheerio.load(html)
expect($('#route').text()).toBe('top level route param: [hello|world]')
})
it('should render nested optional catch-all root', async () => {
const html = await render('/nested', { optionalName: '' })
const $ = cheerio.load(html)
expect($('#route').text()).toBe('nested route param: undefined')
expect($('#keys').text()).toBe('[]')
})
it('should render nested optional catch-all one level', async () => {
const html = await render('/nested/hello', { optionalName: 'hello' })
const $ = cheerio.load(html)
expect($('#route').text()).toBe('nested route param: [hello]')
})
it('should render nested optional catch-all two levels', async () => {
const html = await render('/nested/hello/world', {
optionalName: 'hello/world',
})
const $ = cheerio.load(html)
expect($('#route').text()).toBe('nested route param: [hello|world]')
})
it('should render optional catch-all api root', async () => {
const text = await render('/api/post', { slug: '' })
const data = JSON.parse(text)
expect(data).toEqual({})
})
it('should render optional catch-all api root one level', async () => {
const text = await render('/api/post/hello', { slug: 'hello' })
const data = JSON.parse(text)
expect(data).toEqual({ slug: ['hello'] })
})
it('should render optional catch-all api root two levels', async () => {
const text = await render('/api/post/hello', { slug: 'hello/world' })
const data = JSON.parse(text)
expect(data).toEqual({ slug: ['hello', 'world'] })
})
})
}) })
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