Unverified Commit 3099f088 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add initial SSG fallback handling (#10424)

* Add initial SSG fallback handling

* Remove extra changes and update fallback handling

* Remove extra timeout for testing

* Update SSG tests in dynamic-routing suite

* Add racing to decide between rendering fallback and data

* Update size-limit test

* Update comment

* Make sure to follow correct route change order

* Make comment more verbose for racing

* Revert getStaticData to only return Promise

* Make sure to update URL on fallback

* Add retrying for data, de-dupe initial fallback request, and merge fallback replace

* Update to add preload for fallback pages data

* Add test for data preload link

* Use pre-built fallback in production mode

* Remove preload link for fallback from _document

* Update to make sure fallback is rendered correctly for serverless
parent 5e4850ce
...@@ -88,7 +88,7 @@ export type SsgRoute = { ...@@ -88,7 +88,7 @@ export type SsgRoute = {
export type DynamicSsgRoute = { export type DynamicSsgRoute = {
routeRegex: string routeRegex: string
fallback: string
dataRoute: string dataRoute: string
dataRouteRegex: string dataRouteRegex: string
} }
...@@ -639,15 +639,16 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -639,15 +639,16 @@ export default async function build(dir: string, conf = null): Promise<void> {
// n.b. we cannot handle this above in combinedPages because the dynamic // n.b. we cannot handle this above in combinedPages because the dynamic
// page must be in the `pages` array, but not in the mapping. // page must be in the `pages` array, but not in the mapping.
exportPathMap: (defaultMap: any) => { exportPathMap: (defaultMap: any) => {
// Remove dynamically routed pages from the default path map. These // Generate fallback for dynamically routed pages to use as
// pages cannot be prerendered because we don't have enough information // the loading state for pages while the data is being populated
// to do so.
// //
// Note: prerendering disables automatic static optimization. // Note: prerendering disables automatic static optimization.
ssgPages.forEach(page => { ssgPages.forEach(page => {
if (isDynamicRoute(page)) { if (isDynamicRoute(page)) {
tbdPrerenderRoutes.push(page) tbdPrerenderRoutes.push(page)
delete defaultMap[page] // set __nextFallback query so render doesn't call
// getStaticProps/getServerProps
defaultMap[page] = { page, query: { __nextFallback: true } }
} }
}) })
// Append the "well-known" routes we should prerender for, e.g. blog // Append the "well-known" routes we should prerender for, e.g. blog
...@@ -711,13 +712,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -711,13 +712,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
for (const page of combinedPages) { for (const page of combinedPages) {
const isSsg = ssgPages.has(page) const isSsg = ssgPages.has(page)
const isDynamic = isDynamicRoute(page) const isDynamic = isDynamicRoute(page)
const file = normalizePagePath(page)
// The dynamic version of SSG pages are not prerendered. Below, we handle
// the specific prerenders of these.
if (!(isSsg && isDynamic)) {
await moveExportedPage(page, file, isSsg, 'html')
}
const hasAmp = hybridAmpPages.has(page) const hasAmp = hybridAmpPages.has(page)
let file = normalizePagePath(page)
// We should always have an HTML file to move for each page
await moveExportedPage(page, file, isSsg, 'html')
if (hasAmp) { if (hasAmp) {
await moveExportedPage(`${page}.amp`, `${file}.amp`, isSsg, 'html') await moveExportedPage(`${page}.amp`, `${file}.amp`, isSsg, 'html')
} }
...@@ -734,8 +734,9 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -734,8 +734,9 @@ export default async function build(dir: string, conf = null): Promise<void> {
dataRoute: path.posix.join('/_next/data', buildId, `${file}.json`), dataRoute: path.posix.join('/_next/data', buildId, `${file}.json`),
} }
} else { } else {
// For a dynamic SSG page, we did not copy its html nor data exports. // For a dynamic SSG page, we did not copy its data exports and only
// Instead, we must copy specific versions of this page as defined by // copy the fallback HTML file.
// We must also copy specific versions of this page as defined by
// `unstable_getStaticPaths` (additionalSsgPaths). // `unstable_getStaticPaths` (additionalSsgPaths).
const extraRoutes = additionalSsgPaths.get(page) || [] const extraRoutes = additionalSsgPaths.get(page) || []
for (const route of extraRoutes) { for (const route of extraRoutes) {
...@@ -778,15 +779,17 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -778,15 +779,17 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (ssgPages.size > 0) { if (ssgPages.size > 0) {
const finalDynamicRoutes: PrerenderManifest['dynamicRoutes'] = {} const finalDynamicRoutes: PrerenderManifest['dynamicRoutes'] = {}
tbdPrerenderRoutes.forEach(tbdRoute => { tbdPrerenderRoutes.forEach(tbdRoute => {
const normalizedRoute = normalizePagePath(tbdRoute)
const dataRoute = path.posix.join( const dataRoute = path.posix.join(
'/_next/data', '/_next/data',
buildId, buildId,
`${normalizePagePath(tbdRoute)}.json` `${normalizedRoute}.json`
) )
finalDynamicRoutes[tbdRoute] = { finalDynamicRoutes[tbdRoute] = {
routeRegex: getRouteRegex(tbdRoute).re.source, routeRegex: getRouteRegex(tbdRoute).re.source,
dataRoute, dataRoute,
fallback: `${normalizedRoute}.html`,
dataRouteRegex: getRouteRegex( dataRouteRegex: getRouteRegex(
dataRoute.replace(/\.json$/, '') dataRoute.replace(/\.json$/, '')
).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$'), ).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$'),
......
...@@ -308,7 +308,9 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -308,7 +308,9 @@ 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
let result = await renderToHTML(req, res, "${page}", Object.assign({}, unstable_getStaticProps ? {} : parsedUrl.query, nowParams ? nowParams : params, _params), renderOpts) const isFallback = parsedUrl.query.__nextFallback
let result = await renderToHTML(req, res, "${page}", Object.assign({}, unstable_getStaticProps ? {} : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? { __nextFallback: 'true' } : {}), renderOpts)
if (_nextData && !fromExport) { if (_nextData && !fromExport) {
const payload = JSON.stringify(renderOpts.pageData) const payload = JSON.stringify(renderOpts.pageData)
......
...@@ -44,6 +44,7 @@ const { ...@@ -44,6 +44,7 @@ const {
assetPrefix, assetPrefix,
runtimeConfig, runtimeConfig,
dynamicIds, dynamicIds,
isFallback,
} = data } = data
const prefix = assetPrefix || '' const prefix = assetPrefix || ''
...@@ -98,10 +99,12 @@ class Container extends React.Component { ...@@ -98,10 +99,12 @@ class Container extends React.Component {
// If page was exported and has a querystring // If page was exported and has a querystring
// If it's a dynamic route or has a querystring // If it's a dynamic route or has a querystring
// if it's a fallback page
if ( if (
router.isSsr && router.isSsr &&
((data.nextExport && (isFallback ||
(isDynamicRoute(router.pathname) || location.search)) || (data.nextExport &&
(isDynamicRoute(router.pathname) || location.search)) ||
(Component && Component.__N_SSG && location.search)) (Component && Component.__N_SSG && location.search))
) { ) {
// update query on mount for exported pages // update query on mount for exported pages
...@@ -118,7 +121,7 @@ class Container extends React.Component { ...@@ -118,7 +121,7 @@ class Container extends React.Component {
// client-side hydration. Your app should _never_ use this property. // client-side hydration. Your app should _never_ use this property.
// It may change at any time without notice. // It may change at any time without notice.
_h: 1, _h: 1,
shallow: true, shallow: !isFallback,
} }
) )
} }
......
...@@ -78,17 +78,15 @@ const fetchNextData = ( ...@@ -78,17 +78,15 @@ const fetchNextData = (
) )
.then(res => { .then(res => {
if (!res.ok) { if (!res.ok) {
throw new Error(`Failed to load static props`) const error = new Error(`Failed to load static props`)
;(error as any).statusCode = res.status
throw error
} }
return res.json() return res.json()
}) })
.then(data => { .then(data => {
return cb ? cb(data) : data return cb ? cb(data) : data
}) })
.catch((err: Error) => {
;(err as any).code = 'PAGE_LOAD_ERROR'
throw err
})
} }
export default class Router implements BaseRouter { export default class Router implements BaseRouter {
...@@ -393,31 +391,65 @@ export default class Router implements BaseRouter { ...@@ -393,31 +391,65 @@ export default class Router implements BaseRouter {
// If shallow is true and the route exists in the router cache we reuse the previous result // If shallow is true and the route exists in the router cache we reuse the previous result
this.getRouteInfo(route, pathname, query, as, shallow).then(routeInfo => { this.getRouteInfo(route, pathname, query, as, shallow).then(routeInfo => {
const { error } = routeInfo let emitHistory = false
if (error && error.cancelled) { const doRouteChange = (routeInfo: RouteInfo, complete: boolean) => {
return resolve(false) const { error } = routeInfo
}
Router.events.emit('beforeHistoryChange', as) if (error && error.cancelled) {
this.changeState(method, url, addBasePath(as), options) return resolve(false)
}
if (process.env.NODE_ENV !== 'production') { if (!emitHistory) {
const appComp: any = this.components['/_app'].Component emitHistory = true
;(window as any).next.isPrerendered = Router.events.emit('beforeHistoryChange', as)
appComp.getInitialProps === appComp.origGetInitialProps && this.changeState(method, url, addBasePath(as), options)
!(routeInfo.Component as any).getInitialProps }
}
if (process.env.NODE_ENV !== 'production') {
const appComp: any = this.components['/_app'].Component
;(window as any).next.isPrerendered =
appComp.getInitialProps === appComp.origGetInitialProps &&
!(routeInfo.Component as any).getInitialProps
}
this.set(route, pathname, query, as, routeInfo)
this.set(route, pathname, query, as, routeInfo) if (complete) {
if (error) {
Router.events.emit('routeChangeError', error, as)
throw error
}
if (error) { Router.events.emit('routeChangeComplete', as)
Router.events.emit('routeChangeError', error, as) resolve(true)
throw error }
} }
Router.events.emit('routeChangeComplete', as) if ((routeInfo as any).dataRes) {
return resolve(true) const dataRes = (routeInfo as any).dataRes as Promise<RouteInfo>
// to prevent a flash of the fallback page we delay showing it for
// 110ms and race the timeout with the data response. If the data
// beats the timeout we skip showing the fallback
Promise.race([
new Promise(resolve => setTimeout(() => resolve(false), 110)),
dataRes,
])
.then((data: any) => {
if (!data) {
// data didn't win the race, show fallback
doRouteChange(routeInfo, false)
}
return dataRes
})
.then(finalData => {
// render with the data and complete route change
doRouteChange(finalData as RouteInfo, true)
}, reject)
} else {
doRouteChange(routeInfo, true)
}
}, reject) }, reject)
}) })
} }
...@@ -486,25 +518,51 @@ export default class Router implements BaseRouter { ...@@ -486,25 +518,51 @@ export default class Router implements BaseRouter {
} }
} }
return this._getData<RouteInfo>(() => const isSSG = (Component as any).__N_SSG
(Component as any).__N_SSG const isSSP = (Component as any).__N_SSP
? this._getStaticData(as)
: (Component as any).__N_SSP const handleData = (props: any) => {
? this._getServerData(as)
: this.getInitialProps(
Component,
// we provide AppTree later so this needs to be `any`
{
pathname,
query,
asPath: as,
} as any
)
).then(props => {
routeInfo.props = props routeInfo.props = props
this.components[route] = routeInfo this.components[route] = routeInfo
return routeInfo return routeInfo
}) }
// resolve with fallback routeInfo and promise for data
if (isSSG || isSSP) {
const dataMethod = () =>
isSSG ? this._getStaticData(as) : this._getServerData(as)
const retry = (error: Error & { statusCode: number }) => {
if (error.statusCode === 404) {
throw error
}
return dataMethod()
}
return Promise.resolve({
...routeInfo,
props: {},
dataRes: this._getData(() =>
dataMethod()
// we retry for data twice unless we get a 404
.catch(retry)
.catch(retry)
.then((props: any) => handleData(props))
),
})
}
return this._getData<RouteInfo>(() =>
this.getInitialProps(
Component,
// we provide AppTree later so this needs to be `any`
{
pathname,
query,
asPath: as,
} as any
)
).then(props => handleData(props))
}) })
.catch(err => { .catch(err => {
return new Promise(resolve => { return new Promise(resolve => {
......
...@@ -76,6 +76,7 @@ export type NEXT_DATA = { ...@@ -76,6 +76,7 @@ export type NEXT_DATA = {
runtimeConfig?: { [key: string]: any } runtimeConfig?: { [key: string]: any }
nextExport?: boolean nextExport?: boolean
autoExport?: boolean autoExport?: boolean
isFallback?: boolean
dynamicIds?: string[] dynamicIds?: string[]
err?: Error & { statusCode?: number } err?: Error & { statusCode?: number }
} }
......
...@@ -43,7 +43,12 @@ import Router, { ...@@ -43,7 +43,12 @@ import Router, {
} from './router' } from './router'
import { sendHTML } from './send-html' import { sendHTML } from './send-html'
import { serveStatic } from './serve-static' import { serveStatic } from './serve-static'
import { getSprCache, initializeSprCache, setSprCache } from './spr-cache' import {
getSprCache,
initializeSprCache,
setSprCache,
getFallback,
} from './spr-cache'
import { isBlockedPage } from './utils' import { isBlockedPage } from './utils'
import { import {
Redirect, Redirect,
...@@ -1010,6 +1015,28 @@ export default class Server { ...@@ -1010,6 +1015,28 @@ export default class Server {
return { html, pageData, sprRevalidate } return { html, pageData, sprRevalidate }
}) })
// render fallback if cached data wasn't available
if (!isResSent(res) && !isDataReq && isDynamicRoute(pathname)) {
let html = ''
if (!this.renderOpts.dev) {
html = await getFallback(pathname)
} else {
query.__nextFallback = 'true'
if (isLikeServerless) {
this.prepareServerlessUrl(req, query)
html = await (result.Component as any).renderReqToHTML(req, res)
} else {
html = (await renderToHTML(req, res, pathname, query, {
...result,
...opts,
})) as string
}
}
this.__sendPayload(res, html, 'text/html; charset=utf-8')
}
return doRender(ssgCacheKey, []).then( return doRender(ssgCacheKey, []).then(
async ({ isOrigin, value: { html, pageData, sprRevalidate } }) => { async ({ isOrigin, value: { html, pageData, sprRevalidate } }) => {
// Respond to the request if a payload wasn't sent above (from cache) // Respond to the request if a payload wasn't sent above (from cache)
......
...@@ -152,6 +152,7 @@ function renderDocument( ...@@ -152,6 +152,7 @@ function renderDocument(
runtimeConfig, runtimeConfig,
nextExport, nextExport,
autoExport, autoExport,
isFallback,
dynamicImportsIds, dynamicImportsIds,
dangerousAsPath, dangerousAsPath,
hasCssMode, hasCssMode,
...@@ -187,6 +188,7 @@ function renderDocument( ...@@ -187,6 +188,7 @@ function renderDocument(
htmlProps: any htmlProps: any
bodyTags: any bodyTags: any
headTags: any headTags: any
isFallback?: boolean
} }
): string { ): string {
return ( return (
...@@ -203,6 +205,7 @@ function renderDocument( ...@@ -203,6 +205,7 @@ function renderDocument(
runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML
nextExport, // If this is a page exported by `next export` nextExport, // If this is a page exported by `next export`
autoExport, // If this is an auto exported page autoExport, // If this is an auto exported page
isFallback,
dynamicIds: dynamicIds:
dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds, dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
...@@ -294,6 +297,9 @@ export async function renderToHTML( ...@@ -294,6 +297,9 @@ export async function renderToHTML(
const bodyTags = (...args: any) => callMiddleware('bodyTags', args) const bodyTags = (...args: any) => callMiddleware('bodyTags', args)
const htmlProps = (...args: any) => callMiddleware('htmlProps', args, true) const htmlProps = (...args: any) => callMiddleware('htmlProps', args, true)
const isFallback = !!query.__nextFallback
delete query.__nextFallback
const isSpr = !!unstable_getStaticProps const isSpr = !!unstable_getStaticProps
const defaultAppGetInitialProps = const defaultAppGetInitialProps =
App.getInitialProps === (App as any).origGetInitialProps App.getInitialProps === (App as any).origGetInitialProps
...@@ -428,7 +434,7 @@ export async function renderToHTML( ...@@ -428,7 +434,7 @@ export async function renderToHTML(
ctx, ctx,
}) })
if (isSpr) { if (isSpr && !isFallback) {
const data = await unstable_getStaticProps!({ const data = await unstable_getStaticProps!({
params: isDynamicRoute(pathname) ? (query as any) : undefined, params: isDynamicRoute(pathname) ? (query as any) : undefined,
}) })
...@@ -483,7 +489,7 @@ export async function renderToHTML( ...@@ -483,7 +489,7 @@ export async function renderToHTML(
renderOpts.err = err renderOpts.err = err
} }
if (unstable_getServerProps) { if (unstable_getServerProps && !isFallback) {
const data = await unstable_getServerProps({ const data = await unstable_getServerProps({
params, params,
query, query,
...@@ -504,6 +510,12 @@ export async function renderToHTML( ...@@ -504,6 +510,12 @@ export async function renderToHTML(
// _app's getInitialProps for getServerProps if not this can be removed // _app's getInitialProps for getServerProps if not this can be removed
if (isDataReq) return props if (isDataReq) return props
// We don't call getStaticProps or getServerProps while generating
// the fallback so make sure to set pageProps to an empty object
if (isFallback) {
props.pageProps = {}
}
// the response might be finished on the getInitialProps call // the response might be finished on the getInitialProps call
if (isResSent(res) && !isSpr) return null if (isResSent(res) && !isSpr) return null
...@@ -600,6 +612,7 @@ export async function renderToHTML( ...@@ -600,6 +612,7 @@ export async function renderToHTML(
headTags: await headTags(documentCtx), headTags: await headTags(documentCtx),
bodyTags: await bodyTags(documentCtx), bodyTags: await bodyTags(documentCtx),
htmlProps: await htmlProps(documentCtx), htmlProps: await htmlProps(documentCtx),
isFallback,
docProps, docProps,
pathname, pathname,
ampPath, ampPath,
......
...@@ -92,6 +92,11 @@ export function initializeSprCache({ ...@@ -92,6 +92,11 @@ export function initializeSprCache({
}) })
} }
export async function getFallback(page: string): Promise<string> {
page = normalizePagePath(page)
return readFile(getSeedPath(page, 'html'), 'utf8')
}
// get data from SPR cache if available // get data from SPR cache if available
export async function getSprCache( export async function getSprCache(
pathname: string pathname: string
......
...@@ -239,48 +239,58 @@ function runTests(dev) { ...@@ -239,48 +239,58 @@ function runTests(dev) {
} }
}) })
it('[ssg: catch all] should pass param in getInitialProps during SSR', async () => { it('[ssg: catch all] should pass param in getStaticProps during SSR', async () => {
const html = await renderViaHTTP(appPort, '/p1/p2/all-ssg/test1') const data = await renderViaHTTP(
const $ = cheerio.load(html) appPort,
expect($('#all-ssg-content').text()).toBe('{"rest":["test1"]}') `/_next/data/${buildId}/p1/p2/all-ssg/test1.json`
)
expect(JSON.parse(data).pageProps.params).toEqual({ rest: ['test1'] })
}) })
it('[ssg: catch all] should pass params in getInitialProps during SSR', async () => { it('[ssg: catch all] should pass params in getStaticProps during SSR', async () => {
const html = await renderViaHTTP(appPort, '/p1/p2/all-ssg/test1/test2') const data = await renderViaHTTP(
const $ = cheerio.load(html) appPort,
expect($('#all-ssg-content').text()).toBe('{"rest":["test1","test2"]}') `/_next/data/${buildId}/p1/p2/all-ssg/test1/test2.json`
)
expect(JSON.parse(data).pageProps.params).toEqual({
rest: ['test1', 'test2'],
})
}) })
it('[predefined ssg: catch all] should pass param in getInitialProps during SSR', async () => { it('[predefined ssg: catch all] should pass param in getStaticProps during SSR', async () => {
const html = await renderViaHTTP(appPort, '/p1/p2/predefined-ssg/test1') const data = await renderViaHTTP(
const $ = cheerio.load(html) appPort,
expect($('#all-ssg-content').text()).toBe('{"rest":["test1"]}') `/_next/data/${buildId}/p1/p2/predefined-ssg/test1.json`
)
expect(JSON.parse(data).pageProps.params).toEqual({ rest: ['test1'] })
}) })
it('[predefined ssg: catch all] should pass params in getInitialProps during SSR', async () => { it('[predefined ssg: catch all] should pass params in getStaticProps during SSR', async () => {
const html = await renderViaHTTP( const data = await renderViaHTTP(
appPort, appPort,
'/p1/p2/predefined-ssg/test1/test2' `/_next/data/${buildId}/p1/p2/predefined-ssg/test1/test2.json`
) )
const $ = cheerio.load(html) expect(JSON.parse(data).pageProps.params).toEqual({
expect($('#all-ssg-content').text()).toBe('{"rest":["test1","test2"]}') rest: ['test1', 'test2'],
})
}) })
it('[predefined ssg: prerendered catch all] should pass param in getInitialProps during SSR', async () => { it('[predefined ssg: prerendered catch all] should pass param in getInitialProps during SSR', async () => {
const html = await renderViaHTTP(appPort, '/p1/p2/predefined-ssg/one-level') const data = await renderViaHTTP(
const $ = cheerio.load(html) appPort,
expect($('#all-ssg-content').text()).toBe('{"rest":["one-level"]}') `/_next/data/${buildId}/p1/p2/predefined-ssg/one-level.json`
)
expect(JSON.parse(data).pageProps.params).toEqual({ rest: ['one-level'] })
}) })
it('[predefined ssg: prerendered catch all] should pass params in getInitialProps during SSR', async () => { it('[predefined ssg: prerendered catch all] should pass params in getInitialProps during SSR', async () => {
const html = await renderViaHTTP( const data = await renderViaHTTP(
appPort, appPort,
'/p1/p2/predefined-ssg/1st-level/2nd-level' `/_next/data/${buildId}/p1/p2/predefined-ssg/1st-level/2nd-level.json`
)
const $ = cheerio.load(html)
expect($('#all-ssg-content').text()).toBe(
'{"rest":["1st-level","2nd-level"]}'
) )
expect(JSON.parse(data).pageProps.params).toEqual({
rest: ['1st-level', '2nd-level'],
})
}) })
it('[ssg: catch-all] should pass params in getStaticProps during client navigation (single)', async () => { it('[ssg: catch-all] should pass params in getStaticProps during client navigation (single)', async () => {
...@@ -492,6 +502,7 @@ describe('Dynamic Routing', () => { ...@@ -492,6 +502,7 @@ describe('Dynamic Routing', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
buildId = 'development'
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
......
...@@ -22,6 +22,11 @@ export async function unstable_getStaticProps({ params }) { ...@@ -22,6 +22,11 @@ export async function unstable_getStaticProps({ params }) {
} }
export default ({ post, comment, time }) => { export default ({ post, comment, time }) => {
// we're in a loading state
if (!post) {
return <p>loading...</p>
}
return ( return (
<> <>
<p>Post: {post}</p> <p>Post: {post}</p>
......
...@@ -16,4 +16,4 @@ export async function unstable_getStaticPaths() { ...@@ -16,4 +16,4 @@ export async function unstable_getStaticPaths() {
] ]
} }
export default ({ slug }) => <p id="catchall">Hi {slug.join('/')}</p> export default ({ slug }) => <p id="catchall">Hi {slug?.join('/')}</p>
...@@ -253,7 +253,13 @@ const runTests = (dev = false) => { ...@@ -253,7 +253,13 @@ const runTests = (dev = false) => {
it('should SSR SPR page correctly', async () => { it('should SSR SPR page correctly', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1') const html = await renderViaHTTP(appPort, '/blog/post-1')
expect(html).toMatch(/Post:.*?post-1/)
if (dev) {
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(true)
} else {
expect(html).toMatch(/Post:.*?post-1/)
}
}) })
it('should not supply query values to params or useRouter non-dynamic page SSR', async () => { it('should not supply query values to params or useRouter non-dynamic page SSR', async () => {
...@@ -278,8 +284,13 @@ const runTests = (dev = false) => { ...@@ -278,8 +284,13 @@ const runTests = (dev = false) => {
it('should not supply query values to params or useRouter dynamic page SSR', async () => { it('should not supply query values to params or useRouter dynamic page SSR', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1?hello=world') const html = await renderViaHTTP(appPort, '/blog/post-1?hello=world')
const $ = cheerio.load(html) const $ = cheerio.load(html)
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ post: 'post-1' }) if (!dev) {
// these aren't available in dev since we render the fallback always
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ post: 'post-1' })
}
const query = $('#query').text() const query = $('#query').text()
expect(JSON.parse(query)).toEqual({ post: 'post-1' }) expect(JSON.parse(query)).toEqual({ post: 'post-1' })
}) })
...@@ -346,13 +357,24 @@ const runTests = (dev = false) => { ...@@ -346,13 +357,24 @@ const runTests = (dev = false) => {
it('should support prerendered catchall route', async () => { it('should support prerendered catchall route', async () => {
const html = await renderViaHTTP(appPort, '/catchall/another/value') const html = await renderViaHTTP(appPort, '/catchall/another/value')
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#catchall').text()).toMatch(/Hi.*?another\/value/)
if (dev) {
expect(
JSON.parse(
cheerio
.load(html)('#__NEXT_DATA__')
.text()
).isFallback
).toBe(true)
} else {
expect($('#catchall').text()).toMatch(/Hi.*?another\/value/)
}
}) })
it('should support lazy catchall route', async () => { it('should support lazy catchall route', async () => {
const html = await renderViaHTTP(appPort, '/catchall/third') const browser = await webdriver(appPort, '/catchall/third')
const $ = cheerio.load(html) const text = await browser.elementByCss('#catchall').text()
expect($('#catchall').text()).toMatch(/Hi.*?third/) expect(text).toMatch(/Hi.*?third/)
}) })
if (dev) { if (dev) {
...@@ -438,6 +460,7 @@ const runTests = (dev = false) => { ...@@ -438,6 +460,7 @@ const runTests = (dev = false) => {
expect(manifest.routes).toEqual(expectedManifestRoutes()) expect(manifest.routes).toEqual(expectedManifestRoutes())
expect(manifest.dynamicRoutes).toEqual({ expect(manifest.dynamicRoutes).toEqual({
'/blog/[post]': { '/blog/[post]': {
fallback: '/blog/[post].html',
dataRoute: `/_next/data/${buildId}/blog/[post].json`, dataRoute: `/_next/data/${buildId}/blog/[post].json`,
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\.json$` `^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\.json$`
...@@ -445,6 +468,7 @@ const runTests = (dev = false) => { ...@@ -445,6 +468,7 @@ const runTests = (dev = false) => {
routeRegex: normalizeRegEx('^\\/blog\\/([^\\/]+?)(?:\\/)?$'), routeRegex: normalizeRegEx('^\\/blog\\/([^\\/]+?)(?:\\/)?$'),
}, },
'/blog/[post]/[comment]': { '/blog/[post]/[comment]': {
fallback: '/blog/[post]/[comment].html',
dataRoute: `/_next/data/${buildId}/blog/[post]/[comment].json`, dataRoute: `/_next/data/${buildId}/blog/[post]/[comment].json`,
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$` `^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`
...@@ -454,6 +478,7 @@ const runTests = (dev = false) => { ...@@ -454,6 +478,7 @@ const runTests = (dev = false) => {
), ),
}, },
'/user/[user]/profile': { '/user/[user]/profile': {
fallback: '/user/[user]/profile.html',
dataRoute: `/_next/data/${buildId}/user/[user]/profile.json`, dataRoute: `/_next/data/${buildId}/user/[user]/profile.json`,
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/user\\/([^\\/]+?)\\/profile\\.json$` `^\\/_next\\/data\\/${escapedBuildId}\\/user\\/([^\\/]+?)\\/profile\\.json$`
...@@ -463,6 +488,7 @@ const runTests = (dev = false) => { ...@@ -463,6 +488,7 @@ const runTests = (dev = false) => {
), ),
}, },
'/catchall/[...slug]': { '/catchall/[...slug]': {
fallback: '/catchall/[...slug].html',
routeRegex: normalizeRegEx('^\\/catchall\\/(.+?)(?:\\/)?$'), routeRegex: normalizeRegEx('^\\/catchall\\/(.+?)(?:\\/)?$'),
dataRoute: `/_next/data/${buildId}/catchall/[...slug].json`, dataRoute: `/_next/data/${buildId}/catchall/[...slug].json`,
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
...@@ -489,11 +515,15 @@ const runTests = (dev = false) => { ...@@ -489,11 +515,15 @@ const runTests = (dev = false) => {
it('should handle de-duping correctly', async () => { it('should handle de-duping correctly', async () => {
let vals = new Array(10).fill(null) let vals = new Array(10).fill(null)
// use data route so we don't get the fallback
vals = await Promise.all( vals = await Promise.all(
vals.map(() => renderViaHTTP(appPort, '/blog/post-10')) vals.map(() =>
renderViaHTTP(appPort, `/_next/data/${buildId}/blog/post-10.json`)
)
) )
const val = vals[0] const val = vals[0]
expect(val).toMatch(/Post:.*?post-10/)
expect(JSON.parse(val).pageProps.post).toBe('post-10')
expect(new Set(vals).size).toBe(1) expect(new Set(vals).size).toBe(1)
}) })
......
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