Unverified Commit 47ff1eb9 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Ability to Disable SSG Fallback (#10701)

* Ability to Disable SSG Fallback

* Throw error when value is missing

* Fix existing tests

* Adjust error message

* Do not render fallback at build time for `fallback: false` page

* Fix existing fallback behavior

* fix build

* fix version

* fix some tests

* Fix last test

* Add docs for get static paths

* Add explicit mode tests

* test for fallback error message
parent b3ffdabb
...@@ -11,7 +11,30 @@ Make sure to return the following shape from `unstable_getStaticPaths`: ...@@ -11,7 +11,30 @@ Make sure to return the following shape from `unstable_getStaticPaths`:
```js ```js
export async function unstable_getStaticPaths() { export async function unstable_getStaticPaths() {
return { return {
paths: Array<string | { params: { [key: string]: string } }> paths: Array<string | { params: { [key: string]: string } }>,
fallback: boolean
} }
} }
``` ```
There are two required properties:
1. `paths`: this property is an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of URLs ("paths") that should be statically generated at build-time. The returned paths must match the dynamic route shape.
- You may return a [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) or an [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) that explicitly defines all URL `params`.
```js
// pages/blog/[slug].js
export async function unstable_getStaticPaths() {
return {
paths: [
// String variant:
'/blog/first-post',
// Object variant:
{ params: { slug: 'second-post' } },
],
fallback: true,
}
}
```
1. `fallback`: this property is a [Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), specifying whether or not a fallback version of this page should be generated.
- Enabling `fallback` (via `true`) allows you to return a subset of all the possible paths that should be statically generated. At runtime, Next.js will statically generate the remaining paths the **first time they are requested**. Consecutive calls to the path will be served as-if it was statically generated at build-time. This reduces build times when dealing with thousands or millions of pages.
- Disabling `fallback` (via `false`) requires you return the full collection of paths you would like to statically generate at build-time. At runtime, any path that was not generated at build-time **will 404**.
...@@ -90,13 +90,13 @@ export type SsgRoute = { ...@@ -90,13 +90,13 @@ export type SsgRoute = {
export type DynamicSsgRoute = { export type DynamicSsgRoute = {
routeRegex: string routeRegex: string
fallback: string fallback: string | false
dataRoute: string dataRoute: string
dataRouteRegex: string dataRouteRegex: string
} }
export type PrerenderManifest = { export type PrerenderManifest = {
version: number version: 2
routes: { [route: string]: SsgRoute } routes: { [route: string]: SsgRoute }
dynamicRoutes: { [route: string]: DynamicSsgRoute } dynamicRoutes: { [route: string]: DynamicSsgRoute }
preview: __ApiPreviewProps preview: __ApiPreviewProps
...@@ -432,6 +432,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -432,6 +432,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
const buildManifestPath = path.join(distDir, BUILD_MANIFEST) const buildManifestPath = path.join(distDir, BUILD_MANIFEST)
const ssgPages = new Set<string>() const ssgPages = new Set<string>()
const ssgFallbackPages = new Set<string>()
const staticPages = new Set<string>() const staticPages = new Set<string>()
const invalidPages = new Set<string>() const invalidPages = new Set<string>()
const hybridAmpPages = new Set<string>() const hybridAmpPages = new Set<string>()
...@@ -478,6 +479,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -478,6 +479,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
let isStatic = false let isStatic = false
let isHybridAmp = false let isHybridAmp = false
let ssgPageRoutes: string[] | null = null let ssgPageRoutes: string[] | null = null
let hasSsgFallback: boolean = false
pagesManifest[page] = bundleRelative.replace(/\\/g, '/') pagesManifest[page] = bundleRelative.replace(/\\/g, '/')
...@@ -533,6 +535,10 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -533,6 +535,10 @@ export default async function build(dir: string, conf = null): Promise<void> {
additionalSsgPaths.set(page, result.prerenderRoutes) additionalSsgPaths.set(page, result.prerenderRoutes)
ssgPageRoutes = result.prerenderRoutes ssgPageRoutes = result.prerenderRoutes
} }
if (result.prerenderFallback) {
hasSsgFallback = true
ssgFallbackPages.add(page)
}
} else if (result.hasServerProps) { } else if (result.hasServerProps) {
serverPropsPages.add(page) serverPropsPages.add(page)
} else if (result.isStatic && customAppGetInitialProps === false) { } else if (result.isStatic && customAppGetInitialProps === false) {
...@@ -564,6 +570,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -564,6 +570,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
isSsg, isSsg,
isHybridAmp, isHybridAmp,
ssgPageRoutes, ssgPageRoutes,
hasSsgFallback,
}) })
}) })
) )
...@@ -669,9 +676,15 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -669,9 +676,15 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (isDynamicRoute(page)) { if (isDynamicRoute(page)) {
tbdPrerenderRoutes.push(page) tbdPrerenderRoutes.push(page)
// Override the rendering for the dynamic page to be treated as a if (ssgFallbackPages.has(page)) {
// fallback render. // Override the rendering for the dynamic page to be treated as a
defaultMap[page] = { page, query: { __nextFallback: true } } // fallback render.
defaultMap[page] = { page, query: { __nextFallback: true } }
} else {
// Remove dynamically routed pages from the default path map when
// fallback behavior is disabled.
delete defaultMap[page]
}
} }
}) })
// Append the "well-known" routes we should prerender for, e.g. blog // Append the "well-known" routes we should prerender for, e.g. blog
...@@ -736,12 +749,16 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -736,12 +749,16 @@ 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 isSsgFallback = ssgFallbackPages.has(page)
const isDynamic = isDynamicRoute(page) const isDynamic = isDynamicRoute(page)
const hasAmp = hybridAmpPages.has(page) const hasAmp = hybridAmpPages.has(page)
let file = normalizePagePath(page) let file = normalizePagePath(page)
// We should always have an HTML file to move for each page // The dynamic version of SSG pages are only prerendered if the fallback
await moveExportedPage(page, file, isSsg, 'html') // is enabled. Below, we handle the specific prerenders of these.
if (!(isSsg && isDynamic && !isSsgFallback)) {
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')
...@@ -760,7 +777,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -760,7 +777,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
} }
} else { } else {
// For a dynamic SSG page, we did not copy its data exports and only // For a dynamic SSG page, we did not copy its data exports and only
// copy the fallback HTML file. // copy the fallback HTML file (if present).
// We must also copy specific versions of this page as defined by // 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) || []
...@@ -814,14 +831,16 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -814,14 +831,16 @@ export default async function build(dir: string, conf = null): Promise<void> {
finalDynamicRoutes[tbdRoute] = { finalDynamicRoutes[tbdRoute] = {
routeRegex: getRouteRegex(tbdRoute).re.source, routeRegex: getRouteRegex(tbdRoute).re.source,
dataRoute, dataRoute,
fallback: `${normalizedRoute}.html`, fallback: ssgFallbackPages.has(tbdRoute)
? `${normalizedRoute}.html`
: false,
dataRouteRegex: getRouteRegex( dataRouteRegex: getRouteRegex(
dataRoute.replace(/\.json$/, '') dataRoute.replace(/\.json$/, '')
).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$'), ).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$'),
} }
}) })
const prerenderManifest: PrerenderManifest = { const prerenderManifest: PrerenderManifest = {
version: 1, version: 2,
routes: finalPrerenderRoutes, routes: finalPrerenderRoutes,
dynamicRoutes: finalDynamicRoutes, dynamicRoutes: finalDynamicRoutes,
preview: previewProps, preview: previewProps,
...@@ -834,7 +853,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -834,7 +853,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
) )
} else { } else {
const prerenderManifest: PrerenderManifest = { const prerenderManifest: PrerenderManifest = {
version: 1, version: 2,
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
preview: previewProps, preview: previewProps,
......
...@@ -42,6 +42,7 @@ export interface PageInfo { ...@@ -42,6 +42,7 @@ export interface PageInfo {
static: boolean static: boolean
isSsg: boolean isSsg: boolean
ssgPageRoutes: string[] | null ssgPageRoutes: string[] | null
hasSsgFallback: boolean
serverBundle: string serverBundle: string
} }
...@@ -500,7 +501,7 @@ export async function getPageSizeInKb( ...@@ -500,7 +501,7 @@ export async function getPageSizeInKb(
export async function buildStaticPaths( export async function buildStaticPaths(
page: string, page: string,
unstable_getStaticPaths: Unstable_getStaticPaths unstable_getStaticPaths: Unstable_getStaticPaths
): Promise<Array<string>> { ): Promise<{ paths: string[]; fallback: boolean }> {
const prerenderPaths = new Set<string>() const prerenderPaths = new Set<string>()
const _routeRegex = getRouteRegex(page) const _routeRegex = getRouteRegex(page)
const _routeMatcher = getRouteMatcher(_routeRegex) const _routeMatcher = getRouteMatcher(_routeRegex)
...@@ -511,7 +512,7 @@ export async function buildStaticPaths( ...@@ -511,7 +512,7 @@ export async function buildStaticPaths(
const staticPathsResult = await unstable_getStaticPaths() const staticPathsResult = await unstable_getStaticPaths()
const expectedReturnVal = const expectedReturnVal =
`Expected: { paths: [] }\n` + `Expected: { paths: [], fallback: boolean }\n` +
`See here for more info: https://err.sh/zeit/next.js/invalid-getstaticpaths-value` `See here for more info: https://err.sh/zeit/next.js/invalid-getstaticpaths-value`
if ( if (
...@@ -525,7 +526,7 @@ export async function buildStaticPaths( ...@@ -525,7 +526,7 @@ export async function buildStaticPaths(
} }
const invalidStaticPathKeys = Object.keys(staticPathsResult).filter( const invalidStaticPathKeys = Object.keys(staticPathsResult).filter(
key => key !== 'paths' key => !(key === 'paths' || key === 'fallback')
) )
if (invalidStaticPathKeys.length > 0) { if (invalidStaticPathKeys.length > 0) {
...@@ -536,6 +537,13 @@ export async function buildStaticPaths( ...@@ -536,6 +537,13 @@ export async function buildStaticPaths(
) )
} }
if (typeof staticPathsResult.fallback !== 'boolean') {
throw new Error(
`The \`fallback\` key must be returned from unstable_getStaticProps in ${page}.\n` +
expectedReturnVal
)
}
const toPrerender = staticPathsResult.paths const toPrerender = staticPathsResult.paths
if (!Array.isArray(toPrerender)) { if (!Array.isArray(toPrerender)) {
...@@ -601,7 +609,7 @@ export async function buildStaticPaths( ...@@ -601,7 +609,7 @@ export async function buildStaticPaths(
} }
}) })
return [...prerenderPaths] return { paths: [...prerenderPaths], fallback: staticPathsResult.fallback }
} }
export async function isPageStatic( export async function isPageStatic(
...@@ -614,6 +622,7 @@ export async function isPageStatic( ...@@ -614,6 +622,7 @@ export async function isPageStatic(
hasServerProps?: boolean hasServerProps?: boolean
hasStaticProps?: boolean hasStaticProps?: boolean
prerenderRoutes?: string[] | undefined prerenderRoutes?: string[] | undefined
prerenderFallback?: boolean | undefined
}> { }> {
try { try {
require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig) require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig)
...@@ -667,11 +676,12 @@ export async function isPageStatic( ...@@ -667,11 +676,12 @@ export async function isPageStatic(
} }
let prerenderRoutes: Array<string> | undefined let prerenderRoutes: Array<string> | undefined
let prerenderFallback: boolean | undefined
if (hasStaticProps && hasStaticPaths) { if (hasStaticProps && hasStaticPaths) {
prerenderRoutes = await buildStaticPaths( ;({
page, paths: prerenderRoutes,
mod.unstable_getStaticPaths fallback: prerenderFallback,
) } = await buildStaticPaths(page, mod.unstable_getStaticPaths))
} }
const config = mod.config || {} const config = mod.config || {}
...@@ -679,6 +689,7 @@ export async function isPageStatic( ...@@ -679,6 +689,7 @@ export async function isPageStatic(
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps, isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps,
isHybridAmp: config.amp === 'hybrid', isHybridAmp: config.amp === 'hybrid',
prerenderRoutes, prerenderRoutes,
prerenderFallback,
hasStaticProps, hasStaticProps,
hasServerProps, hasServerProps,
} }
......
...@@ -264,7 +264,7 @@ export default async function({ ...@@ -264,7 +264,7 @@ export default async function({
return results return results
} catch (error) { } catch (error) {
console.error( console.error(
`\nError occurred prerendering page "${path}" https://err.sh/next.js/prerender-error:\n` + `\nError occurred prerendering page "${path}". Read more: https://err.sh/next.js/prerender-error:\n` +
error error
) )
return { ...results, error: true } return { ...results, error: true }
......
...@@ -52,6 +52,7 @@ type Unstable_getStaticProps = (ctx: { ...@@ -52,6 +52,7 @@ type Unstable_getStaticProps = (ctx: {
export type Unstable_getStaticPaths = () => Promise<{ export type Unstable_getStaticPaths = () => Promise<{
paths: Array<string | { params: ParsedUrlQuery }> paths: Array<string | { params: ParsedUrlQuery }>
fallback: boolean
}> }>
type Unstable_getServerProps = (context: { type Unstable_getServerProps = (context: {
......
...@@ -6,6 +6,7 @@ import nanoid from 'next/dist/compiled/nanoid/index.js' ...@@ -6,6 +6,7 @@ import nanoid from 'next/dist/compiled/nanoid/index.js'
import { join, resolve, sep } from 'path' import { join, resolve, sep } from 'path'
import { parse as parseQs, ParsedUrlQuery } from 'querystring' import { parse as parseQs, ParsedUrlQuery } from 'querystring'
import { format as formatUrl, parse as parseUrl, UrlWithParsedQuery } from 'url' import { format as formatUrl, parse as parseUrl, UrlWithParsedQuery } from 'url'
import { PrerenderManifest } from '../../build'
import { import {
getRedirectStatus, getRedirectStatus,
Header, Header,
...@@ -292,15 +293,17 @@ export default class Server { ...@@ -292,15 +293,17 @@ export default class Server {
return require(join(this.distDir, ROUTES_MANIFEST)) return require(join(this.distDir, ROUTES_MANIFEST))
} }
private _cachedPreviewProps: __ApiPreviewProps | undefined private _cachedPreviewManifest: PrerenderManifest | undefined
protected getPreviewProps(): __ApiPreviewProps { protected getPrerenderManifest(): PrerenderManifest {
if (this._cachedPreviewProps) { if (this._cachedPreviewManifest) {
return this._cachedPreviewProps return this._cachedPreviewManifest
} }
return (this._cachedPreviewProps = require(join( const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
this.distDir, return (this._cachedPreviewManifest = manifest)
PRERENDER_MANIFEST }
)).preview)
protected getPreviewProps(): __ApiPreviewProps {
return this.getPrerenderManifest().preview
} }
protected generateRoutes(): { protected generateRoutes(): {
...@@ -870,7 +873,7 @@ export default class Server { ...@@ -870,7 +873,7 @@ export default class Server {
pathname: string, pathname: string,
{ components, query }: FindComponentsResult, { components, query }: FindComponentsResult,
opts: any opts: any
): Promise<string | null> { ): Promise<string | false | null> {
// we need to ensure the status code if /404 is visited directly // we need to ensure the status code if /404 is visited directly
if (pathname === '/404') { if (pathname === '/404') {
res.statusCode = 404 res.statusCode = 404
...@@ -1029,24 +1032,35 @@ export default class Server { ...@@ -1029,24 +1032,35 @@ export default class Server {
// we lazy load the staticPaths to prevent the user // we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode // from waiting on them for the page to load in dev mode
let staticPaths: string[] | undefined let staticPaths: string[] | undefined
let hasStaticFallback = false
if (!isProduction && hasStaticPaths) { if (hasStaticPaths) {
const __getStaticPaths = async () => { if (isProduction) {
const paths = await this.staticPathsWorker!.loadStaticPaths( // `staticPaths` is intentionally set to `undefined` as it should've
this.distDir, // been caught above when checking disk data.
this.buildId, staticPaths = undefined
pathname,
!this.renderOpts.dev && this._isLikeServerless // Read whether or not fallback should exist from the manifest.
) hasStaticFallback =
return paths typeof this.getPrerenderManifest().dynamicRoutes[pathname]
.fallback === 'string'
} else {
const __getStaticPaths = async () => {
const paths = await this.staticPathsWorker!.loadStaticPaths(
this.distDir,
this.buildId,
pathname,
!this.renderOpts.dev && this._isLikeServerless
)
return paths
}
;({ paths: staticPaths, fallback: hasStaticFallback } = (
await withCoalescedInvoke(__getStaticPaths)(
`staticPaths-${pathname}`,
[]
)
).value)
} }
staticPaths = (
await withCoalescedInvoke(__getStaticPaths)(
`staticPaths-${pathname}`,
[]
)
).value
} }
// const isForcedBlocking = // const isForcedBlocking =
...@@ -1074,6 +1088,16 @@ export default class Server { ...@@ -1074,6 +1088,16 @@ export default class Server {
// `getStaticPaths` // `getStaticPaths`
(isProduction || !staticPaths || !staticPaths.includes(urlPathname)) (isProduction || !staticPaths || !staticPaths.includes(urlPathname))
) { ) {
if (
// In development, fall through to render to handle missing
// getStaticPaths.
(isProduction || staticPaths) &&
// When fallback isn't present, abort this render so we 404
!hasStaticFallback
) {
return false
}
let html: string let html: string
// Production already emitted the fallback as static HTML. // Production already emitted the fallback as static HTML.
...@@ -1137,13 +1161,16 @@ export default class Server { ...@@ -1137,13 +1161,16 @@ export default class Server {
try { try {
const result = await this.findPageComponents(pathname, query) const result = await this.findPageComponents(pathname, query)
if (result) { if (result) {
return await this.renderToHTMLWithComponents( const result2 = await this.renderToHTMLWithComponents(
req, req,
res, res,
pathname, pathname,
result, result,
{ ...this.renderOpts, amphtml, hasAmp } { ...this.renderOpts, amphtml, hasAmp }
) )
if (result2 !== false) {
return result2
}
} }
if (this.dynamicRoutes) { if (this.dynamicRoutes) {
...@@ -1159,7 +1186,7 @@ export default class Server { ...@@ -1159,7 +1186,7 @@ export default class Server {
params params
) )
if (result) { if (result) {
return await this.renderToHTMLWithComponents( const result2 = await this.renderToHTMLWithComponents(
req, req,
res, res,
dynamicRoute.page, dynamicRoute.page,
...@@ -1171,6 +1198,9 @@ export default class Server { ...@@ -1171,6 +1198,9 @@ export default class Server {
hasAmp, hasAmp,
} }
) )
if (result2 !== false) {
return result2
}
} }
} }
} }
...@@ -1224,9 +1254,9 @@ export default class Server { ...@@ -1224,9 +1254,9 @@ export default class Server {
result = await this.findPageComponents('/_error', query) result = await this.findPageComponents('/_error', query)
} }
let html let html: string | null
try { try {
html = await this.renderToHTMLWithComponents( const result2 = await this.renderToHTMLWithComponents(
req, req,
res, res,
using404Page ? '/404' : '/_error', using404Page ? '/404' : '/_error',
...@@ -1236,6 +1266,10 @@ export default class Server { ...@@ -1236,6 +1266,10 @@ export default class Server {
err, err,
} }
) )
if (result2 === false) {
throw new Error('invariant: failed to render error page')
}
html = result2
} catch (err) { } catch (err) {
console.error(err) console.error(err)
res.statusCode = 500 res.statusCode = 500
......
...@@ -74,7 +74,7 @@ export function initializeSprCache({ ...@@ -74,7 +74,7 @@ export function initializeSprCache({
if (dev) { if (dev) {
prerenderManifest = { prerenderManifest = {
version: -1, version: -1 as any, // letting us know this doesn't conform to spec
routes: {}, routes: {},
dynamicRoutes: {}, dynamicRoutes: {},
preview: null as any, // `preview` is special case read in next-dev-server preview: null as any, // `preview` is special case read in next-dev-server
......
export async function unstable_getStaticPaths() { export async function unstable_getStaticPaths() {
return { paths: ['/hello', '/world'] } return { paths: ['/hello', '/world'], fallback: true }
} }
export default () => <p>something is missing 🤔</p> export default () => <p>something is missing 🤔</p>
...@@ -9,6 +9,7 @@ export function unstable_getStaticProps({ params }) { ...@@ -9,6 +9,7 @@ export function unstable_getStaticProps({ params }) {
export function unstable_getStaticPaths() { export function unstable_getStaticPaths() {
return { return {
paths: [], paths: [],
fallback: true,
} }
} }
......
...@@ -15,6 +15,7 @@ export function unstable_getStaticProps({ params }) { ...@@ -15,6 +15,7 @@ export function unstable_getStaticProps({ params }) {
export function unstable_getStaticPaths() { export function unstable_getStaticPaths() {
return { return {
paths: [], paths: [],
fallback: true,
} }
} }
......
...@@ -12,6 +12,7 @@ export function unstable_getStaticPaths() { ...@@ -12,6 +12,7 @@ export function unstable_getStaticPaths() {
`/p1/p2/predefined-ssg/one-level`, `/p1/p2/predefined-ssg/one-level`,
`/p1/p2/predefined-ssg/1st-level/2nd-level`, `/p1/p2/predefined-ssg/1st-level/2nd-level`,
], ],
fallback: true,
} }
} }
......
export const unstable_getStaticPaths = async () => { export const unstable_getStaticPaths = async () => {
return { return {
props: { world: 'world' } props: { world: 'world' }, fallback: true
} }
} }
......
...@@ -2,7 +2,7 @@ import React from 'react' ...@@ -2,7 +2,7 @@ import React from 'react'
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
export async function unstable_getStaticPaths() { export async function unstable_getStaticPaths() {
return { paths: [{ params: { slug: 'hello' } }] } return { paths: [{ params: { slug: 'hello' } }], fallback: true }
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
......
...@@ -2,7 +2,7 @@ import React from 'react' ...@@ -2,7 +2,7 @@ import React from 'react'
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
export async function unstable_getStaticPaths() { export async function unstable_getStaticPaths() {
return { paths: [{ foo: 'bad', baz: 'herro' }] } return { paths: [{ foo: 'bad', baz: 'herro' }], fallback: true }
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
......
...@@ -8,6 +8,7 @@ export async function unstable_getStaticPaths() { ...@@ -8,6 +8,7 @@ export async function unstable_getStaticPaths() {
'/blog/post-1/comment-1', '/blog/post-1/comment-1',
{ params: { post: 'post-2', comment: 'comment-2' } }, { params: { post: 'post-2', comment: 'comment-2' } },
], ],
fallback: true,
} }
} }
......
...@@ -13,6 +13,7 @@ export async function unstable_getStaticPaths() { ...@@ -13,6 +13,7 @@ export async function unstable_getStaticPaths() {
'/blog/post.1', '/blog/post.1',
'/blog/post.1', // handle duplicates '/blog/post.1', // handle duplicates
], ],
fallback: true,
} }
} }
......
export async function unstable_getStaticProps({ params: { slug } }) {
if (slug[0] === 'delayby3s') {
await new Promise(resolve => setTimeout(resolve, 3000))
}
return {
props: {
slug,
},
revalidate: 1,
}
}
export async function unstable_getStaticPaths() {
return {
paths: [
{ params: { slug: ['first'] } },
'/catchall-explicit/second',
{ params: { slug: ['another', 'value'] } },
'/catchall-explicit/hello/another',
],
fallback: false,
}
}
export default ({ slug }) => {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return <p id="catchall">Hi {slug.join(' ')}</p>
}
...@@ -21,6 +21,7 @@ export async function unstable_getStaticPaths() { ...@@ -21,6 +21,7 @@ export async function unstable_getStaticPaths() {
{ params: { slug: ['another', 'value'] } }, { params: { slug: ['another', 'value'] } },
'/catchall/hello/another', '/catchall/hello/another',
], ],
fallback: true,
} }
} }
......
...@@ -3,7 +3,7 @@ import Link from 'next/link' ...@@ -3,7 +3,7 @@ import Link from 'next/link'
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
export async function unstable_getStaticPaths() { export async function unstable_getStaticPaths() {
return { paths: [] } return { paths: [], fallback: true }
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
......
...@@ -92,6 +92,26 @@ const expectedManifestRoutes = () => ({ ...@@ -92,6 +92,26 @@ const expectedManifestRoutes = () => ({
initialRevalidateSeconds: 10, initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]', srcRoute: '/blog/[post]',
}, },
'/catchall-explicit/another/value': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/another/value.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/first': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/first.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/hello/another': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/hello/another.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/second': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/second.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/another': { '/another': {
dataRoute: `/_next/data/${buildId}/another.json`, dataRoute: `/_next/data/${buildId}/another.json`,
initialRevalidateSeconds: 1, initialRevalidateSeconds: 1,
...@@ -418,6 +438,49 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -418,6 +438,49 @@ const runTests = (dev = false, looseMode = false) => {
) )
}) })
it('should support prerendered catchall-explicit route (nested)', async () => {
const html = await renderViaHTTP(
appPort,
'/catchall-explicit/another/value'
)
const $ = cheerio.load(html)
expect(
JSON.parse(
cheerio
.load(html)('#__NEXT_DATA__')
.text()
).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?another value/)
})
it('should support prerendered catchall-explicit route (single)', async () => {
const html = await renderViaHTTP(appPort, '/catchall-explicit/second')
const $ = cheerio.load(html)
expect(
JSON.parse(
cheerio
.load(html)('#__NEXT_DATA__')
.text()
).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?second/)
})
if (!looseMode) {
it('should 404 for a missing catchall explicit route', async () => {
const res = await fetchViaHTTP(
appPort,
'/catchall-explicit/notreturnedinpaths'
)
expect(res.status).toBe(404)
const html = await res.text()
expect(html).toMatch(/This page could not be found/)
})
}
if (dev) { if (dev) {
// TODO: re-enable when this is supported in dev // TODO: re-enable when this is supported in dev
// it('should show error when rewriting to dynamic SSG page', async () => { // it('should show error when rewriting to dynamic SSG page', async () => {
...@@ -561,6 +624,36 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -561,6 +624,36 @@ const runTests = (dev = false, looseMode = false) => {
} }
}) })
it('should error on dynamic page without getStaticPaths returning fallback property', async () => {
const curPage = join(__dirname, '../pages/temp2/[slug].js')
await fs.mkdirp(dirname(curPage))
await fs.writeFile(
curPage,
`
export async function unstable_getStaticPaths() {
return {
paths: []
}
}
export async function unstable_getStaticProps() {
return {
props: {
hello: 'world'
}
}
}
export default () => 'oops'
`
)
await waitFor(1000)
try {
const html = await renderViaHTTP(appPort, '/temp2/hello')
expect(html).toMatch(/`fallback` key must be returned from/)
} finally {
await fs.remove(curPage)
}
})
it('should not re-call getStaticProps when updating query', async () => { it('should not re-call getStaticProps when updating query', async () => {
const browser = await webdriver(appPort, '/something?hello=world') const browser = await webdriver(appPort, '/something?hello=world')
await waitFor(2000) await waitFor(2000)
...@@ -641,6 +734,14 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -641,6 +734,14 @@ const runTests = (dev = false, looseMode = false) => {
), ),
page: '/catchall/[...slug]', page: '/catchall/[...slug]',
}, },
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/catchall\\-explicit\\/(.+?)\\.json$`
),
page: '/catchall-explicit/[...slug]',
},
{ {
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex( `^\\/_next\\/data\\/${escapeRegex(
...@@ -683,7 +784,7 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -683,7 +784,7 @@ const runTests = (dev = false, looseMode = false) => {
} }
}) })
expect(manifest.version).toBe(1) expect(manifest.version).toBe(2)
expect(manifest.routes).toEqual(expectedManifestRoutes()) expect(manifest.routes).toEqual(expectedManifestRoutes())
expect(manifest.dynamicRoutes).toEqual({ expect(manifest.dynamicRoutes).toEqual({
'/blog/[post]': { '/blog/[post]': {
...@@ -722,6 +823,16 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -722,6 +823,16 @@ const runTests = (dev = false, looseMode = false) => {
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\/(.+?)\\.json$` `^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\/(.+?)\\.json$`
), ),
}, },
'/catchall-explicit/[...slug]': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\-explicit\\/(.+?)\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/catchall\\-explicit\\/(.+?)(?:\\/)?$'
),
},
}) })
}) })
......
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