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

Handle encoding for data requests and fix fallback response (#13622)

This addresses some errors for `/_next/data` requests where encoded `/` values in dynamic route param would cause invalid behavior, a headers already sent error would be shown when sending the fallback page in development, and when rendering the `_error` page for a data request the error response would still be treated as a data request. 

This also adds test cases for these errors to prevent regression
parent ee87e5d8
...@@ -427,11 +427,16 @@ export default class Server { ...@@ -427,11 +427,16 @@ export default class Server {
} }
// re-create page's pathname // re-create page's pathname
const pathname = `/${params.path.join('/')}` const pathname = `/${params.path
// we need to re-encode the params since they are decoded
// by path-match and we are re-building the URL
.map((param: string) => encodeURIComponent(param))
.join('/')}`
.replace(/\.json$/, '') .replace(/\.json$/, '')
.replace(/\/index$/, '/') .replace(/\/index$/, '/')
const parsedUrl = parseUrl(pathname, true) const parsedUrl = parseUrl(pathname, true)
await this.render( await this.render(
req, req,
res, res,
...@@ -960,7 +965,7 @@ export default class Server { ...@@ -960,7 +965,7 @@ export default class Server {
} }
// Toggle whether or not this is a Data request // Toggle whether or not this is a Data request
const isDataReq = !!query._nextDataReq const isDataReq = !!query._nextDataReq && (isSSG || isServerProps)
delete query._nextDataReq delete query._nextDataReq
let previewData: string | false | object | undefined let previewData: string | false | object | undefined
...@@ -1128,6 +1133,7 @@ export default class Server { ...@@ -1128,6 +1133,7 @@ export default class Server {
} }
sendPayload(res, html, 'html') sendPayload(res, html, 'html')
return null
} }
const { const {
......
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: true,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
unstable_revalidate: 1,
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
...@@ -503,6 +503,42 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -503,6 +503,42 @@ const runTests = (dev = false, looseMode = false) => {
expect($('#catchall').text()).toMatch(/Hi.*?second/) expect($('#catchall').text()).toMatch(/Hi.*?second/)
}) })
if (!looseMode) {
it('should handle fallback only page correctly HTML', async () => {
const browser = await webdriver(appPort, '/fallback-only/first%2Fpost')
const text = await browser.elementByCss('p').text()
expect(text).toContain('hi fallback')
// wait for fallback data to load
await check(() => browser.elementByCss('p').text(), /Post/)
// check fallback data
const post = await browser.elementByCss('p').text()
const query = JSON.parse(await browser.elementByCss('#query').text())
const params = JSON.parse(await browser.elementByCss('#params').text())
expect(post).toContain('first/post')
expect(params).toEqual({
slug: 'first/post',
})
expect(query).toEqual(params)
})
it('should handle fallback only page correctly data', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
`/_next/data/${buildId}/fallback-only/second%2Fpost.json`
)
)
expect(data.pageProps.params).toEqual({
slug: 'second/post',
})
})
}
if (!looseMode) { if (!looseMode) {
it('should 404 for a missing catchall explicit route', async () => { it('should 404 for a missing catchall explicit route', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
...@@ -746,6 +782,11 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -746,6 +782,11 @@ const runTests = (dev = false, looseMode = false) => {
/Failed to load static props/ /Failed to load static props/
) )
}) })
it('should not contain headers already sent error', async () => {
await renderViaHTTP(appPort, '/fallback-only/some-fallback-post')
expect(stderr).not.toContain('ERR_HTTP_HEADERS_SENT')
})
} else { } else {
if (!looseMode) { if (!looseMode) {
it('should should use correct caching headers for a no-revalidate page', async () => { it('should should use correct caching headers for a no-revalidate page', async () => {
...@@ -854,6 +895,18 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -854,6 +895,18 @@ const runTests = (dev = false, looseMode = false) => {
), ),
page: '/default-revalidate', page: '/default-revalidate',
}, },
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/fallback\\-only\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/fallback\\-only/(?<slug>[^/]+?)\\.json$`,
page: '/fallback-only/[slug]',
routeKeys: ['slug'],
},
{ {
namedDataRouteRegex: `^/_next/data/${escapeRegex( namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId buildId
...@@ -937,6 +990,16 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -937,6 +990,16 @@ const runTests = (dev = false, looseMode = false) => {
'^\\/blog\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$' '^\\/blog\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$'
), ),
}, },
'/fallback-only/[slug]': {
dataRoute: `/_next/data/${buildId}/fallback-only/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/fallback\\-only\\/([^\\/]+?)\\.json$`
),
fallback: '/fallback-only/[slug].html',
routeRegex: normalizeRegEx(
'^\\/fallback\\-only\\/([^\\/]+?)(?:\\/)?$'
),
},
'/lang/[lang]/about': { '/lang/[lang]/about': {
dataRoute: `/_next/data/${buildId}/lang/[lang]/about.json`, dataRoute: `/_next/data/${buildId}/lang/[lang]/about.json`,
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
...@@ -1361,6 +1424,7 @@ describe('SSG Prerender', () => { ...@@ -1361,6 +1424,7 @@ describe('SSG Prerender', () => {
'/catchall/[...slug].js', '/catchall/[...slug].js',
'/non-json/[p].js', '/non-json/[p].js',
'/blog/[post]/index.js', '/blog/[post]/index.js',
'/fallback-only/[slug].js',
] ]
const fallbackTruePageContents = {} const fallbackTruePageContents = {}
......
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