Unverified Commit e8183899 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Add support for `fallback: 'blocking'` (#15672)

By popular request, this pull request adds support for returning `fallback: 'blocking'` from `getStaticPaths`.

This new mode will cause unknown paths to be rendered on-demand ("SSR") without the static (placeholder) fallback.

This feature is **currently experimental and should not be used in production yet**. It's currently flagged behind `unstable_`:

```
fallback: 'unstable_blocking'
```

TODO:

- [x] Next.js tests
- [ ] Add Vercel support
- [ ] Vercel tests

---

Fixes #15637
parent 668cc6a6
......@@ -87,7 +87,7 @@ export type SsgRoute = {
export type DynamicSsgRoute = {
routeRegex: string
fallback: string | false
fallback: string | null | false
dataRoute: string
dataRouteRegex: string
}
......@@ -443,7 +443,8 @@ export default async function build(
const buildManifestPath = path.join(distDir, BUILD_MANIFEST)
const ssgPages = new Set<string>()
const ssgFallbackPages = new Set<string>()
const ssgStaticFallbackPages = new Set<string>()
const ssgBlockingFallbackPages = new Set<string>()
const staticPages = new Set<string>()
const invalidPages = new Set<string>()
const hybridAmpPages = new Set<string>()
......@@ -498,7 +499,6 @@ export default async function build(
let isStatic = false
let isHybridAmp = false
let ssgPageRoutes: string[] | null = null
let hasSsgFallback: boolean = false
const nonReservedPage = !page.match(/^\/(_app|_error|_document|api)/)
......@@ -554,9 +554,11 @@ export default async function build(
additionalSsgPaths.set(page, workerResult.prerenderRoutes)
ssgPageRoutes = workerResult.prerenderRoutes
}
if (workerResult.prerenderFallback) {
hasSsgFallback = true
ssgFallbackPages.add(page)
if (workerResult.prerenderFallback === 'unstable_blocking') {
ssgBlockingFallbackPages.add(page)
} else if (workerResult.prerenderFallback === true) {
ssgStaticFallbackPages.add(page)
}
} else if (workerResult.hasServerProps) {
serverPropsPages.add(page)
......@@ -591,7 +593,6 @@ export default async function build(
isSsg,
isHybridAmp,
ssgPageRoutes,
hasSsgFallback,
initialRevalidateSeconds: false,
})
})
......@@ -706,7 +707,7 @@ export default async function build(
if (isDynamicRoute(page)) {
tbdPrerenderRoutes.push(page)
if (ssgFallbackPages.has(page)) {
if (ssgStaticFallbackPages.has(page)) {
// Override the rendering for the dynamic page to be treated as a
// fallback render.
defaultMap[page] = { page, query: { __nextFallback: true } }
......@@ -802,14 +803,14 @@ export default async function build(
for (const page of combinedPages) {
const isSsg = ssgPages.has(page)
const isSsgFallback = ssgFallbackPages.has(page)
const isStaticSsgFallback = ssgStaticFallbackPages.has(page)
const isDynamic = isDynamicRoute(page)
const hasAmp = hybridAmpPages.has(page)
const file = normalizePagePath(page)
// The dynamic version of SSG pages are only prerendered if the fallback
// is enabled. Below, we handle the specific prerenders of these.
if (!(isSsg && isDynamic && !isSsgFallback)) {
if (!(isSsg && isDynamic && !isStaticSsgFallback)) {
await moveExportedPage(page, page, file, isSsg, 'html')
}
......@@ -921,7 +922,9 @@ export default async function build(
finalDynamicRoutes[tbdRoute] = {
routeRegex: normalizeRouteRegex(getRouteRegex(tbdRoute).re.source),
dataRoute,
fallback: ssgFallbackPages.has(tbdRoute)
fallback: ssgBlockingFallbackPages.has(tbdRoute)
? null
: ssgStaticFallbackPages.has(tbdRoute)
? `${normalizedRoute}.html`
: false,
dataRouteRegex: normalizeRouteRegex(
......
......@@ -26,6 +26,7 @@ import { GetStaticPaths } from 'next/types'
import { denormalizePagePath } from '../next-server/server/normalize-page-path'
import { BuildManifest } from '../next-server/server/get-page-files'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import type { UnwrapPromise } from '../lib/coalesced-function'
const fileGzipStats: { [k: string]: Promise<number> } = {}
const fsStatGzip = (file: string) => {
......@@ -51,7 +52,6 @@ export interface PageInfo {
static: boolean
isSsg: boolean
ssgPageRoutes: string[] | null
hasSsgFallback: boolean
initialRevalidateSeconds: number | false
}
......@@ -531,7 +531,9 @@ export async function getJsPageSizeInKb(
export async function buildStaticPaths(
page: string,
getStaticPaths: GetStaticPaths
): Promise<{ paths: string[]; fallback: boolean }> {
): Promise<
Omit<UnwrapPromise<ReturnType<GetStaticPaths>>, 'paths'> & { paths: string[] }
> {
const prerenderPaths = new Set<string>()
const _routeRegex = getRouteRegex(page)
const _routeMatcher = getRouteMatcher(_routeRegex)
......@@ -567,7 +569,12 @@ export async function buildStaticPaths(
)
}
if (typeof staticPathsResult.fallback !== 'boolean') {
if (
!(
typeof staticPathsResult.fallback === 'boolean' ||
staticPathsResult.fallback === 'unstable_blocking'
)
) {
throw new Error(
`The \`fallback\` key must be returned from getStaticPaths in ${page}.\n` +
expectedReturnVal
......@@ -668,7 +675,7 @@ export async function isPageStatic(
hasServerProps?: boolean
hasStaticProps?: boolean
prerenderRoutes?: string[] | undefined
prerenderFallback?: boolean | undefined
prerenderFallback?: boolean | 'unstable_blocking' | undefined
}> {
try {
require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig)
......@@ -743,7 +750,7 @@ export async function isPageStatic(
}
let prerenderRoutes: Array<string> | undefined
let prerenderFallback: boolean | undefined
let prerenderFallback: boolean | 'unstable_blocking' | undefined
if (hasStaticProps && hasStaticPaths) {
;({
paths: prerenderRoutes,
......
......@@ -306,7 +306,7 @@ export default async function exportApp(
}
if (prerenderManifest && !options.buildExport) {
const fallbackTruePages = new Set()
const fallbackEnabledPages = new Set()
for (const key of Object.keys(prerenderManifest.dynamicRoutes)) {
// only error if page is included in path map
......@@ -315,15 +315,15 @@ export default async function exportApp(
}
if (prerenderManifest.dynamicRoutes[key].fallback !== false) {
fallbackTruePages.add(key)
fallbackEnabledPages.add(key)
}
}
if (fallbackTruePages.size) {
if (fallbackEnabledPages.size) {
throw new Error(
`Found pages with \`fallback: true\`:\n${[...fallbackTruePages].join(
'\n'
)}\n${SSG_FALLBACK_EXPORT_ERROR}\n`
`Found pages with \`fallback\` enabled:\n${[
...fallbackEnabledPages,
].join('\n')}\n${SSG_FALLBACK_EXPORT_ERROR}\n`
)
}
}
......
......@@ -47,4 +47,4 @@ export const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's comp
export const NON_STANDARD_NODE_ENV = `You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://err.sh/next.js/non-standard-node-env`
export const SSG_FALLBACK_EXPORT_ERROR = `Pages with \`fallback: true\` in \`getStaticPaths\` can not be exported. See more info here: https://err.sh/next.js/ssg-fallback-true-export`
export const SSG_FALLBACK_EXPORT_ERROR = `Pages with \`fallback\` enabled in \`getStaticPaths\` can not be exported. See more info here: https://err.sh/next.js/ssg-fallback-true-export`
......@@ -937,18 +937,25 @@ export default class Server {
pathname: string
): Promise<{
staticPaths: string[] | undefined
hasStaticFallback: boolean
fallbackMode: 'static' | 'blocking' | false
}> {
// `staticPaths` is intentionally set to `undefined` as it should've
// been caught when checking disk data.
const staticPaths = undefined
// Read whether or not fallback should exist from the manifest.
const hasStaticFallback =
typeof this.getPrerenderManifest().dynamicRoutes[pathname].fallback ===
'string'
const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname]
.fallback
return { staticPaths, hasStaticFallback }
return {
staticPaths,
fallbackMode:
typeof fallbackField === 'string'
? 'static'
: fallbackField === null
? 'blocking'
: false,
}
}
private async renderToHTMLWithComponents(
......@@ -1113,15 +1120,17 @@ export default class Server {
const isDynamicPathname = isDynamicRoute(pathname)
const didRespond = isResSent(res)
const { staticPaths, hasStaticFallback } = hasStaticPaths
const { staticPaths, fallbackMode } = hasStaticPaths
? await this.getStaticPaths(pathname)
: { staticPaths: undefined, hasStaticFallback: false }
: { staticPaths: undefined, fallbackMode: false }
// When we did not respond from cache, we need to choose to block on
// rendering or return a skeleton.
//
// * Data requests always block.
//
// * Blocking mode fallback always blocks.
//
// * Preview mode toggles all pages to be resolved in a blocking manner.
//
// * Non-dynamic pages should block (though this is an impossible
......@@ -1131,6 +1140,7 @@ export default class Server {
// getStaticPaths, then finish the data request on the client-side.
//
if (
fallbackMode !== 'blocking' &&
ssgCacheKey &&
!didRespond &&
!isDataReq &&
......@@ -1145,7 +1155,7 @@ export default class Server {
// getStaticPaths.
(isProduction || staticPaths) &&
// When fallback isn't present, abort this render so we 404
!hasStaticFallback
fallbackMode !== 'static'
) {
throw new NoFallbackError()
}
......
......@@ -476,7 +476,7 @@ export default class DevServer extends Server {
pathname: string
): Promise<{
staticPaths: string[] | undefined
hasStaticFallback: boolean
fallbackMode: false | 'static' | 'blocking'
}> {
// we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode
......@@ -489,11 +489,19 @@ export default class DevServer extends Server {
)
return paths
}
const { paths: staticPaths, fallback: hasStaticFallback } = (
const { paths: staticPaths, fallback } = (
await withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, [])
).value
return { staticPaths, hasStaticFallback }
return {
staticPaths,
fallbackMode:
fallback === 'unstable_blocking'
? 'blocking'
: fallback === true
? 'static'
: false,
}
}
protected async ensureApiPage(pathname: string) {
......
......@@ -100,7 +100,7 @@ export type GetStaticPaths<
P extends ParsedUrlQuery = ParsedUrlQuery
> = () => Promise<{
paths: Array<string | { params: P }>
fallback: boolean
fallback: boolean | 'unstable_blocking'
}>
export type GetServerSidePropsContext<
......
......@@ -17,9 +17,9 @@ describe('Export error for fallback: true', () => {
it('should have error during next export', async () => {
const { stderr } = await nextExport(appDir, { outdir }, { stderr: true })
expect(stderr).toContain('Found pages with `fallback: true`')
expect(stderr).toContain('Found pages with `fallback` enabled')
expect(stderr).toContain(
'Pages with `fallback: true` in `getStaticPaths` can not be exported'
'Pages with `fallback` enabled in `getStaticPaths` can not be exported'
)
expect(stderr).toContain('/[slug]')
})
......
......@@ -5,6 +5,10 @@ module.exports = {
source: '/about',
destination: '/lang/en/about',
},
{
source: '/blocked-create',
destination: '/blocking-fallback/blocked-create',
},
]
},
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: 'unstable_blocking',
}
}
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(),
},
revalidate: false,
}
}
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>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [{ params: { slug: 'a' } }, { params: { slug: 'b' } }],
fallback: 'unstable_blocking',
}
}
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(),
},
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>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: 'unstable_blocking',
}
}
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(),
},
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>
</>
)
}
import { useRouter } from 'next/router'
export async function getStaticProps() {
return {
props: { time: new Date() },
}
}
export async function getStaticPaths() {
return { paths: [], fallback: 'unstable_blocking' }
}
const Page = ({ time }) => {
const { isFallback } = useRouter()
if (isFallback) return null
return <p>hello blocking {time.toString()}</p>
}
export default Page
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