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
......@@ -142,6 +142,16 @@ const expectedManifestRoutes = () => ({
initialRevalidateSeconds: 1,
srcRoute: null,
},
'/blocking-fallback-some/a': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-some/a.json`,
initialRevalidateSeconds: 1,
srcRoute: '/blocking-fallback-some/[slug]',
},
'/blocking-fallback-some/b': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-some/b.json`,
initialRevalidateSeconds: 1,
srcRoute: '/blocking-fallback-some/[slug]',
},
'/blog': {
dataRoute: `/_next/data/${buildId}/blog.json`,
initialRevalidateSeconds: 10,
......@@ -418,6 +428,20 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
expect(html).toMatch(/Post:.*?post-1/)
})
it('should SSR blocking path correctly (blocking)', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback/random-path')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect($('p').text()).toBe('Post: random-path')
})
it('should SSR blocking path correctly (pre-rendered)', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback-some/a')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect($('p').text()).toBe('Post: a')
})
it('should have gsp in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
......@@ -729,6 +753,11 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
expect(html).toMatch(/About:.*?en/)
})
it("should allow rewriting to SSG page with fallback: 'blocking'", async () => {
const html = await renderViaHTTP(appPort, '/blocked-create')
expect(html).toMatch(/Post:.*?blocked-create/)
})
it('should fetch /_next/data correctly with mismatched href and as', async () => {
const browser = await webdriver(appPort, '/')
......@@ -825,6 +854,28 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should never show fallback for page not in getStaticPaths when blocking', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback-some/asf')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it still is
const html2 = await renderViaHTTP(appPort, '/blocking-fallback-some/asf')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should not show fallback for page in getStaticPaths when blocking', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback-some/b')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it's still not
const html2 = await renderViaHTTP(appPort, '/blocking-fallback-some/b')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should log error in console and browser in dev mode', async () => {
const origContent = await fs.readFile(indexPage, 'utf8')
......@@ -964,6 +1015,11 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
expect(html).toContain('"isFallback":true')
})
it('should not fallback before invalid JSON is returned from getStaticProps when blocking fallback', async () => {
const html = await renderViaHTTP(appPort, '/non-json-blocking/foobar')
expect(html).toContain('"isFallback":false')
})
it('should show error for invalid JSON returned from getStaticProps on SSR', async () => {
const browser = await webdriver(appPort, '/non-json/direct')
......@@ -1057,6 +1113,42 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
),
page: '/bad-ssr',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blocking\\-fallback/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blocking\\-fallback\\-once/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback-once/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blocking\\-fallback\\-some/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback-some/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/blog.json$`
......@@ -1204,6 +1296,20 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
p: 'p',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/non\\-json\\-blocking/(?<p>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`
),
page: '/non-json-blocking/[p]',
routeKeys: {
p: 'p',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/something.json$`
......@@ -1247,6 +1353,36 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
expect(manifest.version).toBe(2)
expect(manifest.routes).toEqual(expectedManifestRoutes())
expect(manifest.dynamicRoutes).toEqual({
'/blocking-fallback-once/[slug]': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-once/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\-once\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blocking-fallback-some/[slug]': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-some/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\-some\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blocking-fallback/[slug]': {
dataRoute: `/_next/data/${buildId}/blocking-fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blog/[post]': {
fallback: '/blog/[post].html',
dataRoute: `/_next/data/${buildId}/blog/[post].json`,
......@@ -1291,6 +1427,16 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
fallback: false,
routeRegex: normalizeRegEx('^\\/lang\\/([^\\/]+?)\\/about(?:\\/)?$'),
},
'/non-json-blocking/[p]': {
dataRoute: `/_next/data/${buildId}/non-json-blocking/[p].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/non\\-json\\-blocking\\/([^\\/]+?)(?:\\/)?$'
),
},
'/non-json/[p]': {
dataRoute: `/_next/data/${buildId}/non-json/[p].json`,
dataRouteRegex: normalizeRegEx(
......@@ -1386,6 +1532,20 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
})
if (!isEmulatedServerless) {
it('should not revalidate when set to false in blocking fallback mode', async () => {
const route = '/blocking-fallback-once/test-no-revalidate'
const initialHtml = await renderViaHTTP(appPort, route)
let newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
})
it('should handle revalidating HTML correctly', async () => {
const route = '/blog/post-2/comment-2'
const initialHtml = await renderViaHTTP(appPort, route)
......@@ -1423,6 +1583,80 @@ const runTests = (dev = false, isEmulatedServerless = false) => {
expect(newJson).toMatch(/post-2/)
expect(newJson).toMatch(/comment-3/)
})
it('should handle revalidating HTML correctly with blocking', async () => {
const route = '/blocking-fallback/pewpew'
const initialHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toMatch(/Post:.*?pewpew/)
let newHtml = await renderViaHTTP(appPort, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(appPort, route)
expect(newHtml === initialHtml).toBe(false)
expect(newHtml).toMatch(/Post:.*?pewpew/)
})
it('should handle revalidating JSON correctly with blocking', async () => {
const route = `/_next/data/${buildId}/blocking-fallback/pewpewdata.json`
const initialJson = await renderViaHTTP(appPort, route)
expect(initialJson).toMatch(/pewpewdata/)
let newJson = await renderViaHTTP(appPort, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(appPort, route)
expect(newJson === initialJson).toBe(false)
expect(newJson).toMatch(/pewpewdata/)
})
it('should handle revalidating HTML correctly with blocking and seed', async () => {
const route = '/blocking-fallback/a'
const initialHtml = await renderViaHTTP(appPort, route)
const $initial = cheerio.load(initialHtml)
expect($initial('p').text()).toBe('Post: a')
let newHtml = await renderViaHTTP(appPort, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(appPort, route)
expect(newHtml === initialHtml).toBe(false)
const $new = cheerio.load(newHtml)
expect($new('p').text()).toBe('Post: a')
})
it('should handle revalidating JSON correctly with blocking and seed', async () => {
const route = `/_next/data/${buildId}/blocking-fallback/b.json`
const initialJson = await renderViaHTTP(appPort, route)
expect(JSON.parse(initialJson)).toMatchObject({
pageProps: { params: { slug: 'b' } },
})
let newJson = await renderViaHTTP(appPort, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(appPort, route)
expect(newJson === initialJson).toBe(false)
expect(JSON.parse(newJson)).toMatchObject({
pageProps: { params: { slug: 'b' } },
})
})
}
it('should not fetch prerender data on mount', async () => {
......@@ -1487,6 +1721,10 @@ describe('SSG Prerender', () => {
{
source: '/about',
destination: '/lang/en/about'
},
{
source: '/blocked-create',
destination: '/blocking-fallback/blocked-create',
}
]
}
......@@ -1589,6 +1827,10 @@ describe('SSG Prerender', () => {
{
source: '/about',
destination: '/lang/en/about'
},
{
source: '/blocked-create',
destination: '/blocking-fallback/blocked-create',
}
]
}
......@@ -1768,10 +2010,17 @@ describe('SSG Prerender', () => {
'/blog/[post]/index.js',
'/fallback-only/[slug].js',
]
const fallbackBlockingPages = [
'/blocking-fallback/[slug].js',
'/blocking-fallback-once/[slug].js',
'/blocking-fallback-some/[slug].js',
'/non-json-blocking/[p].js',
]
const brokenPages = ['/bad-gssp.js', '/bad-ssr.js']
const fallbackTruePageContents = {}
const fallbackBlockingPageContents = {}
beforeAll(async () => {
exportDir = join(appDir, 'out')
......@@ -1802,6 +2051,18 @@ describe('SSG Prerender', () => {
)
}
for (const page of fallbackBlockingPages) {
const pagePath = join(appDir, 'pages', page)
fallbackBlockingPageContents[page] = await fs.readFile(pagePath, 'utf8')
await fs.writeFile(
pagePath,
fallbackBlockingPageContents[page].replace(
"fallback: 'unstable_blocking'",
'fallback: false'
)
)
}
for (const page of brokenPages) {
const pagePath = join(appDir, 'pages', page)
await fs.rename(pagePath, `${pagePath}.bak`)
......@@ -1819,10 +2080,14 @@ describe('SSG Prerender', () => {
for (const page of fallbackTruePages) {
const pagePath = join(appDir, 'pages', page)
await fs.writeFile(pagePath, fallbackTruePageContents[page])
}
for (const page of fallbackBlockingPages) {
const pagePath = join(appDir, 'pages', page)
await fs.writeFile(pagePath, fallbackBlockingPageContents[page])
}
for (const page of brokenPages) {
const pagePath = join(appDir, 'pages', page)
await fs.rename(`${pagePath}.bak`, pagePath)
......
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