Unverified Commit 69388a52 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Partial Prerendering (#57287)

This PR introduces a build optimization to create a "partial prerender" of the page.

1. During compilation, we create a static shell for the page using your existing Suspense boundaries. Components that can be static will be included in this static shell, leaving holes for the dynamic components.
1. Using `<Suspense />`, we can define fallbacks to be included in the partial prerender, as well as the holes for the dynamic components to stream into.

This means Next.js can initially serve a static loading skeleton, kicking off the dynamic parts in parallel. Then, the dynamic components stream in on demand. Dynamic components can use `cookies()`, `headers()`, `'cache': 'no-store'`, or `unstable_noStore()` to opt-into dynamic rendering.
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 679a398e
...@@ -748,6 +748,11 @@ impl NextConfig { ...@@ -748,6 +748,11 @@ impl NextConfig {
self.await?.experimental.server_actions.unwrap_or(false), self.await?.experimental.server_actions.unwrap_or(false),
)) ))
} }
#[turbo_tasks::function]
pub async fn enable_ppr(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(self.await?.experimental.ppr.unwrap_or(false)))
}
} }
fn next_configs() -> Vc<Vec<String>> { fn next_configs() -> Vc<Vec<String>> {
......
...@@ -92,7 +92,9 @@ pub async fn get_next_client_import_map( ...@@ -92,7 +92,9 @@ pub async fn get_next_client_import_map(
); );
} }
ClientContextType::App { app_dir } => { ClientContextType::App { app_dir } => {
let react_flavor = if *next_config.enable_server_actions().await? { let react_flavor = if *next_config.enable_server_actions().await?
|| *next_config.enable_ppr().await?
{
"-experimental" "-experimental"
} else { } else {
"" ""
...@@ -119,6 +121,27 @@ pub async fn get_next_client_import_map( ...@@ -119,6 +121,27 @@ pub async fn get_next_client_import_map(
&format!("next/dist/compiled/react-dom{react_flavor}"), &format!("next/dist/compiled/react-dom{react_flavor}"),
), ),
); );
import_map.insert_exact_alias(
"react-dom/static",
request_to_import_mapping(
app_dir,
"next/dist/compiled/react-dom-experimental/static",
),
);
import_map.insert_exact_alias(
"react-dom/static.edge",
request_to_import_mapping(
app_dir,
"next/dist/compiled/react-dom-experimental/static.edge",
),
);
import_map.insert_exact_alias(
"react-dom/static.browser",
request_to_import_mapping(
app_dir,
"next/dist/compiled/react-dom-experimental/static.browser",
),
);
import_map.insert_wildcard_alias( import_map.insert_wildcard_alias(
"react-dom/", "react-dom/",
request_to_import_mapping( request_to_import_mapping(
...@@ -622,7 +645,12 @@ async fn rsc_aliases( ...@@ -622,7 +645,12 @@ async fn rsc_aliases(
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
) -> Result<()> { ) -> Result<()> {
let server_actions = *next_config.enable_server_actions().await?; let server_actions = *next_config.enable_server_actions().await?;
let react_channel = if server_actions { "-experimental" } else { "" }; let ppr = *next_config.enable_ppr().await?;
let react_channel = if server_actions || ppr {
"-experimental"
} else {
""
};
let mut alias = indexmap! { let mut alias = indexmap! {
"react" => format!("next/dist/compiled/react{react_channel}"), "react" => format!("next/dist/compiled/react{react_channel}"),
...@@ -630,6 +658,9 @@ async fn rsc_aliases( ...@@ -630,6 +658,9 @@ async fn rsc_aliases(
"react/jsx-runtime" => format!("next/dist/compiled/react{react_channel}/jsx-runtime"), "react/jsx-runtime" => format!("next/dist/compiled/react{react_channel}/jsx-runtime"),
"react/jsx-dev-runtime" => format!("next/dist/compiled/react{react_channel}/jsx-dev-runtime"), "react/jsx-dev-runtime" => format!("next/dist/compiled/react{react_channel}/jsx-dev-runtime"),
"react-dom/client" => format!("next/dist/compiled/react-dom{react_channel}/client"), "react-dom/client" => format!("next/dist/compiled/react-dom{react_channel}/client"),
"react-dom/static" => format!("next/dist/compiled/react-dom-experimental/static"),
"react-dom/static.edge" => format!("next/dist/compiled/react-dom-experimental/static.edge"),
"react-dom/static.browser" => format!("next/dist/compiled/react-dom-experimental/static.browser"),
"react-dom/server" => format!("next/dist/compiled/react-dom{react_channel}/server"), "react-dom/server" => format!("next/dist/compiled/react-dom{react_channel}/server"),
"react-dom/server.edge" => format!("next/dist/compiled/react-dom{react_channel}/server.edge"), "react-dom/server.edge" => format!("next/dist/compiled/react-dom{react_channel}/server.edge"),
"react-dom/server.browser" => format!("next/dist/compiled/react-dom{react_channel}/server.browser"), "react-dom/server.browser" => format!("next/dist/compiled/react-dom{react_channel}/server.browser"),
......
...@@ -251,6 +251,9 @@ export function createRSCAliases( ...@@ -251,6 +251,9 @@ export function createRSCAliases(
'react/jsx-dev-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`, 'react/jsx-dev-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`,
'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`, 'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`,
'react-dom/server$': `next/dist/compiled/react-dom${bundledReactChannel}/server`, 'react-dom/server$': `next/dist/compiled/react-dom${bundledReactChannel}/server`,
'react-dom/static$': `next/dist/compiled/react-dom-experimental/static`,
'react-dom/static.edge$': `next/dist/compiled/react-dom-experimental/static.edge`,
'react-dom/static.browser$': `next/dist/compiled/react-dom-experimental/static.browser`,
'react-dom/server.edge$': `next/dist/compiled/react-dom${bundledReactChannel}/server.edge`, 'react-dom/server.edge$': `next/dist/compiled/react-dom${bundledReactChannel}/server.edge`,
'react-dom/server.browser$': `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`, 'react-dom/server.browser$': `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`,
'react-server-dom-webpack/client$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`, 'react-server-dom-webpack/client$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`,
......
...@@ -1372,6 +1372,7 @@ export default async function build( ...@@ -1372,6 +1372,7 @@ export default async function build(
locales: config.i18n?.locales, locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output, nextConfigOutput: config.output,
ppr: config.experimental.ppr === true,
}) })
) )
...@@ -1459,7 +1460,7 @@ export default async function build( ...@@ -1459,7 +1460,7 @@ export default async function build(
}) })
return checkPageSpan.traceAsyncFn(async () => { return checkPageSpan.traceAsyncFn(async () => {
const actualPage = normalizePagePath(page) const actualPage = normalizePagePath(page)
const [selfSize, allSize] = await getJsPageSizeInKb( const [size, totalSize] = await getJsPageSizeInKb(
pageType, pageType,
actualPage, actualPage,
distDir, distDir,
...@@ -1469,7 +1470,8 @@ export default async function build( ...@@ -1469,7 +1470,8 @@ export default async function build(
computedManifestData computedManifestData
) )
let isSsg = false let isPPR = false
let isSSG = false
let isStatic = false let isStatic = false
let isServerComponent = false let isServerComponent = false
let isHybridAmp = false let isHybridAmp = false
...@@ -1579,6 +1581,7 @@ export default async function build( ...@@ -1579,6 +1581,7 @@ export default async function build(
maxMemoryCacheSize: maxMemoryCacheSize:
config.experimental.isrMemoryCacheSize, config.experimental.isrMemoryCacheSize,
nextConfigOutput: config.output, nextConfigOutput: config.output,
ppr: config.experimental.ppr === true,
}) })
} }
) )
...@@ -1588,12 +1591,21 @@ export default async function build( ...@@ -1588,12 +1591,21 @@ export default async function build(
// TODO-APP: handle prerendering with edge // TODO-APP: handle prerendering with edge
if (isEdgeRuntime(pageRuntime)) { if (isEdgeRuntime(pageRuntime)) {
isStatic = false isStatic = false
isSsg = false isSSG = false
Log.warnOnce( Log.warnOnce(
`Using edge runtime on a page currently disables static generation for that page` `Using edge runtime on a page currently disables static generation for that page`
) )
} else { } else {
// If this route can be partially pre-rendered, then
// mark it as such and mark it that it can be
// generated server-side.
if (workerResult.isPPR) {
isPPR = workerResult.isPPR
isSSG = true
isStatic = true
}
if ( if (
workerResult.encodedPrerenderRoutes && workerResult.encodedPrerenderRoutes &&
workerResult.prerenderRoutes workerResult.prerenderRoutes
...@@ -1607,7 +1619,7 @@ export default async function build( ...@@ -1607,7 +1619,7 @@ export default async function build(
workerResult.encodedPrerenderRoutes workerResult.encodedPrerenderRoutes
) )
ssgPageRoutes = workerResult.prerenderRoutes ssgPageRoutes = workerResult.prerenderRoutes
isSsg = true isSSG = true
} }
const appConfig = workerResult.appConfig || {} const appConfig = workerResult.appConfig || {}
...@@ -1694,7 +1706,7 @@ export default async function build( ...@@ -1694,7 +1706,7 @@ export default async function build(
if (workerResult.hasStaticProps) { if (workerResult.hasStaticProps) {
ssgPages.add(page) ssgPages.add(page)
isSsg = true isSSG = true
if ( if (
workerResult.prerenderRoutes && workerResult.prerenderRoutes &&
...@@ -1729,7 +1741,7 @@ export default async function build( ...@@ -1729,7 +1741,7 @@ export default async function build(
// This is a static server component page that doesn't have // This is a static server component page that doesn't have
// gSP or gSSP. We still treat it as a SSG page. // gSP or gSSP. We still treat it as a SSG page.
ssgPages.add(page) ssgPages.add(page)
isSsg = true isSSG = true
} }
if (hasPages404 && page === '/404') { if (hasPages404 && page === '/404') {
...@@ -1772,7 +1784,7 @@ export default async function build( ...@@ -1772,7 +1784,7 @@ export default async function build(
} }
if (pageType === 'app') { if (pageType === 'app') {
if (isSsg || isStatic) { if (isSSG || isStatic) {
staticAppPagesCount++ staticAppPagesCount++
} else { } else {
serverAppPagesCount++ serverAppPagesCount++
...@@ -1781,10 +1793,11 @@ export default async function build( ...@@ -1781,10 +1793,11 @@ export default async function build(
} }
pageInfos.set(page, { pageInfos.set(page, {
size: selfSize, size,
totalSize: allSize, totalSize,
static: isStatic, isStatic,
isSsg, isSSG,
isPPR,
isHybridAmp, isHybridAmp,
ssgPageRoutes, ssgPageRoutes,
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
...@@ -2191,14 +2204,13 @@ export default async function build( ...@@ -2191,14 +2204,13 @@ export default async function build(
appConfig.revalidate === 0 || appConfig.revalidate === 0 ||
exportResult.byPath.get(page)?.revalidate === 0 exportResult.byPath.get(page)?.revalidate === 0
// TODO: (wyattjoh) maybe change behavior for postpone? if (hasDynamicData && pageInfos.get(page)?.isStatic) {
if (hasDynamicData && pageInfos.get(page)?.static) {
// if the page was marked as being static, but it contains dynamic data // if the page was marked as being static, but it contains dynamic data
// (ie, in the case of a static generation bailout), then it should be marked dynamic // (ie, in the case of a static generation bailout), then it should be marked dynamic
pageInfos.set(page, { pageInfos.set(page, {
...(pageInfos.get(page) as PageInfo), ...(pageInfos.get(page) as PageInfo),
static: false, isStatic: false,
isSsg: false, isSSG: false,
}) })
} }
...@@ -2274,8 +2286,8 @@ export default async function build( ...@@ -2274,8 +2286,8 @@ export default async function build(
// used dynamic data // used dynamic data
pageInfos.set(route, { pageInfos.set(route, {
...(pageInfos.get(route) as PageInfo), ...(pageInfos.get(route) as PageInfo),
isSsg: false, isSSG: false,
static: false, isStatic: false,
}) })
} }
}) })
......
import type { NextConfig, NextConfigComplete } from '../server/config-shared' import type { NextConfig, NextConfigComplete } from '../server/config-shared'
import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin' import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import type { AssetBinding } from './webpack/loaders/get-module-build-info' import type { AssetBinding } from './webpack/loaders/get-module-build-info'
import type { GetStaticPaths, PageConfig, ServerRuntime } from 'next/types' import type {
GetStaticPaths,
GetStaticPathsResult,
PageConfig,
ServerRuntime,
} from 'next/types'
import type { BuildManifest } from '../server/get-page-files' import type { BuildManifest } from '../server/get-page-files'
import type { import type {
Redirect, Redirect,
...@@ -9,13 +14,13 @@ import type { ...@@ -9,13 +14,13 @@ import type {
Header, Header,
CustomRoutes, CustomRoutes,
} from '../lib/load-custom-routes' } from '../lib/load-custom-routes'
import type { UnwrapPromise } from '../lib/coalesced-function'
import type { import type {
EdgeFunctionDefinition, EdgeFunctionDefinition,
MiddlewareManifest, MiddlewareManifest,
} from './webpack/plugins/middleware-plugin' } from './webpack/plugins/middleware-plugin'
import type { WebpackLayerName } from '../lib/constants' import type { WebpackLayerName } from '../lib/constants'
import type { AppPageModule } from '../server/future/route-modules/app-page/module' import type { AppPageModule } from '../server/future/route-modules/app-page/module'
import type { RouteModule } from '../server/future/route-modules/route-module'
import '../server/require-hook' import '../server/require-hook'
import '../server/node-polyfill-crypto' import '../server/node-polyfill-crypto'
...@@ -65,6 +70,7 @@ import * as ciEnvironment from '../telemetry/ci-info' ...@@ -65,6 +70,7 @@ import * as ciEnvironment from '../telemetry/ci-info'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { denormalizeAppPagePath } from '../shared/lib/page-path/denormalize-app-path' import { denormalizeAppPagePath } from '../shared/lib/page-path/denormalize-app-path'
import { AppRouteRouteModule } from '../server/future/route-modules/app-route/module.compiled' import { AppRouteRouteModule } from '../server/future/route-modules/app-route/module.compiled'
import { RouteKind } from '../server/future/route-kind'
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
...@@ -323,8 +329,9 @@ export interface PageInfo { ...@@ -323,8 +329,9 @@ export interface PageInfo {
isHybridAmp?: boolean isHybridAmp?: boolean
size: number size: number
totalSize: number totalSize: number
static: boolean isStatic: boolean
isSsg: boolean isSSG: boolean
isPPR: boolean
ssgPageRoutes: string[] | null ssgPageRoutes: string[] | null
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
pageDuration: number | undefined pageDuration: number | undefined
...@@ -335,7 +342,7 @@ export interface PageInfo { ...@@ -335,7 +342,7 @@ export interface PageInfo {
export async function printTreeView( export async function printTreeView(
lists: { lists: {
pages: ReadonlyArray<string> pages: ReadonlyArray<string>
app?: ReadonlyArray<string> app: ReadonlyArray<string> | undefined
}, },
pageInfos: Map<string, PageInfo>, pageInfos: Map<string, PageInfo>,
{ {
...@@ -446,12 +453,14 @@ export async function printTreeView( ...@@ -446,12 +453,14 @@ export async function printTreeView(
const symbol = const symbol =
item === '/_app' || item === '/_app.server' item === '/_app' || item === '/_app.server'
? ' ' ? ' '
: pageInfo?.static
? '○'
: pageInfo?.isSsg
? '●'
: isEdgeRuntime(pageInfo?.runtime) : isEdgeRuntime(pageInfo?.runtime)
? 'ℇ' ? 'ℇ'
: pageInfo?.isPPR
? '◐'
: pageInfo?.isStatic
? '○'
: pageInfo?.isSSG
? '●'
: 'λ' : 'λ'
usedSymbols.add(symbol) usedSymbols.add(symbol)
...@@ -620,9 +629,9 @@ export async function printTreeView( ...@@ -620,9 +629,9 @@ export async function printTreeView(
} }
pageInfos.set('/404', { pageInfos.set('/404', {
...(pageInfos.get('/404') || pageInfos.get('/_error')), ...(pageInfos.get('/404') || pageInfos.get('/_error'))!,
static: useStaticPages404, isStatic: useStaticPages404,
} as any) })
// If there's no app /_notFound page present, then the 404 is still using the pages/404 // If there's no app /_notFound page present, then the 404 is still using the pages/404
if (!lists.pages.includes('/404') && !lists.app?.includes('/_not-found')) { if (!lists.pages.includes('/404') && !lists.app?.includes('/_not-found')) {
...@@ -658,6 +667,11 @@ export async function printTreeView( ...@@ -658,6 +667,11 @@ export async function printTreeView(
print( print(
textTable( textTable(
[ [
usedSymbols.has('◐') && [
'◐',
'(Partially Pre-Rendered)',
'static parts of the page were pre-rendered and the dynamic parts will be streamed',
],
usedSymbols.has('ℇ') && [ usedSymbols.has('ℇ') && [
'ℇ', 'ℇ',
'(Streaming)', '(Streaming)',
...@@ -876,13 +890,13 @@ export async function buildStaticPaths({ ...@@ -876,13 +890,13 @@ export async function buildStaticPaths({
}: { }: {
page: string page: string
getStaticPaths?: GetStaticPaths getStaticPaths?: GetStaticPaths
staticPathsResult?: UnwrapPromise<ReturnType<GetStaticPaths>> staticPathsResult?: GetStaticPathsResult
configFileName: string configFileName: string
locales?: string[] locales?: string[]
defaultLocale?: string defaultLocale?: string
appDir?: boolean appDir?: boolean
}): Promise< }): Promise<
Omit<UnwrapPromise<ReturnType<GetStaticPaths>>, 'paths'> & { Omit<GetStaticPathsResult, 'paths'> & {
paths: string[] paths: string[]
encodedPaths: string[] encodedPaths: string[]
} }
...@@ -1208,6 +1222,7 @@ export async function buildAppStaticPaths({ ...@@ -1208,6 +1222,7 @@ export async function buildAppStaticPaths({
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
staticGenerationAsyncStorage, staticGenerationAsyncStorage,
serverHooks, serverHooks,
ppr,
}: { }: {
page: string page: string
configFileName: string configFileName: string
...@@ -1222,6 +1237,7 @@ export async function buildAppStaticPaths({ ...@@ -1222,6 +1237,7 @@ export async function buildAppStaticPaths({
typeof patchFetch typeof patchFetch
>[0]['staticGenerationAsyncStorage'] >[0]['staticGenerationAsyncStorage']
serverHooks: Parameters<typeof patchFetch>[0]['serverHooks'] serverHooks: Parameters<typeof patchFetch>[0]['serverHooks']
ppr: boolean
}) { }) {
patchFetch({ patchFetch({
staticGenerationAsyncStorage, staticGenerationAsyncStorage,
...@@ -1265,6 +1281,7 @@ export async function buildAppStaticPaths({ ...@@ -1265,6 +1281,7 @@ export async function buildAppStaticPaths({
supportsDynamicHTML: true, supportsDynamicHTML: true,
isRevalidate: false, isRevalidate: false,
isBot: false, isBot: false,
ppr,
}, },
}, },
async () => { async () => {
...@@ -1372,6 +1389,7 @@ export async function isPageStatic({ ...@@ -1372,6 +1389,7 @@ export async function isPageStatic({
isrFlushToDisk, isrFlushToDisk,
maxMemoryCacheSize, maxMemoryCacheSize,
incrementalCacheHandlerPath, incrementalCacheHandlerPath,
ppr,
}: { }: {
page: string page: string
distDir: string distDir: string
...@@ -1389,7 +1407,9 @@ export async function isPageStatic({ ...@@ -1389,7 +1407,9 @@ export async function isPageStatic({
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
incrementalCacheHandlerPath?: string incrementalCacheHandlerPath?: string
nextConfigOutput: 'standalone' | 'export' nextConfigOutput: 'standalone' | 'export'
ppr: boolean
}): Promise<{ }): Promise<{
isPPR?: boolean
isStatic?: boolean isStatic?: boolean
isAmpOnly?: boolean isAmpOnly?: boolean
isHybridAmp?: boolean isHybridAmp?: boolean
...@@ -1458,17 +1478,17 @@ export async function isPageStatic({ ...@@ -1458,17 +1478,17 @@ export async function isPageStatic({
}) })
} }
const Comp = componentsResult.Component || {} const Comp = componentsResult.Component || {}
let staticPathsResult: let staticPathsResult: GetStaticPathsResult | undefined
| UnwrapPromise<ReturnType<GetStaticPaths>>
| undefined const routeModule: RouteModule =
componentsResult.ComponentMod?.routeModule
if (pageType === 'app') { if (pageType === 'app') {
const ComponentMod: AppPageModule = componentsResult.ComponentMod const ComponentMod: AppPageModule = componentsResult.ComponentMod
isClientComponent = isClientReference(componentsResult.ComponentMod) isClientComponent = isClientReference(componentsResult.ComponentMod)
const { tree, staticGenerationAsyncStorage, serverHooks, routeModule } = const { tree, staticGenerationAsyncStorage, serverHooks } = ComponentMod
ComponentMod
const generateParams: GenerateParams = const generateParams: GenerateParams =
routeModule && AppRouteRouteModule.is(routeModule) routeModule && AppRouteRouteModule.is(routeModule)
...@@ -1550,6 +1570,7 @@ export async function isPageStatic({ ...@@ -1550,6 +1570,7 @@ export async function isPageStatic({
isrFlushToDisk, isrFlushToDisk,
maxMemoryCacheSize, maxMemoryCacheSize,
incrementalCacheHandlerPath, incrementalCacheHandlerPath,
ppr,
})) }))
} }
} else { } else {
...@@ -1619,8 +1640,22 @@ export async function isPageStatic({ ...@@ -1619,8 +1640,22 @@ export async function isPageStatic({
) )
} }
let isStatic = false
if (!hasStaticProps && !hasGetInitialProps && !hasServerProps) {
isStatic = true
}
// When PPR is enabled, any route may contain or be completely static, so
// mark this route as static.
let isPPR = false
if (ppr && routeModule.definition.kind === RouteKind.APP_PAGE) {
isPPR = true
isStatic = true
}
return { return {
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps, isStatic,
isPPR,
isHybridAmp: config.amp === 'hybrid', isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true, isAmpOnly: config.amp === true,
prerenderRoutes, prerenderRoutes,
......
...@@ -28,10 +28,12 @@ import { urlToUrlWithoutFlightMarker } from '../app-router' ...@@ -28,10 +28,12 @@ import { urlToUrlWithoutFlightMarker } from '../app-router'
import { callServer } from '../../app-call-server' import { callServer } from '../../app-call-server'
import { PrefetchKind } from './router-reducer-types' import { PrefetchKind } from './router-reducer-types'
import { hexHash } from '../../../shared/lib/hash' import { hexHash } from '../../../shared/lib/hash'
import { NEXT_DID_POSTPONE_HEADER } from '../../../lib/constants'
export type FetchServerResponseResult = [ export type FetchServerResponseResult = [
flightData: FlightData, flightData: FlightData,
canonicalUrlOverride: URL | undefined canonicalUrlOverride: URL | undefined,
postponed?: boolean
] ]
function doMpaNavigation(url: string): FetchServerResponseResult { function doMpaNavigation(url: string): FetchServerResponseResult {
...@@ -109,6 +111,7 @@ export async function fetchServerResponse( ...@@ -109,6 +111,7 @@ export async function fetchServerResponse(
const canonicalUrl = res.redirected ? responseUrl : undefined const canonicalUrl = res.redirected ? responseUrl : undefined
const contentType = res.headers.get('content-type') || '' const contentType = res.headers.get('content-type') || ''
const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)
let isFlightResponse = contentType === RSC_CONTENT_TYPE_HEADER let isFlightResponse = contentType === RSC_CONTENT_TYPE_HEADER
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
...@@ -142,7 +145,7 @@ export async function fetchServerResponse( ...@@ -142,7 +145,7 @@ export async function fetchServerResponse(
return doMpaNavigation(res.url) return doMpaNavigation(res.url)
} }
return [flightData, canonicalUrl] return [flightData, canonicalUrl, postponed]
} catch (err) { } catch (err) {
console.error( console.error(
`Failed to fetch RSC payload for ${url}. Falling back to browser navigation.`, `Failed to fetch RSC payload for ${url}. Falling back to browser navigation.`,
......
...@@ -249,7 +249,7 @@ export function navigateReducer( ...@@ -249,7 +249,7 @@ export function navigateReducer(
prefetchQueue.bump(data!) prefetchQueue.bump(data!)
// Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves. // Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.
const [flightData, canonicalUrlOverride] = readRecordValue(data!) const [flightData, canonicalUrlOverride, postponed] = readRecordValue(data!)
// we only want to mark this once // we only want to mark this once
if (!prefetchValues.lastUsedTime) { if (!prefetchValues.lastUsedTime) {
...@@ -300,13 +300,17 @@ export function navigateReducer( ...@@ -300,13 +300,17 @@ export function navigateReducer(
return handleExternalUrl(state, mutable, href, pendingPush) return handleExternalUrl(state, mutable, href, pendingPush)
} }
let applied = applyFlightData( // TODO-APP: If the prefetch was postponed, we don't want to apply it
currentCache, // until we land router changes to handle the postponed case.
cache, let applied = postponed
flightDataPath, ? false
prefetchValues.kind === 'auto' && : applyFlightData(
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable currentCache,
) cache,
flightDataPath,
prefetchValues.kind === 'auto' &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
)
if ( if (
!applied && !applied &&
......
...@@ -42,6 +42,10 @@ export interface StaticGenerationStore { ...@@ -42,6 +42,10 @@ export interface StaticGenerationStore {
fetchMetrics?: FetchMetrics fetchMetrics?: FetchMetrics
isDraftMode?: boolean isDraftMode?: boolean
readonly experimental: {
readonly ppr: boolean
}
} }
export type StaticGenerationAsyncStorage = export type StaticGenerationAsyncStorage =
......
...@@ -36,7 +36,7 @@ export const staticGenerationBailout: StaticGenerationBailout = ( ...@@ -36,7 +36,7 @@ export const staticGenerationBailout: StaticGenerationBailout = (
) )
} }
if (staticGenerationStore) { if (staticGenerationStore && !staticGenerationStore?.experimental.ppr) {
staticGenerationStore.revalidate = 0 staticGenerationStore.revalidate = 0
if (!opts?.dynamic) { if (!opts?.dynamic) {
...@@ -47,14 +47,24 @@ export const staticGenerationBailout: StaticGenerationBailout = ( ...@@ -47,14 +47,24 @@ export const staticGenerationBailout: StaticGenerationBailout = (
} }
if (staticGenerationStore?.isStaticGeneration) { if (staticGenerationStore?.isStaticGeneration) {
const err = new DynamicServerError( const message = formatErrorMessage(reason, {
formatErrorMessage(reason, { ...opts,
...opts, // this error should be caught by Next to bail out of static generation
// this error should be caught by Next to bail out of static generation // in case it's uncaught, this link provides some additional context as to why
// in case it's uncaught, this link provides some additional context as to why link: 'https://nextjs.org/docs/messages/dynamic-server-error',
link: 'https://nextjs.org/docs/messages/dynamic-server-error', })
})
) if (staticGenerationStore?.experimental.ppr) {
const React = require('react') as typeof import('react')
// App Route's cannot be postponed, so we only postpone if it's a page.
if (typeof React.unstable_postpone === 'function') {
// This throws a postpone error similar to the below error.
React.unstable_postpone(message)
}
}
const err = new DynamicServerError(message)
staticGenerationStore.dynamicUsageDescription = reason staticGenerationStore.dynamicUsageDescription = reason
staticGenerationStore.dynamicUsageStack = err.stack staticGenerationStore.dynamicUsageStack = err.stack
......
...@@ -7,4 +7,6 @@ export const isDynamicUsageError = (err: any) => ...@@ -7,4 +7,6 @@ export const isDynamicUsageError = (err: any) =>
err.digest === DYNAMIC_ERROR_CODE || err.digest === DYNAMIC_ERROR_CODE ||
isNotFoundError(err) || isNotFoundError(err) ||
err.digest === NEXT_DYNAMIC_NO_SSR_CODE || err.digest === NEXT_DYNAMIC_NO_SSR_CODE ||
isRedirectError(err) isRedirectError(err) ||
// TODO: (wyattjoh) remove once we bump react
err.$$typeof === Symbol.for('react.postpone')
...@@ -503,6 +503,7 @@ export async function exportAppImpl( ...@@ -503,6 +503,7 @@ export async function exportAppImpl(
: {}), : {}),
strictNextHead: !!nextConfig.experimental.strictNextHead, strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId, deploymentId: nextConfig.experimental.deploymentId,
ppr: nextConfig.experimental.ppr === true,
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......
...@@ -2,6 +2,7 @@ import type { ExportRouteResult, FileWriter } from '../types' ...@@ -2,6 +2,7 @@ import type { ExportRouteResult, FileWriter } from '../types'
import type { RenderOpts } from '../../server/app-render/types' import type { RenderOpts } from '../../server/app-render/types'
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
import type { NextParsedUrlQuery } from '../../server/request-meta' import type { NextParsedUrlQuery } from '../../server/request-meta'
import type { RouteMetadata } from './types'
import type { import type {
MockedRequest, MockedRequest,
...@@ -105,6 +106,7 @@ export async function exportAppPage( ...@@ -105,6 +106,7 @@ export async function exportAppPage(
const { metadata } = result const { metadata } = result
const flightData = metadata.pageData const flightData = metadata.pageData
const revalidate = metadata.revalidate ?? false const revalidate = metadata.revalidate ?? false
const postponed = metadata.postponed
if (revalidate === 0) { if (revalidate === 0) {
if (isDynamicError) { if (isDynamicError) {
...@@ -158,11 +160,11 @@ export async function exportAppPage( ...@@ -158,11 +160,11 @@ export async function exportAppPage(
) )
// Writing the request metadata to a file. // Writing the request metadata to a file.
const meta = { headers } const meta: RouteMetadata = { status: undefined, headers, postponed }
await fileWriter( await fileWriter(
ExportedAppPageFiles.META, ExportedAppPageFiles.META,
htmlFilepath.replace(/\.html$/, '.meta'), htmlFilepath.replace(/\.html$/, '.meta'),
JSON.stringify(meta) JSON.stringify(meta, null, 2)
) )
// Writing the RSC payload to a file. // Writing the RSC payload to a file.
......
...@@ -60,6 +60,7 @@ export async function exportAppRoute( ...@@ -60,6 +60,7 @@ export async function exportAppRoute(
notFoundRoutes: [], notFoundRoutes: [],
}, },
renderOpts: { renderOpts: {
ppr: false,
originalPathname: page, originalPathname: page,
nextExport: true, nextExport: true,
supportsDynamicHTML: false, supportsDynamicHTML: false,
......
import type { OutgoingHttpHeaders } from 'node:http'
export type RouteMetadata = {
status: number | undefined
headers: OutgoingHttpHeaders | undefined
postponed: string | undefined
}
...@@ -6,6 +6,8 @@ export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate' ...@@ -6,6 +6,8 @@ export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'
export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER = export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
'x-prerender-revalidate-if-generated' 'x-prerender-revalidate-if-generated'
export const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed'
export const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags' export const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags'
export const NEXT_CACHE_SOFT_TAGS_HEADER = 'x-next-cache-soft-tags' export const NEXT_CACHE_SOFT_TAGS_HEADER = 'x-next-cache-soft-tags'
export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags' export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'
......
...@@ -5,8 +5,9 @@ import { isNotFoundError } from '../../client/components/not-found' ...@@ -5,8 +5,9 @@ import { isNotFoundError } from '../../client/components/not-found'
import { isRedirectError } from '../../client/components/redirect' import { isRedirectError } from '../../client/components/redirect'
import { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error' import { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error'
import { SpanStatusCode, getTracer } from '../lib/trace/tracer' import { SpanStatusCode, getTracer } from '../lib/trace/tracer'
import { isAbortError } from '../pipe-readable'
export type ErrorHandler = (err: any) => string export type ErrorHandler = (err: any) => string | undefined
/** /**
* Create error handler for renderers. * Create error handler for renderers.
...@@ -31,7 +32,7 @@ export function createErrorHandler({ ...@@ -31,7 +32,7 @@ export function createErrorHandler({
capturedErrors: Error[] capturedErrors: Error[]
allCapturedErrors?: Error[] allCapturedErrors?: Error[]
}): ErrorHandler { }): ErrorHandler {
return (err: any): string => { return (err) => {
if (allCapturedErrors) allCapturedErrors.push(err) if (allCapturedErrors) allCapturedErrors.push(err)
if ( if (
...@@ -44,6 +45,9 @@ export function createErrorHandler({ ...@@ -44,6 +45,9 @@ export function createErrorHandler({
return err.digest return err.digest
} }
// If the response was closed, we don't need to log the error.
if (isAbortError(err)) return
// Format server errors in development to add more helpful error messages // Format server errors in development to add more helpful error messages
if (dev) { if (dev) {
formatServerError(err) formatServerError(err)
......
...@@ -6,24 +6,29 @@ import type { createErrorHandler } from './create-error-handler' ...@@ -6,24 +6,29 @@ import type { createErrorHandler } from './create-error-handler'
import React, { use } from 'react' import React, { use } from 'react'
import { useFlightResponse } from './use-flight-response' import { useFlightResponse } from './use-flight-response'
export type ServerComponentRendererOptions = {
ComponentMod: AppPageModule
inlinedDataTransformStream: TransformStream<Uint8Array, Uint8Array>
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
formState: null | any
serverComponentsErrorHandler: ReturnType<typeof createErrorHandler>
nonce?: string
}
/** /**
* Create a component that renders the Flight stream. * Create a component that renders the Flight stream.
* This is only used for renderToHTML, the Flight response does not need additional wrappers. * This is only used for renderToHTML, the Flight response does not need additional wrappers.
*/ */
export function createServerComponentRenderer<Props>( export function createServerComponentRenderer<Props>(
ComponentToRender: (props: Props) => any, ComponentToRender: (props: Props) => any,
ComponentMod: AppPageModule,
{ {
ComponentMod,
inlinedDataTransformStream, inlinedDataTransformStream,
clientReferenceManifest, clientReferenceManifest,
formState, formState,
}: { nonce,
inlinedDataTransformStream: TransformStream<Uint8Array, Uint8Array> serverComponentsErrorHandler,
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']> }: ServerComponentRendererOptions
formState: null | any
},
serverComponentsErrorHandler: ReturnType<typeof createErrorHandler>,
nonce?: string
): (props: Props) => JSX.Element { ): (props: Props) => JSX.Element {
let flightStream: ReadableStream<Uint8Array> let flightStream: ReadableStream<Uint8Array>
const createFlightStream = (props: Props) => { const createFlightStream = (props: Props) => {
......
...@@ -5,28 +5,29 @@ import { ...@@ -5,28 +5,29 @@ import {
isRedirectError, isRedirectError,
} from '../../client/components/redirect' } from '../../client/components/redirect'
import { getRedirectStatusCodeFromError } from '../../client/components/get-redirect-status-code-from-error' import { getRedirectStatusCodeFromError } from '../../client/components/get-redirect-status-code-from-error'
import { renderToString } from './render-to-string' import { renderToReadableStream } from 'react-dom/server.edge'
import { streamToString } from '../stream-utils/node-web-streams-helper'
export function makeGetServerInsertedHTML({ export function makeGetServerInsertedHTML({
polyfills, polyfills,
renderServerInsertedHTML, renderServerInsertedHTML,
hasPostponed,
}: { }: {
polyfills: JSX.IntrinsicElements['script'][] polyfills: JSX.IntrinsicElements['script'][]
renderServerInsertedHTML: () => React.ReactNode renderServerInsertedHTML: () => React.ReactNode
hasPostponed: boolean
}) { }) {
let flushedErrorMetaTagsUntilIndex = 0 let flushedErrorMetaTagsUntilIndex = 0
let polyfillsFlushed = false // If the render had postponed, then we have already flushed the polyfills.
let polyfillsFlushed = hasPostponed
return function getServerInsertedHTML(serverCapturedErrors: Error[]) { return async function getServerInsertedHTML(serverCapturedErrors: Error[]) {
// Loop through all the errors that have been captured but not yet // Loop through all the errors that have been captured but not yet
// flushed. // flushed.
const errorMetaTags = [] const errorMetaTags = []
for ( while (flushedErrorMetaTagsUntilIndex < serverCapturedErrors.length) {
;
flushedErrorMetaTagsUntilIndex < serverCapturedErrors.length;
flushedErrorMetaTagsUntilIndex++
) {
const error = serverCapturedErrors[flushedErrorMetaTagsUntilIndex] const error = serverCapturedErrors[flushedErrorMetaTagsUntilIndex]
flushedErrorMetaTagsUntilIndex++
if (isNotFoundError(error)) { if (isNotFoundError(error)) {
errorMetaTags.push( errorMetaTags.push(
...@@ -51,21 +52,24 @@ export function makeGetServerInsertedHTML({ ...@@ -51,21 +52,24 @@ export function makeGetServerInsertedHTML({
} }
} }
const flushed = renderToString({ const stream = await renderToReadableStream(
ReactDOMServer: require('react-dom/server.edge'), <>
element: ( {/* Insert the polyfills if they haven't been flushed yet. */}
<> {!polyfillsFlushed &&
{polyfillsFlushed polyfills?.map((polyfill) => {
? null return <script key={polyfill.src} {...polyfill} />
: polyfills?.map((polyfill) => { })}
return <script key={polyfill.src} {...polyfill} /> {renderServerInsertedHTML()}
})} {errorMetaTags}
{renderServerInsertedHTML()} </>
{errorMetaTags} )
</>
), // Mark polyfills as flushed so they don't get flushed again.
}) if (!polyfillsFlushed) polyfillsFlushed = true
polyfillsFlushed = true
return flushed // Wait for the stream to be ready.
await stream.allReady
return streamToString(stream)
} }
} }
type StreamOptions = {
onError?: (error: Error) => void
nonce?: string
bootstrapScripts?: {
src: string
integrity?: string
crossOrigin?: string
}[]
formState?: boolean
}
type RenderResult = {
stream: ReadableStream<Uint8Array>
postponed?: object | null
}
export interface Renderer {
render(children: JSX.Element, options: StreamOptions): Promise<RenderResult>
}
class StaticRenderer implements Renderer {
private readonly prerender = require('react-dom/static.edge')
.prerender as typeof import('react-dom/static.edge')['prerender']
public async render(children: JSX.Element, streamOptions: StreamOptions) {
const { prelude, postponed } = await this.prerender(children, streamOptions)
return { stream: prelude, postponed }
}
}
class StaticResumeRenderer implements Renderer {
private readonly resume = require('react-dom/server.edge')
.resume as typeof import('react-dom/server.edge')['resume']
constructor(private readonly postponed: object) {}
public async render(children: JSX.Element, streamOptions: StreamOptions) {
const stream = await this.resume(children, this.postponed, streamOptions)
return { stream }
}
}
export class ServerRenderer implements Renderer {
private readonly renderToReadableStream = require('react-dom/server.edge')
.renderToReadableStream as typeof import('react-dom/server.edge')['renderToReadableStream']
public async render(
children: JSX.Element,
options: StreamOptions
): Promise<RenderResult> {
const stream = await this.renderToReadableStream(children, options)
return { stream }
}
}
type Options = {
ppr: boolean
isStaticGeneration: boolean
postponed: object | null
}
export function createStaticRenderer({
ppr,
isStaticGeneration,
postponed,
}: Options): Renderer {
if (ppr) {
if (isStaticGeneration) {
return new StaticRenderer()
}
if (postponed) {
return new StaticResumeRenderer(postponed)
}
}
return new ServerRenderer()
}
...@@ -135,6 +135,8 @@ export interface RenderOptsPartial { ...@@ -135,6 +135,8 @@ export interface RenderOptsPartial {
serverActionsBodySizeLimit?: SizeLimit serverActionsBodySizeLimit?: SizeLimit
params?: ParsedUrlQuery params?: ParsedUrlQuery
isPrefetch?: boolean isPrefetch?: boolean
ppr: boolean
postponed?: string
} }
export type RenderOpts = LoadComponentsReturnType<AppPageModule> & export type RenderOpts = LoadComponentsReturnType<AppPageModule> &
......
...@@ -12,12 +12,12 @@ export type StaticGenerationContext = { ...@@ -12,12 +12,12 @@ export type StaticGenerationContext = {
isRevalidate?: boolean isRevalidate?: boolean
isOnDemandRevalidate?: boolean isOnDemandRevalidate?: boolean
isBot?: boolean isBot?: boolean
isPrefetch?: boolean
nextExport?: boolean nextExport?: boolean
fetchCache?: StaticGenerationStore['fetchCache'] fetchCache?: StaticGenerationStore['fetchCache']
isDraftMode?: boolean isDraftMode?: boolean
isServerAction?: boolean isServerAction?: boolean
waitUntil?: Promise<any> waitUntil?: Promise<any>
ppr: boolean
/** /**
* A hack around accessing the store value outside the context of the * A hack around accessing the store value outside the context of the
...@@ -76,6 +76,9 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -76,6 +76,9 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate, isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
isDraftMode: renderOpts.isDraftMode, isDraftMode: renderOpts.isDraftMode,
experimental: {
ppr: renderOpts.ppr,
},
} }
// TODO: remove this when we resolve accessing the store outside the execution context // TODO: remove this when we resolve accessing the store outside the execution context
......
...@@ -109,6 +109,7 @@ import { ...@@ -109,6 +109,7 @@ import {
import { import {
CACHE_ONE_YEAR, CACHE_ONE_YEAR,
NEXT_CACHE_TAGS_HEADER, NEXT_CACHE_TAGS_HEADER,
NEXT_DID_POSTPONE_HEADER,
NEXT_QUERY_PARAM_PREFIX, NEXT_QUERY_PARAM_PREFIX,
} from '../lib/constants' } from '../lib/constants'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
...@@ -246,6 +247,7 @@ type BaseRenderOpts = { ...@@ -246,6 +247,7 @@ type BaseRenderOpts = {
appDirDevErrorLogger?: (err: any) => Promise<void> appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean strictNextHead: boolean
isExperimentalCompile?: boolean isExperimentalCompile?: boolean
ppr: boolean
} }
export interface BaseRequestHandler { export interface BaseRequestHandler {
...@@ -504,6 +506,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -504,6 +506,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// @ts-expect-error internal field not publicly exposed // @ts-expect-error internal field not publicly exposed
isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile, isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,
ppr: this.nextConfig.experimental.ppr === true,
} }
// Initialize next/config with the environment configuration // Initialize next/config with the environment configuration
...@@ -1684,6 +1687,13 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1684,6 +1687,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) && ) &&
(isSSG || hasServerProps) (isSSG || hasServerProps)
/**
* If true, this indicates that the request being made is for an app
* prefetch request.
*/
const isAppPrefetch =
req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] === '1'
// when we are handling a middleware prefetch and it doesn't // when we are handling a middleware prefetch and it doesn't
// resolve to a static data route we bail early to avoid // resolve to a static data route we bail early to avoid
// unexpected SSR invocations // unexpected SSR invocations
...@@ -1962,10 +1972,12 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1962,10 +1972,12 @@ export default abstract class Server<ServerOptions extends Options = Options> {
| 'https', | 'https',
}) })
const doRender: () => Promise<ResponseCacheEntry | null> = async () => { const doRender: (
postponed?: string
) => Promise<ResponseCacheEntry | null> = async (postponed?: string) => {
// In development, we always want to generate dynamic HTML. // In development, we always want to generate dynamic HTML.
const supportsDynamicHTML = const supportsDynamicHTML =
(!isDataReq && opts.dev) || !(isSSG || hasStaticPaths) (!isDataReq && opts.dev) || !(isSSG || hasStaticPaths) || !!postponed
let headers: OutgoingHttpHeaders | undefined let headers: OutgoingHttpHeaders | undefined
...@@ -2021,6 +2033,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2021,6 +2033,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
isOnDemandRevalidate, isOnDemandRevalidate,
isDraftMode: isPreviewMode, isDraftMode: isPreviewMode,
isServerAction, isServerAction,
postponed,
} }
// Legacy render methods will return a render result that needs to be // Legacy render methods will return a render result that needs to be
...@@ -2034,6 +2047,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2034,6 +2047,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
params: opts.params, params: opts.params,
prerenderManifest, prerenderManifest,
renderOpts: { renderOpts: {
// App Route's cannot postpone, so don't enable it.
ppr: false,
originalPathname: components.ComponentMod.originalPathname, originalPathname: components.ComponentMod.originalPathname,
supportsDynamicHTML, supportsDynamicHTML,
incrementalCache, incrementalCache,
...@@ -2123,12 +2138,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2123,12 +2138,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} else if ( } else if (
components.routeModule?.definition.kind === RouteKind.APP_PAGE components.routeModule?.definition.kind === RouteKind.APP_PAGE
) { ) {
const isAppPrefetch = req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()]
if (isAppPrefetch && process.env.NODE_ENV === 'production') { if (isAppPrefetch && process.env.NODE_ENV === 'production') {
try { try {
const prefetchRsc = await this.getPrefetchRsc(resolvedUrlPathname) const prefetchRsc = await this.getPrefetchRsc(resolvedUrlPathname)
if (prefetchRsc) { if (prefetchRsc) {
res.setHeader( res.setHeader(
'cache-control', 'cache-control',
...@@ -2138,9 +2150,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2138,9 +2150,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
res.body(prefetchRsc).send() res.body(prefetchRsc).send()
return null return null
} }
} catch (_) { } catch {
// we fallback to invoking the function if prefetch // We fallback to invoking the function if prefetch data is not
// data is not available // available.
} }
} }
...@@ -2243,6 +2255,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2243,6 +2255,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
kind: 'PAGE', kind: 'PAGE',
html: result, html: result,
pageData: metadata.pageData, pageData: metadata.pageData,
postponed: metadata.postponed,
headers, headers,
status: isAppPath ? res.statusCode : undefined, status: isAppPath ? res.statusCode : undefined,
}, },
...@@ -2351,10 +2364,14 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2351,10 +2364,14 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const html = await this.getFallback( const html = await this.getFallback(
locale ? `/${locale}${pathname}` : pathname locale ? `/${locale}${pathname}` : pathname
) )
return { return {
value: { value: {
kind: 'PAGE', kind: 'PAGE',
html: RenderResult.fromStatic(html), html: RenderResult.fromStatic(html),
postponed: undefined,
status: undefined,
headers: undefined,
pageData: {}, pageData: {},
}, },
} }
...@@ -2523,11 +2540,76 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2523,11 +2540,76 @@ export default abstract class Server<ServerOptions extends Options = Options> {
res.statusCode = cachedData.status res.statusCode = cachedData.status
} }
// Mark that the request did postpone if this is a data request or we're
// testing. It's used to verify that we're actually serving a postponed
// request so we can trust the cache headers.
if (
cachedData.postponed &&
(isDataReq || process.env.__NEXT_TEST_MODE)
) {
res.setHeader(NEXT_DID_POSTPONE_HEADER, '1')
}
if (isDataReq) {
if (cachedData.postponed && !isAppPrefetch) {
const result = await doRender(cachedData.postponed)
if (!result) {
return null
}
if (result.value?.kind !== 'PAGE') {
throw new Error('Invariant: Expected a page response')
}
if (!result.value.pageData) {
throw new Error('Invariant: Expected pageData to be defined')
}
return {
type: 'rsc',
body: RenderResult.fromStatic(result.value.pageData as string),
revalidate: cacheEntry.revalidate,
}
}
return {
type: 'rsc',
body: RenderResult.fromStatic(cachedData.pageData as string),
revalidate: cacheEntry.revalidate,
}
}
let body = cachedData.html
// If the request has a postponed state, let's try and resume it...
if (cachedData.postponed) {
const transformer = new TransformStream<Uint8Array, Uint8Array>()
// Perform the second render, now with the postponed state.
doRender(cachedData.postponed)
.then(async (result) => {
if (!result) {
throw new Error('Invariant: Expected a result to be returned')
}
if (result.value?.kind !== 'PAGE') {
throw new Error('Invariant: Expected a page response')
}
// Pipe the resume result to the transformer.
await result.value.html.pipeTo(transformer.writable)
})
.catch((err) => {
console.error('Error while resuming postponed state', err)
})
// Chain this new transformer readable to the existing body.
body.chain(transformer.readable)
}
return { return {
type: isDataReq ? 'rsc' : 'html', type: 'html',
body: isDataReq body,
? RenderResult.fromStatic(cachedData.pageData as string)
: cachedData.html,
revalidate: cacheEntry.revalidate, revalidate: cacheEntry.revalidate,
} }
} }
......
...@@ -668,6 +668,7 @@ export default class DevServer extends Server { ...@@ -668,6 +668,7 @@ export default class DevServer extends Server {
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix, fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk, isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize, maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize,
ppr: this.nextConfig.experimental.ppr === true,
}) })
return pathsResult return pathsResult
} finally { } finally {
......
...@@ -18,7 +18,11 @@ import { staticGenerationAsyncStorage } from '../../client/components/static-gen ...@@ -18,7 +18,11 @@ import { staticGenerationAsyncStorage } from '../../client/components/static-gen
const { AppRouteRouteModule } = const { AppRouteRouteModule } =
require('../future/route-modules/app-route/module.compiled') as typeof import('../future/route-modules/app-route/module') require('../future/route-modules/app-route/module.compiled') as typeof import('../future/route-modules/app-route/module')
type RuntimeConfig = any type RuntimeConfig = {
configFileName: string
publicRuntimeConfig: { [key: string]: any }
serverRuntimeConfig: { [key: string]: any }
}
// we call getStaticPaths in a separate process to ensure // we call getStaticPaths in a separate process to ensure
// side-effects aren't relied on in dev that will break // side-effects aren't relied on in dev that will break
...@@ -37,6 +41,7 @@ export async function loadStaticPaths({ ...@@ -37,6 +41,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize, maxMemoryCacheSize,
requestHeaders, requestHeaders,
incrementalCacheHandlerPath, incrementalCacheHandlerPath,
ppr,
}: { }: {
distDir: string distDir: string
pathname: string pathname: string
...@@ -51,6 +56,7 @@ export async function loadStaticPaths({ ...@@ -51,6 +56,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
incrementalCacheHandlerPath?: string incrementalCacheHandlerPath?: string
ppr: boolean
}): Promise<{ }): Promise<{
paths?: string[] paths?: string[]
encodedPaths?: string[] encodedPaths?: string[]
...@@ -106,6 +112,7 @@ export async function loadStaticPaths({ ...@@ -106,6 +112,7 @@ export async function loadStaticPaths({
isrFlushToDisk, isrFlushToDisk,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
maxMemoryCacheSize, maxMemoryCacheSize,
ppr,
}) })
} }
......
import type { OutgoingHttpHeaders } from 'http' import type { RouteMetadata } from '../../../export/routes/types'
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './' import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
import type { CacheFs } from '../../../shared/lib/utils' import type { CacheFs } from '../../../shared/lib/utils'
import type { CachedFetchValue } from '../../response-cache' import type { CachedFetchValue } from '../../response-cache'
...@@ -197,7 +197,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -197,7 +197,7 @@ export default class FileSystemCache implements CacheHandler {
) )
) )
let meta: { status?: number; headers?: OutgoingHttpHeaders } = {} let meta: RouteMetadata | undefined
if (isAppPath) { if (isAppPath) {
try { try {
...@@ -216,8 +216,9 @@ export default class FileSystemCache implements CacheHandler { ...@@ -216,8 +216,9 @@ export default class FileSystemCache implements CacheHandler {
kind: 'PAGE', kind: 'PAGE',
html: fileData, html: fileData,
pageData, pageData,
headers: meta.headers, postponed: meta?.postponed,
status: meta.status, headers: meta?.headers,
status: meta?.status,
}, },
} }
} }
...@@ -281,7 +282,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -281,7 +282,7 @@ export default class FileSystemCache implements CacheHandler {
} }
} }
return data || null return data ?? null
} }
public async set( public async set(
...@@ -304,9 +305,16 @@ export default class FileSystemCache implements CacheHandler { ...@@ -304,9 +305,16 @@ export default class FileSystemCache implements CacheHandler {
}) })
await this.fs.mkdir(path.dirname(filePath)) await this.fs.mkdir(path.dirname(filePath))
await this.fs.writeFile(filePath, data.body) await this.fs.writeFile(filePath, data.body)
const meta: RouteMetadata = {
headers: data.headers,
status: data.status,
postponed: undefined,
}
await this.fs.writeFile( await this.fs.writeFile(
filePath.replace(/\.body$/, '.meta'), filePath.replace(/\.body$/, '.meta'),
JSON.stringify({ headers: data.headers, status: data.status }) JSON.stringify(meta, null, 2)
) )
return return
} }
...@@ -331,12 +339,15 @@ export default class FileSystemCache implements CacheHandler { ...@@ -331,12 +339,15 @@ export default class FileSystemCache implements CacheHandler {
) )
if (data.headers || data.status) { if (data.headers || data.status) {
const meta: RouteMetadata = {
headers: data.headers,
status: data.status,
postponed: data.postponed,
}
await this.fs.writeFile( await this.fs.writeFile(
htmlPath.replace(/\.html$/, '.meta'), htmlPath.replace(/\.html$/, '.meta'),
JSON.stringify({ JSON.stringify(meta)
headers: data.headers,
status: data.status,
})
) )
} }
} else if (data?.kind === 'FETCH') { } else if (data?.kind === 'FETCH') {
......
...@@ -2,7 +2,11 @@ import type { ServerResponse } from 'http' ...@@ -2,7 +2,11 @@ import type { ServerResponse } from 'http'
import type { StaticGenerationStore } from '../client/components/static-generation-async-storage.external' import type { StaticGenerationStore } from '../client/components/static-generation-async-storage.external'
import type { Revalidate } from './lib/revalidate' import type { Revalidate } from './lib/revalidate'
import { streamToString } from './stream-utils/node-web-streams-helper' import {
chainStreams,
streamFromString,
streamToString,
} from './stream-utils/node-web-streams-helper'
import { isAbortError, pipeToNodeResponse } from './pipe-readable' import { isAbortError, pipeToNodeResponse } from './pipe-readable'
type ContentTypeOption = string | undefined type ContentTypeOption = string | undefined
...@@ -17,9 +21,14 @@ export type RenderResultMetadata = { ...@@ -17,9 +21,14 @@ export type RenderResultMetadata = {
fetchMetrics?: StaticGenerationStore['fetchMetrics'] fetchMetrics?: StaticGenerationStore['fetchMetrics']
fetchTags?: string fetchTags?: string
waitUntil?: Promise<any> waitUntil?: Promise<any>
postponed?: string
} }
type RenderResultResponse = ReadableStream<Uint8Array> | string | null type RenderResultResponse =
| ReadableStream<Uint8Array>[]
| ReadableStream<Uint8Array>
| string
| null
export default class RenderResult { export default class RenderResult {
/** /**
...@@ -40,7 +49,7 @@ export default class RenderResult { ...@@ -40,7 +49,7 @@ export default class RenderResult {
* dynamic response. If it's null, then the response was not found or was * dynamic response. If it's null, then the response was not found or was
* already sent. * already sent.
*/ */
private readonly response: RenderResultResponse private response: RenderResultResponse
/** /**
* Creates a new RenderResult instance from a static response. * Creates a new RenderResult instance from a static response.
...@@ -111,7 +120,7 @@ export default class RenderResult { ...@@ -111,7 +120,7 @@ export default class RenderResult {
) )
} }
return streamToString(this.response) return streamToString(this.readable)
} }
return this.response return this.response
...@@ -129,9 +138,44 @@ export default class RenderResult { ...@@ -129,9 +138,44 @@ export default class RenderResult {
throw new Error('Invariant: static responses cannot be streamed') throw new Error('Invariant: static responses cannot be streamed')
} }
// If the response is an array of streams, then chain them together.
if (Array.isArray(this.response)) {
return chainStreams(...this.response)
}
return this.response return this.response
} }
/**
* Chains a new stream to the response. This will convert the response to an
* array of streams if it is not already one and will add the new stream to
* the end. When this response is piped, all of the streams will be piped
* one after the other.
*
* @param readable The new stream to chain
*/
public chain(readable: ReadableStream<Uint8Array>) {
if (this.response === null) {
throw new Error('Invariant: response is null. This is a bug in Next.js')
}
// If the response is not an array of streams already, make it one.
let responses: ReadableStream<Uint8Array>[]
if (typeof this.response === 'string') {
responses = [streamFromString(this.response)]
} else if (Array.isArray(this.response)) {
responses = this.response
} else {
responses = [this.response]
}
// Add the new stream to the array.
responses.push(readable)
// Update the response.
this.response = responses
}
/** /**
* Pipes the response to a writable stream. This will close/cancel the * Pipes the response to a writable stream. This will close/cancel the
* writable stream if an error is encountered. * writable stream if an error is encountered.
......
...@@ -1327,18 +1327,17 @@ export async function renderToHTMLImpl( ...@@ -1327,18 +1327,17 @@ export async function renderToHTMLImpl(
const createBodyResult = getTracer().wrap( const createBodyResult = getTracer().wrap(
RenderSpan.createBodyResult, RenderSpan.createBodyResult,
(initialStream: ReactReadableStream, suffix?: string) => { (initialStream: ReactReadableStream, suffix?: string) => {
// this must be called inside bodyResult so appWrappers is
// up to date when `wrapApp` is called
const getServerInsertedHTML = async (): Promise<string> => {
return renderToString(styledJsxInsertedHTML())
}
return continueFizzStream(initialStream, { return continueFizzStream(initialStream, {
suffix, suffix,
inlinedDataStream: serverComponentsInlinedTransformStream?.readable, inlinedDataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML: true, generateStaticHTML: true,
getServerInsertedHTML, // this must be called inside bodyResult so appWrappers is
// up to date when `wrapApp` is called
getServerInsertedHTML: () => {
return renderToString(styledJsxInsertedHTML())
},
serverInsertedHTMLToHead: false, serverInsertedHTMLToHead: false,
validateRootLayout: undefined,
}) })
} }
) )
...@@ -1553,16 +1552,18 @@ export async function renderToHTMLImpl( ...@@ -1553,16 +1552,18 @@ export async function renderToHTMLImpl(
prefix += '<!-- __NEXT_DATA__ -->' prefix += '<!-- __NEXT_DATA__ -->'
} }
const streams = [ const content = await streamToString(
streamFromString(prefix), chainStreams(
await documentResult.bodyResult(renderTargetSuffix), streamFromString(prefix),
] await documentResult.bodyResult(renderTargetSuffix)
)
)
const postOptimize = (html: string) => const optimizedHtml = await postProcessHTML(pathname, content, renderOpts, {
postProcessHTML(pathname, html, renderOpts, { inAmpMode, hybridAmp }) inAmpMode,
hybridAmp,
})
const html = await streamToString(chainStreams(streams))
const optimizedHtml = await postOptimize(html)
return new RenderResult(optimizedHtml, renderResultMeta) return new RenderResult(optimizedHtml, renderResultMeta)
} }
......
...@@ -93,6 +93,7 @@ export default class ResponseCache { ...@@ -93,6 +93,7 @@ export default class ResponseCache {
kind: 'PAGE', kind: 'PAGE',
html: RenderResult.fromStatic(cachedResponse.value.html), html: RenderResult.fromStatic(cachedResponse.value.html),
pageData: cachedResponse.value.pageData, pageData: cachedResponse.value.pageData,
postponed: cachedResponse.value.postponed,
headers: cachedResponse.value.headers, headers: cachedResponse.value.headers,
status: cachedResponse.value.status, status: cachedResponse.value.status,
} }
...@@ -137,6 +138,7 @@ export default class ResponseCache { ...@@ -137,6 +138,7 @@ export default class ResponseCache {
? { ? {
kind: 'PAGE', kind: 'PAGE',
html: cacheEntry.value.html.toUnchunkedString(), html: cacheEntry.value.html.toUnchunkedString(),
postponed: cacheEntry.value.postponed,
pageData: cacheEntry.value.pageData, pageData: cacheEntry.value.pageData,
headers: cacheEntry.value.headers, headers: cacheEntry.value.headers,
status: cacheEntry.value.status, status: cacheEntry.value.status,
......
...@@ -38,9 +38,10 @@ interface CachedPageValue { ...@@ -38,9 +38,10 @@ interface CachedPageValue {
// this needs to be a RenderResult so since renderResponse // this needs to be a RenderResult so since renderResponse
// expects that type instead of a string // expects that type instead of a string
html: RenderResult html: RenderResult
postponed: string | undefined
pageData: Object pageData: Object
status?: number status: number | undefined
headers?: OutgoingHttpHeaders headers: OutgoingHttpHeaders | undefined
} }
export interface CachedRouteValue { export interface CachedRouteValue {
...@@ -67,8 +68,9 @@ interface IncrementalCachedPageValue { ...@@ -67,8 +68,9 @@ interface IncrementalCachedPageValue {
// the string value // the string value
html: string html: string
pageData: Object pageData: Object
headers?: OutgoingHttpHeaders postponed: string | undefined
status?: number headers: OutgoingHttpHeaders | undefined
status: number | undefined
} }
export type IncrementalCacheEntry = { export type IncrementalCacheEntry = {
......
import type { FlightRouterState } from '../app-render/types' import type { FlightRouterState } from '../app-render/types'
import { nonNullable } from '../../lib/non-nullable'
import { getTracer } from '../lib/trace/tracer' import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants' import { AppRenderSpan } from '../lib/trace/constants'
import { createDecodeTransformStream } from './encode-decode' import { createDecodeTransformStream } from './encode-decode'
...@@ -31,7 +30,7 @@ export function cloneTransformStream(source: TransformStream) { ...@@ -31,7 +30,7 @@ export function cloneTransformStream(source: TransformStream) {
} }
export function chainStreams<T>( export function chainStreams<T>(
streams: ReadableStream<T>[] ...streams: ReadableStream<T>[]
): ReadableStream<T> { ): ReadableStream<T> {
const { readable, writable } = new TransformStream() const { readable, writable } = new TransformStream()
...@@ -428,6 +427,36 @@ export function createRootLayoutValidatorStream( ...@@ -428,6 +427,36 @@ export function createRootLayoutValidatorStream(
}) })
} }
function chainTransformers<T>(
readable: ReadableStream<T>,
transformers: ReadonlyArray<TransformStream<T, T> | null>
): ReadableStream<T> {
let stream = readable
for (const transformer of transformers) {
if (!transformer) continue
stream = stream.pipeThrough(transformer)
}
return stream
}
export type ContinueStreamOptions = {
inlinedDataStream: ReadableStream<Uint8Array> | undefined
generateStaticHTML: boolean
getServerInsertedHTML: (() => Promise<string>) | undefined
serverInsertedHTMLToHead: boolean
validateRootLayout:
| {
assetPrefix: string | undefined
getTree: () => FlightRouterState
}
| undefined
/**
* Suffix to inject after the buffered data, but before the close tags.
*/
suffix: string | undefined
}
export async function continueFizzStream( export async function continueFizzStream(
renderStream: ReactReadableStream, renderStream: ReactReadableStream,
{ {
...@@ -437,29 +466,20 @@ export async function continueFizzStream( ...@@ -437,29 +466,20 @@ export async function continueFizzStream(
getServerInsertedHTML, getServerInsertedHTML,
serverInsertedHTMLToHead, serverInsertedHTMLToHead,
validateRootLayout, validateRootLayout,
}: { }: ContinueStreamOptions
inlinedDataStream?: ReadableStream<Uint8Array>
generateStaticHTML: boolean
getServerInsertedHTML?: () => Promise<string>
serverInsertedHTMLToHead: boolean
validateRootLayout?: {
assetPrefix?: string
getTree: () => FlightRouterState
}
// Suffix to inject after the buffered data, but before the close tags.
suffix?: string
}
): Promise<ReadableStream<Uint8Array>> { ): Promise<ReadableStream<Uint8Array>> {
const closeTag = '</body></html>' const closeTag = '</body></html>'
// Suffix itself might contain close tags at the end, so we need to split it. // Suffix itself might contain close tags at the end, so we need to split it.
const suffixUnclosed = suffix ? suffix.split(closeTag, 1)[0] : null const suffixUnclosed = suffix ? suffix.split(closeTag, 1)[0] : null
if (generateStaticHTML) { // If we're generating static HTML and there's an `allReady` promise on the
// stream, we need to wait for it to resolve before continuing.
if (generateStaticHTML && 'allReady' in renderStream) {
await renderStream.allReady await renderStream.allReady
} }
const transforms: Array<TransformStream<Uint8Array, Uint8Array>> = [ return chainTransformers(renderStream, [
// Buffer everything to avoid flushing too frequently // Buffer everything to avoid flushing too frequently
createBufferedTransformStream(), createBufferedTransformStream(),
...@@ -477,7 +497,7 @@ export async function continueFizzStream( ...@@ -477,7 +497,7 @@ export async function continueFizzStream(
inlinedDataStream ? createMergedTransformStream(inlinedDataStream) : null, inlinedDataStream ? createMergedTransformStream(inlinedDataStream) : null,
// Close tags should always be deferred to the end // Close tags should always be deferred to the end
closeTag && createMoveSuffixStream(closeTag), createMoveSuffixStream(closeTag),
// Special head insertions // Special head insertions
// TODO-APP: Insert server side html to end of head in app layout rendering, to avoid // TODO-APP: Insert server side html to end of head in app layout rendering, to avoid
...@@ -492,10 +512,47 @@ export async function continueFizzStream( ...@@ -492,10 +512,47 @@ export async function continueFizzStream(
validateRootLayout.getTree validateRootLayout.getTree
) )
: null, : null,
].filter(nonNullable) ])
}
return transforms.reduce( type ContinuePostponedStreamOptions = Pick<
(readable, transform) => readable.pipeThrough(transform), ContinueStreamOptions,
renderStream | 'inlinedDataStream'
) | 'generateStaticHTML'
| 'getServerInsertedHTML'
| 'serverInsertedHTMLToHead'
>
export async function continuePostponedFizzStream(
renderStream: ReactReadableStream,
{
inlinedDataStream,
generateStaticHTML,
getServerInsertedHTML,
serverInsertedHTMLToHead,
}: ContinuePostponedStreamOptions
) {
const closeTag = '</body></html>'
// If we're generating static HTML and there's an `allReady` promise on the
// stream, we need to wait for it to resolve before continuing.
if (generateStaticHTML && 'allReady' in renderStream) {
await renderStream.allReady
}
return chainTransformers(renderStream, [
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
// Insert generated tags to head
getServerInsertedHTML && !serverInsertedHTMLToHead
? createInsertedHTMLStream(getServerInsertedHTML)
: null,
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
inlinedDataStream ? createMergedTransformStream(inlinedDataStream) : null,
// Close tags should always be deferred to the end
createMoveSuffixStream(closeTag),
])
} }
...@@ -109,6 +109,8 @@ export class EdgeRouteModuleWrapper { ...@@ -109,6 +109,8 @@ export class EdgeRouteModuleWrapper {
}, },
renderOpts: { renderOpts: {
supportsDynamicHTML: true, supportsDynamicHTML: true,
// App Route's cannot be postponed.
ppr: false,
}, },
} }
......
...@@ -53,8 +53,11 @@ export function unstable_cache<T extends Callback>( ...@@ -53,8 +53,11 @@ export function unstable_cache<T extends Callback>(
...store, ...store,
fetchCache: 'only-no-store', fetchCache: 'only-no-store',
urlPathname: store?.urlPathname || '/', urlPathname: store?.urlPathname || '/',
isStaticGeneration: !!store?.isStaticGeneration,
isUnstableCacheCallback: true, isUnstableCacheCallback: true,
isStaticGeneration: store?.isStaticGeneration === true,
experimental: {
ppr: store?.experimental?.ppr === true,
},
}, },
async () => { async () => {
const tags = validateTags( const tags = validateTags(
......
...@@ -31,10 +31,6 @@ declare module 'react-server-dom-webpack/server.edge' ...@@ -31,10 +31,6 @@ declare module 'react-server-dom-webpack/server.edge'
declare module 'react-server-dom-webpack/server.node' declare module 'react-server-dom-webpack/server.node'
declare module 'react-server-dom-webpack/client.edge' declare module 'react-server-dom-webpack/client.edge'
declare module 'react-dom/server-rendering-stub'
declare module 'react-dom/server.browser'
declare module 'react-dom/server.edge'
declare module 'VAR_MODULE_GLOBAL_ERROR' declare module 'VAR_MODULE_GLOBAL_ERROR'
declare module 'VAR_USERLAND' declare module 'VAR_USERLAND'
declare module 'VAR_MODULE_DOCUMENT' declare module 'VAR_MODULE_DOCUMENT'
......
declare module 'react-dom/server-rendering-stub'
declare module 'react-dom/server.browser'
declare module 'react-dom/server.edge' {
export function resume(
children: JSX.Element,
postponedState: object,
options?: {
onError?: (error: Error) => void
}
): Promise<ReadableStream<Uint8Array>>
export function renderToReadableStream(
children: JSX.Element,
options?: {
onError?: (error: Error) => void
nonce?: string
}
): Promise<
ReadableStream<Uint8Array> & {
allReady: Promise<void>
}
>
}
declare module 'react-dom/static.edge' {
export function prerender(
children: JSX.Element,
options?: {
onError?: (error: Error) => void
}
): Promise<{
prelude: ReadableStream<Uint8Array>
postponed: object | null
}>
}
import React from 'react'
declare module 'react' {
export function unstable_postpone(reason: string): never
}
export = React
...@@ -32,6 +32,9 @@ function makeAppAliases(reactChannel = '') { ...@@ -32,6 +32,9 @@ function makeAppAliases(reactChannel = '') {
'react-dom/server$': `next/dist/compiled/react-dom${reactChannel}/server`, 'react-dom/server$': `next/dist/compiled/react-dom${reactChannel}/server`,
'react-dom/server.edge$': `next/dist/compiled/react-dom${reactChannel}/server.edge`, 'react-dom/server.edge$': `next/dist/compiled/react-dom${reactChannel}/server.edge`,
'react-dom/server.browser$': `next/dist/compiled/react-dom${reactChannel}/server.browser`, 'react-dom/server.browser$': `next/dist/compiled/react-dom${reactChannel}/server.browser`,
'react-dom/static$': `next/dist/compiled/react-dom-experimental/static`,
'react-dom/static.edge$': `next/dist/compiled/react-dom-experimental/static.edge`,
'react-dom/static.browser$': `next/dist/compiled/react-dom-experimental/static.browser`,
'react-server-dom-turbopack/client$': `next/dist/compiled/react-server-dom-turbopack${reactChannel}/client`, 'react-server-dom-turbopack/client$': `next/dist/compiled/react-server-dom-turbopack${reactChannel}/client`,
'react-server-dom-turbopack/client.edge$': `next/dist/compiled/react-server-dom-turbopack${reactChannel}/client.edge`, 'react-server-dom-turbopack/client.edge$': `next/dist/compiled/react-server-dom-turbopack${reactChannel}/client.edge`,
'react-server-dom-turbopack/server.edge$': `next/dist/compiled/react-server-dom-turbopack${reactChannel}/server.edge`, 'react-server-dom-turbopack/server.edge$': `next/dist/compiled/react-server-dom-turbopack${reactChannel}/server.edge`,
......
import { cookies } from 'next/headers'
export function POST(request) {
const url = new URL(request.url)
const name = url.searchParams.get('name')
if (!name) {
return new Response(null, { status: 400 })
}
cookies().set(name, '1')
return new Response(null, { status: 204 })
}
export function DELETE(request) {
const url = new URL(request.url)
const name = url.searchParams.get('name')
if (!name) {
return new Response(null, { status: 400 })
}
cookies().delete(name)
return new Response(null, { status: 204 })
}
import React from 'react'
import Link from 'next/link'
const links = [
{ href: '/' },
{ href: '/no-suspense' },
{ href: '/suspense/node' },
{ href: '/suspense/edge' },
{ href: '/suspense/node/nested/1' },
{ href: '/loading/nested/1' },
{ href: '/loading/nested/2' },
{ href: '/loading/nested/3' },
]
export default function Root({ children }) {
return (
<html>
<head>
<script src="https://cdn.tailwindcss.com?plugins=typography"></script>
</head>
<body>
<main className="prose my-6 mx-auto">
<h1 id="page">Page</h1>
{children}
<h2>Links</h2>
<ul>
{links.map(({ href }) => (
<li key={href}>
{href} - <Link href={href}>link</Link> -{' '}
<a href={href}>anchor</a>
</li>
))}
</ul>
</main>
</body>
</html>
)
}
export default function Layout({ children }) {
return children
}
export default function Loading() {
return 'Loading...'
}
import { NonSuspensePage } from '../../../../components/page'
export default function Page() {
return <NonSuspensePage />
}
export const generateStaticParams = async () => {
return []
}
export { NonSuspensePage as default } from '../../components/page'
import React from 'react'
export default function Page() {
return <p>Go to a page from here</p>
}
export { SuspensePage as default } from '../../../components/page'
export const runtime = 'edge'
export { SuspensePage as default } from '../../../../../components/page'
export const generateStaticParams = async () => {
return []
}
export { SuspensePage as default } from '../../../components/page'
import React, { use } from 'react'
import { cookies } from 'next/headers'
import { Delay, Login } from './state'
export function Dynamic({ fallback }) {
const dynamic = fallback !== true
let signedIn
let active
if (dynamic) {
signedIn = cookies().has('session') ? true : false
active = cookies().has('delay') ? true : false
if (active) {
use(new Promise((resolve) => setTimeout(resolve, 1000)))
}
}
if (!dynamic) {
return (
<div id="dynamic-fallback">
<pre>Loading...</pre>
<Login fallback />
<Delay fallback />
</div>
)
}
return (
<div id="dynamic">
<pre id="state" className={signedIn ? 'bg-green-600' : 'bg-red-600'}>
{signedIn ? 'Signed In' : 'Not Signed In'}
</pre>
<Login signedIn={signedIn} />
<Delay active={active} />
</div>
)
}
import React, { Suspense } from 'react'
import { Dynamic } from './dynamic'
export function Page({ suspense = false }) {
let slot = <Dynamic />
if (suspense) {
slot = <Suspense fallback={<Dynamic fallback />}>{slot}</Suspense>
}
return (
<>
<h2>Dynamic Component</h2>
<p>
This shows the dynamic component based on the existence of the{' '}
<code>session</code>
cookie.
</p>
<div id="container">{slot}</div>
</>
)
}
export function NonSuspensePage() {
return <Page />
}
export function SuspensePage() {
return <Page suspense />
}
'use client'
import { usePathname } from 'next/navigation'
import React from 'react'
import { useCallback } from 'react'
export function Login({ signedIn = false, fallback }) {
const onClick = useCallback(async () => {
if (signedIn) {
await fetch('/api/cookie?name=session', {
method: 'DELETE',
credentials: 'same-origin',
})
} else {
await fetch('/api/cookie?name=session', {
method: 'POST',
credentials: 'same-origin',
})
}
window.location.reload()
}, [signedIn])
const pathname = usePathname()
return (
<>
<pre>pathname: {pathname}</pre>
<button
id="login"
className="bg-gray-400 hover:bg-gray-500 px-4 py-2 text-white rounded-md"
onClick={onClick}
>
{fallback ? 'Sign ..' : signedIn ? 'Sign Out' : 'Sign In'}
</button>
</>
)
}
export function Delay({ active = false, fallback }) {
const onClick = useCallback(async () => {
if (active) {
await fetch('/api/cookie?name=delay', {
method: 'DELETE',
credentials: 'same-origin',
})
} else {
await fetch('/api/cookie?name=delay', {
method: 'POST',
credentials: 'same-origin',
})
}
window.location.reload()
}, [active])
return (
<>
<pre>
delay: {fallback ? 'loading...' : active ? 'enabled' : 'disabled'}
</pre>
<button
id="login"
className="bg-gray-400 hover:bg-gray-500 px-4 py-2 text-white rounded-md"
onClick={onClick}
>
{fallback ? 'Loading...' : active ? 'Disable Delay' : 'Enable Delay'}
</button>
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
},
}
module.exports = nextConfig
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'ppr',
{
files: __dirname,
skipDeployment: true,
},
({ next, isNextDev }) => {
describe.each([
{ pathname: '/suspense/node' },
{ pathname: '/suspense/node/nested/1' },
{ pathname: '/suspense/node/nested/2' },
{ pathname: '/suspense/node/nested/3' },
{ pathname: '/loading/nested/1' },
{ pathname: '/loading/nested/2' },
{ pathname: '/loading/nested/3' },
])('for $pathname', ({ pathname }) => {
// When we're partially pre-rendering, we should get the static parts
// immediately, and the dynamic parts after the page loads. So we should
// see the static part in the output, but the dynamic part should be
// missing.
it('should serve the static part', async () => {
const $ = await next.render$(pathname)
expect($('#page').length).toBe(1)
})
if (isNextDev) {
it('should have the dynamic part', async () => {
let $ = await next.render$(pathname)
let dynamic = $('#container > #dynamic > #state')
expect(dynamic.length).toBe(1)
expect(dynamic.text()).toBe('Not Signed In')
$ = await next.render$(
pathname,
{},
{
headers: {
cookie: 'session=1',
},
}
)
dynamic = $('#container > #dynamic > #state')
expect(dynamic.length).toBe(1)
expect(dynamic.text()).toBe('Signed In')
})
} else {
it('should not have the dynamic part', async () => {
const $ = await next.render$(pathname)
expect($('#container > #dynamic > #state').length).toBe(0)
})
}
if (!isNextDev) {
it('should cache the static part', async () => {
// First, render the page to populate the cache.
let res = await next.fetch(pathname)
expect(res.status).toBe(200)
expect(res.headers.get('x-nextjs-postponed')).toBe('1')
// Then, render the page again.
res = await next.fetch(pathname)
expect(res.status).toBe(200)
expect(res.headers.get('x-nextjs-cache')).toBe('HIT')
expect(res.headers.get('x-nextjs-postponed')).toBe('1')
})
}
})
describe.each([
{ pathname: '/suspense/node' },
{ pathname: '/suspense/edge' },
])('with suspense for $pathname', ({ pathname }) => {
// When the browser loads the page, we expect that the dynamic part will
// be rendered.
it('should eventually render the dynamic part', async () => {
const browser = await next.browser(pathname)
try {
// Wait for the page part to load.
await browser.waitForElementByCss('#page')
await browser.waitForIdleNetwork()
// Wait for the dynamic part to load.
await browser.waitForElementByCss('#container > #dynamic > #state')
// Ensure we've got the right dynamic part.
let dynamic = await browser
.elementByCss('#container > #dynamic > #state')
.text()
expect(dynamic).toBe('Not Signed In')
// Re-visit the page with the cookie.
await browser.addCookie({ name: 'session', value: '1' }).refresh()
// Wait for the page part to load.
await browser.waitForElementByCss('#page')
await browser.waitForIdleNetwork()
// Wait for the dynamic part to load.
await browser.waitForElementByCss('#container > #dynamic > #state')
// Ensure we've got the right dynamic part.
dynamic = await browser
.elementByCss('#container > #dynamic > #state')
.text()
expect(dynamic).toBe('Signed In')
} finally {
await browser.deleteCookies()
await browser.close()
}
})
})
describe.each([{ pathname: '/no-suspense' }])(
'without suspense for $pathname',
({ pathname }) => {
// When the browser loads the page, we expect that the dynamic part will
// be rendered.
it('should immediately render the dynamic part', async () => {
let $ = await next.render$(pathname)
let dynamic = $('#container > #dynamic > #state').text()
expect(dynamic).toBe('Not Signed In')
// Re-visit the page with the cookie.
$ = await next.render$(
pathname,
{},
{
headers: {
cookie: 'session=1',
},
}
)
dynamic = $('#container > #dynamic > #state').text()
expect(dynamic).toBe('Signed In')
})
}
)
}
)
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