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 {
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>> {
......
......@@ -92,7 +92,9 @@ pub async fn get_next_client_import_map(
);
}
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"
} else {
""
......@@ -119,6 +121,27 @@ pub async fn get_next_client_import_map(
&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(
"react-dom/",
request_to_import_mapping(
......@@ -622,7 +645,12 @@ async fn rsc_aliases(
next_config: Vc<NextConfig>,
) -> Result<()> {
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! {
"react" => format!("next/dist/compiled/react{react_channel}"),
......@@ -630,6 +658,9 @@ async fn rsc_aliases(
"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-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.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"),
......
......@@ -251,6 +251,9 @@ export function createRSCAliases(
'react/jsx-dev-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`,
'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`,
'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.browser$': `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`,
'react-server-dom-webpack/client$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`,
......
......@@ -1372,6 +1372,7 @@ export default async function build(
locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output,
ppr: config.experimental.ppr === true,
})
)
......@@ -1459,7 +1460,7 @@ export default async function build(
})
return checkPageSpan.traceAsyncFn(async () => {
const actualPage = normalizePagePath(page)
const [selfSize, allSize] = await getJsPageSizeInKb(
const [size, totalSize] = await getJsPageSizeInKb(
pageType,
actualPage,
distDir,
......@@ -1469,7 +1470,8 @@ export default async function build(
computedManifestData
)
let isSsg = false
let isPPR = false
let isSSG = false
let isStatic = false
let isServerComponent = false
let isHybridAmp = false
......@@ -1579,6 +1581,7 @@ export default async function build(
maxMemoryCacheSize:
config.experimental.isrMemoryCacheSize,
nextConfigOutput: config.output,
ppr: config.experimental.ppr === true,
})
}
)
......@@ -1588,12 +1591,21 @@ export default async function build(
// TODO-APP: handle prerendering with edge
if (isEdgeRuntime(pageRuntime)) {
isStatic = false
isSsg = false
isSSG = false
Log.warnOnce(
`Using edge runtime on a page currently disables static generation for that page`
)
} 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 (
workerResult.encodedPrerenderRoutes &&
workerResult.prerenderRoutes
......@@ -1607,7 +1619,7 @@ export default async function build(
workerResult.encodedPrerenderRoutes
)
ssgPageRoutes = workerResult.prerenderRoutes
isSsg = true
isSSG = true
}
const appConfig = workerResult.appConfig || {}
......@@ -1694,7 +1706,7 @@ export default async function build(
if (workerResult.hasStaticProps) {
ssgPages.add(page)
isSsg = true
isSSG = true
if (
workerResult.prerenderRoutes &&
......@@ -1729,7 +1741,7 @@ export default async function build(
// This is a static server component page that doesn't have
// gSP or gSSP. We still treat it as a SSG page.
ssgPages.add(page)
isSsg = true
isSSG = true
}
if (hasPages404 && page === '/404') {
......@@ -1772,7 +1784,7 @@ export default async function build(
}
if (pageType === 'app') {
if (isSsg || isStatic) {
if (isSSG || isStatic) {
staticAppPagesCount++
} else {
serverAppPagesCount++
......@@ -1781,10 +1793,11 @@ export default async function build(
}
pageInfos.set(page, {
size: selfSize,
totalSize: allSize,
static: isStatic,
isSsg,
size,
totalSize,
isStatic,
isSSG,
isPPR,
isHybridAmp,
ssgPageRoutes,
initialRevalidateSeconds: false,
......@@ -2191,14 +2204,13 @@ export default async function build(
appConfig.revalidate === 0 ||
exportResult.byPath.get(page)?.revalidate === 0
// TODO: (wyattjoh) maybe change behavior for postpone?
if (hasDynamicData && pageInfos.get(page)?.static) {
if (hasDynamicData && pageInfos.get(page)?.isStatic) {
// 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
pageInfos.set(page, {
...(pageInfos.get(page) as PageInfo),
static: false,
isSsg: false,
isStatic: false,
isSSG: false,
})
}
......@@ -2274,8 +2286,8 @@ export default async function build(
// used dynamic data
pageInfos.set(route, {
...(pageInfos.get(route) as PageInfo),
isSsg: false,
static: false,
isSSG: false,
isStatic: false,
})
}
})
......
import type { NextConfig, NextConfigComplete } from '../server/config-shared'
import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
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 {
Redirect,
......@@ -9,13 +14,13 @@ import type {
Header,
CustomRoutes,
} from '../lib/load-custom-routes'
import type { UnwrapPromise } from '../lib/coalesced-function'
import type {
EdgeFunctionDefinition,
MiddlewareManifest,
} from './webpack/plugins/middleware-plugin'
import type { WebpackLayerName } from '../lib/constants'
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/node-polyfill-crypto'
......@@ -65,6 +70,7 @@ import * as ciEnvironment from '../telemetry/ci-info'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { denormalizeAppPagePath } from '../shared/lib/page-path/denormalize-app-path'
import { AppRouteRouteModule } from '../server/future/route-modules/app-route/module.compiled'
import { RouteKind } from '../server/future/route-kind'
export type ROUTER_TYPE = 'pages' | 'app'
......@@ -323,8 +329,9 @@ export interface PageInfo {
isHybridAmp?: boolean
size: number
totalSize: number
static: boolean
isSsg: boolean
isStatic: boolean
isSSG: boolean
isPPR: boolean
ssgPageRoutes: string[] | null
initialRevalidateSeconds: number | false
pageDuration: number | undefined
......@@ -335,7 +342,7 @@ export interface PageInfo {
export async function printTreeView(
lists: {
pages: ReadonlyArray<string>
app?: ReadonlyArray<string>
app: ReadonlyArray<string> | undefined
},
pageInfos: Map<string, PageInfo>,
{
......@@ -446,12 +453,14 @@ export async function printTreeView(
const symbol =
item === '/_app' || item === '/_app.server'
? ' '
: pageInfo?.static
? '○'
: pageInfo?.isSsg
? '●'
: isEdgeRuntime(pageInfo?.runtime)
? 'ℇ'
: pageInfo?.isPPR
? '◐'
: pageInfo?.isStatic
? '○'
: pageInfo?.isSSG
? '●'
: 'λ'
usedSymbols.add(symbol)
......@@ -620,9 +629,9 @@ export async function printTreeView(
}
pageInfos.set('/404', {
...(pageInfos.get('/404') || pageInfos.get('/_error')),
static: useStaticPages404,
} as any)
...(pageInfos.get('/404') || pageInfos.get('/_error'))!,
isStatic: useStaticPages404,
})
// 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')) {
......@@ -658,6 +667,11 @@ export async function printTreeView(
print(
textTable(
[
usedSymbols.has('◐') && [
'◐',
'(Partially Pre-Rendered)',
'static parts of the page were pre-rendered and the dynamic parts will be streamed',
],
usedSymbols.has('ℇ') && [
'ℇ',
'(Streaming)',
......@@ -876,13 +890,13 @@ export async function buildStaticPaths({
}: {
page: string
getStaticPaths?: GetStaticPaths
staticPathsResult?: UnwrapPromise<ReturnType<GetStaticPaths>>
staticPathsResult?: GetStaticPathsResult
configFileName: string
locales?: string[]
defaultLocale?: string
appDir?: boolean
}): Promise<
Omit<UnwrapPromise<ReturnType<GetStaticPaths>>, 'paths'> & {
Omit<GetStaticPathsResult, 'paths'> & {
paths: string[]
encodedPaths: string[]
}
......@@ -1208,6 +1222,7 @@ export async function buildAppStaticPaths({
fetchCacheKeyPrefix,
staticGenerationAsyncStorage,
serverHooks,
ppr,
}: {
page: string
configFileName: string
......@@ -1222,6 +1237,7 @@ export async function buildAppStaticPaths({
typeof patchFetch
>[0]['staticGenerationAsyncStorage']
serverHooks: Parameters<typeof patchFetch>[0]['serverHooks']
ppr: boolean
}) {
patchFetch({
staticGenerationAsyncStorage,
......@@ -1265,6 +1281,7 @@ export async function buildAppStaticPaths({
supportsDynamicHTML: true,
isRevalidate: false,
isBot: false,
ppr,
},
},
async () => {
......@@ -1372,6 +1389,7 @@ export async function isPageStatic({
isrFlushToDisk,
maxMemoryCacheSize,
incrementalCacheHandlerPath,
ppr,
}: {
page: string
distDir: string
......@@ -1389,7 +1407,9 @@ export async function isPageStatic({
maxMemoryCacheSize?: number
incrementalCacheHandlerPath?: string
nextConfigOutput: 'standalone' | 'export'
ppr: boolean
}): Promise<{
isPPR?: boolean
isStatic?: boolean
isAmpOnly?: boolean
isHybridAmp?: boolean
......@@ -1458,17 +1478,17 @@ export async function isPageStatic({
})
}
const Comp = componentsResult.Component || {}
let staticPathsResult:
| UnwrapPromise<ReturnType<GetStaticPaths>>
| undefined
let staticPathsResult: GetStaticPathsResult | undefined
const routeModule: RouteModule =
componentsResult.ComponentMod?.routeModule
if (pageType === 'app') {
const ComponentMod: AppPageModule = componentsResult.ComponentMod
isClientComponent = isClientReference(componentsResult.ComponentMod)
const { tree, staticGenerationAsyncStorage, serverHooks, routeModule } =
ComponentMod
const { tree, staticGenerationAsyncStorage, serverHooks } = ComponentMod
const generateParams: GenerateParams =
routeModule && AppRouteRouteModule.is(routeModule)
......@@ -1550,6 +1570,7 @@ export async function isPageStatic({
isrFlushToDisk,
maxMemoryCacheSize,
incrementalCacheHandlerPath,
ppr,
}))
}
} else {
......@@ -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 {
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps,
isStatic,
isPPR,
isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true,
prerenderRoutes,
......
......@@ -28,10 +28,12 @@ import { urlToUrlWithoutFlightMarker } from '../app-router'
import { callServer } from '../../app-call-server'
import { PrefetchKind } from './router-reducer-types'
import { hexHash } from '../../../shared/lib/hash'
import { NEXT_DID_POSTPONE_HEADER } from '../../../lib/constants'
export type FetchServerResponseResult = [
flightData: FlightData,
canonicalUrlOverride: URL | undefined
canonicalUrlOverride: URL | undefined,
postponed?: boolean
]
function doMpaNavigation(url: string): FetchServerResponseResult {
......@@ -109,6 +111,7 @@ export async function fetchServerResponse(
const canonicalUrl = res.redirected ? responseUrl : undefined
const contentType = res.headers.get('content-type') || ''
const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)
let isFlightResponse = contentType === RSC_CONTENT_TYPE_HEADER
if (process.env.NODE_ENV === 'production') {
......@@ -142,7 +145,7 @@ export async function fetchServerResponse(
return doMpaNavigation(res.url)
}
return [flightData, canonicalUrl]
return [flightData, canonicalUrl, postponed]
} catch (err) {
console.error(
`Failed to fetch RSC payload for ${url}. Falling back to browser navigation.`,
......
......@@ -249,7 +249,7 @@ export function navigateReducer(
prefetchQueue.bump(data!)
// 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
if (!prefetchValues.lastUsedTime) {
......@@ -300,13 +300,17 @@ export function navigateReducer(
return handleExternalUrl(state, mutable, href, pendingPush)
}
let applied = applyFlightData(
currentCache,
cache,
flightDataPath,
prefetchValues.kind === 'auto' &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
)
// TODO-APP: If the prefetch was postponed, we don't want to apply it
// until we land router changes to handle the postponed case.
let applied = postponed
? false
: applyFlightData(
currentCache,
cache,
flightDataPath,
prefetchValues.kind === 'auto' &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
)
if (
!applied &&
......
......@@ -42,6 +42,10 @@ export interface StaticGenerationStore {
fetchMetrics?: FetchMetrics
isDraftMode?: boolean
readonly experimental: {
readonly ppr: boolean
}
}
export type StaticGenerationAsyncStorage =
......
......@@ -36,7 +36,7 @@ export const staticGenerationBailout: StaticGenerationBailout = (
)
}
if (staticGenerationStore) {
if (staticGenerationStore && !staticGenerationStore?.experimental.ppr) {
staticGenerationStore.revalidate = 0
if (!opts?.dynamic) {
......@@ -47,14 +47,24 @@ export const staticGenerationBailout: StaticGenerationBailout = (
}
if (staticGenerationStore?.isStaticGeneration) {
const err = new DynamicServerError(
formatErrorMessage(reason, {
...opts,
// 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
link: 'https://nextjs.org/docs/messages/dynamic-server-error',
})
)
const message = formatErrorMessage(reason, {
...opts,
// 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
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.dynamicUsageStack = err.stack
......
......@@ -7,4 +7,6 @@ export const isDynamicUsageError = (err: any) =>
err.digest === DYNAMIC_ERROR_CODE ||
isNotFoundError(err) ||
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(
: {}),
strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId,
ppr: nextConfig.experimental.ppr === true,
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......
......@@ -2,6 +2,7 @@ import type { ExportRouteResult, FileWriter } from '../types'
import type { RenderOpts } from '../../server/app-render/types'
import type { OutgoingHttpHeaders } from 'http'
import type { NextParsedUrlQuery } from '../../server/request-meta'
import type { RouteMetadata } from './types'
import type {
MockedRequest,
......@@ -105,6 +106,7 @@ export async function exportAppPage(
const { metadata } = result
const flightData = metadata.pageData
const revalidate = metadata.revalidate ?? false
const postponed = metadata.postponed
if (revalidate === 0) {
if (isDynamicError) {
......@@ -158,11 +160,11 @@ export async function exportAppPage(
)
// Writing the request metadata to a file.
const meta = { headers }
const meta: RouteMetadata = { status: undefined, headers, postponed }
await fileWriter(
ExportedAppPageFiles.META,
htmlFilepath.replace(/\.html$/, '.meta'),
JSON.stringify(meta)
JSON.stringify(meta, null, 2)
)
// Writing the RSC payload to a file.
......
......@@ -60,6 +60,7 @@ export async function exportAppRoute(
notFoundRoutes: [],
},
renderOpts: {
ppr: false,
originalPathname: page,
nextExport: true,
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'
export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
'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_SOFT_TAGS_HEADER = 'x-next-cache-soft-tags'
export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'
......
......@@ -5,8 +5,9 @@ import { isNotFoundError } from '../../client/components/not-found'
import { isRedirectError } from '../../client/components/redirect'
import { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error'
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.
......@@ -31,7 +32,7 @@ export function createErrorHandler({
capturedErrors: Error[]
allCapturedErrors?: Error[]
}): ErrorHandler {
return (err: any): string => {
return (err) => {
if (allCapturedErrors) allCapturedErrors.push(err)
if (
......@@ -44,6 +45,9 @@ export function createErrorHandler({
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
if (dev) {
formatServerError(err)
......
......@@ -6,24 +6,29 @@ import type { createErrorHandler } from './create-error-handler'
import React, { use } from 'react'
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.
* This is only used for renderToHTML, the Flight response does not need additional wrappers.
*/
export function createServerComponentRenderer<Props>(
ComponentToRender: (props: Props) => any,
ComponentMod: AppPageModule,
{
ComponentMod,
inlinedDataTransformStream,
clientReferenceManifest,
formState,
}: {
inlinedDataTransformStream: TransformStream<Uint8Array, Uint8Array>
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
formState: null | any
},
serverComponentsErrorHandler: ReturnType<typeof createErrorHandler>,
nonce?: string
nonce,
serverComponentsErrorHandler,
}: ServerComponentRendererOptions
): (props: Props) => JSX.Element {
let flightStream: ReadableStream<Uint8Array>
const createFlightStream = (props: Props) => {
......
......@@ -5,28 +5,29 @@ import {
isRedirectError,
} from '../../client/components/redirect'
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({
polyfills,
renderServerInsertedHTML,
hasPostponed,
}: {
polyfills: JSX.IntrinsicElements['script'][]
renderServerInsertedHTML: () => React.ReactNode
hasPostponed: boolean
}) {
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
// flushed.
const errorMetaTags = []
for (
;
flushedErrorMetaTagsUntilIndex < serverCapturedErrors.length;
flushedErrorMetaTagsUntilIndex++
) {
while (flushedErrorMetaTagsUntilIndex < serverCapturedErrors.length) {
const error = serverCapturedErrors[flushedErrorMetaTagsUntilIndex]
flushedErrorMetaTagsUntilIndex++
if (isNotFoundError(error)) {
errorMetaTags.push(
......@@ -51,21 +52,24 @@ export function makeGetServerInsertedHTML({
}
}
const flushed = renderToString({
ReactDOMServer: require('react-dom/server.edge'),
element: (
<>
{polyfillsFlushed
? null
: polyfills?.map((polyfill) => {
return <script key={polyfill.src} {...polyfill} />
})}
{renderServerInsertedHTML()}
{errorMetaTags}
</>
),
})
polyfillsFlushed = true
return flushed
const stream = await renderToReadableStream(
<>
{/* Insert the polyfills if they haven't been flushed yet. */}
{!polyfillsFlushed &&
polyfills?.map((polyfill) => {
return <script key={polyfill.src} {...polyfill} />
})}
{renderServerInsertedHTML()}
{errorMetaTags}
</>
)
// Mark polyfills as flushed so they don't get flushed again.
if (!polyfillsFlushed) polyfillsFlushed = true
// 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 {
serverActionsBodySizeLimit?: SizeLimit
params?: ParsedUrlQuery
isPrefetch?: boolean
ppr: boolean
postponed?: string
}
export type RenderOpts = LoadComponentsReturnType<AppPageModule> &
......
......@@ -12,12 +12,12 @@ export type StaticGenerationContext = {
isRevalidate?: boolean
isOnDemandRevalidate?: boolean
isBot?: boolean
isPrefetch?: boolean
nextExport?: boolean
fetchCache?: StaticGenerationStore['fetchCache']
isDraftMode?: boolean
isServerAction?: boolean
waitUntil?: Promise<any>
ppr: boolean
/**
* A hack around accessing the store value outside the context of the
......@@ -76,6 +76,9 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
isDraftMode: renderOpts.isDraftMode,
experimental: {
ppr: renderOpts.ppr,
},
}
// TODO: remove this when we resolve accessing the store outside the execution context
......
......@@ -109,6 +109,7 @@ import {
import {
CACHE_ONE_YEAR,
NEXT_CACHE_TAGS_HEADER,
NEXT_DID_POSTPONE_HEADER,
NEXT_QUERY_PARAM_PREFIX,
} from '../lib/constants'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
......@@ -246,6 +247,7 @@ type BaseRenderOpts = {
appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean
isExperimentalCompile?: boolean
ppr: boolean
}
export interface BaseRequestHandler {
......@@ -504,6 +506,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// @ts-expect-error internal field not publicly exposed
isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,
ppr: this.nextConfig.experimental.ppr === true,
}
// Initialize next/config with the environment configuration
......@@ -1684,6 +1687,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) &&
(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
// resolve to a static data route we bail early to avoid
// unexpected SSR invocations
......@@ -1962,10 +1972,12 @@ export default abstract class Server<ServerOptions extends Options = Options> {
| '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.
const supportsDynamicHTML =
(!isDataReq && opts.dev) || !(isSSG || hasStaticPaths)
(!isDataReq && opts.dev) || !(isSSG || hasStaticPaths) || !!postponed
let headers: OutgoingHttpHeaders | undefined
......@@ -2021,6 +2033,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
isOnDemandRevalidate,
isDraftMode: isPreviewMode,
isServerAction,
postponed,
}
// 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> {
params: opts.params,
prerenderManifest,
renderOpts: {
// App Route's cannot postpone, so don't enable it.
ppr: false,
originalPathname: components.ComponentMod.originalPathname,
supportsDynamicHTML,
incrementalCache,
......@@ -2123,12 +2138,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} else if (
components.routeModule?.definition.kind === RouteKind.APP_PAGE
) {
const isAppPrefetch = req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()]
if (isAppPrefetch && process.env.NODE_ENV === 'production') {
try {
const prefetchRsc = await this.getPrefetchRsc(resolvedUrlPathname)
if (prefetchRsc) {
res.setHeader(
'cache-control',
......@@ -2138,9 +2150,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
res.body(prefetchRsc).send()
return null
}
} catch (_) {
// we fallback to invoking the function if prefetch
// data is not available
} catch {
// We fallback to invoking the function if prefetch data is not
// available.
}
}
......@@ -2243,6 +2255,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
kind: 'PAGE',
html: result,
pageData: metadata.pageData,
postponed: metadata.postponed,
headers,
status: isAppPath ? res.statusCode : undefined,
},
......@@ -2351,10 +2364,14 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const html = await this.getFallback(
locale ? `/${locale}${pathname}` : pathname
)
return {
value: {
kind: 'PAGE',
html: RenderResult.fromStatic(html),
postponed: undefined,
status: undefined,
headers: undefined,
pageData: {},
},
}
......@@ -2523,11 +2540,76 @@ export default abstract class Server<ServerOptions extends Options = Options> {
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 {
type: isDataReq ? 'rsc' : 'html',
body: isDataReq
? RenderResult.fromStatic(cachedData.pageData as string)
: cachedData.html,
type: 'html',
body,
revalidate: cacheEntry.revalidate,
}
}
......
......@@ -668,6 +668,7 @@ export default class DevServer extends Server {
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize,
ppr: this.nextConfig.experimental.ppr === true,
})
return pathsResult
} finally {
......
......@@ -18,7 +18,11 @@ import { staticGenerationAsyncStorage } from '../../client/components/static-gen
const { AppRouteRouteModule } =
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
// side-effects aren't relied on in dev that will break
......@@ -37,6 +41,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize,
requestHeaders,
incrementalCacheHandlerPath,
ppr,
}: {
distDir: string
pathname: string
......@@ -51,6 +56,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders']
incrementalCacheHandlerPath?: string
ppr: boolean
}): Promise<{
paths?: string[]
encodedPaths?: string[]
......@@ -106,6 +112,7 @@ export async function loadStaticPaths({
isrFlushToDisk,
fetchCacheKeyPrefix,
maxMemoryCacheSize,
ppr,
})
}
......
import type { OutgoingHttpHeaders } from 'http'
import type { RouteMetadata } from '../../../export/routes/types'
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
import type { CacheFs } from '../../../shared/lib/utils'
import type { CachedFetchValue } from '../../response-cache'
......@@ -197,7 +197,7 @@ export default class FileSystemCache implements CacheHandler {
)
)
let meta: { status?: number; headers?: OutgoingHttpHeaders } = {}
let meta: RouteMetadata | undefined
if (isAppPath) {
try {
......@@ -216,8 +216,9 @@ export default class FileSystemCache implements CacheHandler {
kind: 'PAGE',
html: fileData,
pageData,
headers: meta.headers,
status: meta.status,
postponed: meta?.postponed,
headers: meta?.headers,
status: meta?.status,
},
}
}
......@@ -281,7 +282,7 @@ export default class FileSystemCache implements CacheHandler {
}
}
return data || null
return data ?? null
}
public async set(
......@@ -304,9 +305,16 @@ export default class FileSystemCache implements CacheHandler {
})
await this.fs.mkdir(path.dirname(filePath))
await this.fs.writeFile(filePath, data.body)
const meta: RouteMetadata = {
headers: data.headers,
status: data.status,
postponed: undefined,
}
await this.fs.writeFile(
filePath.replace(/\.body$/, '.meta'),
JSON.stringify({ headers: data.headers, status: data.status })
JSON.stringify(meta, null, 2)
)
return
}
......@@ -331,12 +339,15 @@ export default class FileSystemCache implements CacheHandler {
)
if (data.headers || data.status) {
const meta: RouteMetadata = {
headers: data.headers,
status: data.status,
postponed: data.postponed,
}
await this.fs.writeFile(
htmlPath.replace(/\.html$/, '.meta'),
JSON.stringify({
headers: data.headers,
status: data.status,
})
JSON.stringify(meta)
)
}
} else if (data?.kind === 'FETCH') {
......
......@@ -2,7 +2,11 @@ import type { ServerResponse } from 'http'
import type { StaticGenerationStore } from '../client/components/static-generation-async-storage.external'
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'
type ContentTypeOption = string | undefined
......@@ -17,9 +21,14 @@ export type RenderResultMetadata = {
fetchMetrics?: StaticGenerationStore['fetchMetrics']
fetchTags?: string
waitUntil?: Promise<any>
postponed?: string
}
type RenderResultResponse = ReadableStream<Uint8Array> | string | null
type RenderResultResponse =
| ReadableStream<Uint8Array>[]
| ReadableStream<Uint8Array>
| string
| null
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
* already sent.
*/
private readonly response: RenderResultResponse
private response: RenderResultResponse
/**
* Creates a new RenderResult instance from a static response.
......@@ -111,7 +120,7 @@ export default class RenderResult {
)
}
return streamToString(this.response)
return streamToString(this.readable)
}
return this.response
......@@ -129,9 +138,44 @@ export default class RenderResult {
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
}
/**
* 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
* writable stream if an error is encountered.
......
......@@ -1327,18 +1327,17 @@ export async function renderToHTMLImpl(
const createBodyResult = getTracer().wrap(
RenderSpan.createBodyResult,
(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, {
suffix,
inlinedDataStream: serverComponentsInlinedTransformStream?.readable,
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,
validateRootLayout: undefined,
})
}
)
......@@ -1553,16 +1552,18 @@ export async function renderToHTMLImpl(
prefix += '<!-- __NEXT_DATA__ -->'
}
const streams = [
streamFromString(prefix),
await documentResult.bodyResult(renderTargetSuffix),
]
const content = await streamToString(
chainStreams(
streamFromString(prefix),
await documentResult.bodyResult(renderTargetSuffix)
)
)
const postOptimize = (html: string) =>
postProcessHTML(pathname, html, renderOpts, { inAmpMode, hybridAmp })
const optimizedHtml = await postProcessHTML(pathname, content, renderOpts, {
inAmpMode,
hybridAmp,
})
const html = await streamToString(chainStreams(streams))
const optimizedHtml = await postOptimize(html)
return new RenderResult(optimizedHtml, renderResultMeta)
}
......
......@@ -93,6 +93,7 @@ export default class ResponseCache {
kind: 'PAGE',
html: RenderResult.fromStatic(cachedResponse.value.html),
pageData: cachedResponse.value.pageData,
postponed: cachedResponse.value.postponed,
headers: cachedResponse.value.headers,
status: cachedResponse.value.status,
}
......@@ -137,6 +138,7 @@ export default class ResponseCache {
? {
kind: 'PAGE',
html: cacheEntry.value.html.toUnchunkedString(),
postponed: cacheEntry.value.postponed,
pageData: cacheEntry.value.pageData,
headers: cacheEntry.value.headers,
status: cacheEntry.value.status,
......
......@@ -38,9 +38,10 @@ interface CachedPageValue {
// this needs to be a RenderResult so since renderResponse
// expects that type instead of a string
html: RenderResult
postponed: string | undefined
pageData: Object
status?: number
headers?: OutgoingHttpHeaders
status: number | undefined
headers: OutgoingHttpHeaders | undefined
}
export interface CachedRouteValue {
......@@ -67,8 +68,9 @@ interface IncrementalCachedPageValue {
// the string value
html: string
pageData: Object
headers?: OutgoingHttpHeaders
status?: number
postponed: string | undefined
headers: OutgoingHttpHeaders | undefined
status: number | undefined
}
export type IncrementalCacheEntry = {
......
import type { FlightRouterState } from '../app-render/types'
import { nonNullable } from '../../lib/non-nullable'
import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants'
import { createDecodeTransformStream } from './encode-decode'
......@@ -31,7 +30,7 @@ export function cloneTransformStream(source: TransformStream) {
}
export function chainStreams<T>(
streams: ReadableStream<T>[]
...streams: ReadableStream<T>[]
): ReadableStream<T> {
const { readable, writable } = new TransformStream()
......@@ -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(
renderStream: ReactReadableStream,
{
......@@ -437,29 +466,20 @@ export async function continueFizzStream(
getServerInsertedHTML,
serverInsertedHTMLToHead,
validateRootLayout,
}: {
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
}
}: ContinueStreamOptions
): Promise<ReadableStream<Uint8Array>> {
const closeTag = '</body></html>'
// Suffix itself might contain close tags at the end, so we need to split it.
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
}
const transforms: Array<TransformStream<Uint8Array, Uint8Array>> = [
return chainTransformers(renderStream, [
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
......@@ -477,7 +497,7 @@ export async function continueFizzStream(
inlinedDataStream ? createMergedTransformStream(inlinedDataStream) : null,
// Close tags should always be deferred to the end
closeTag && createMoveSuffixStream(closeTag),
createMoveSuffixStream(closeTag),
// Special head insertions
// TODO-APP: Insert server side html to end of head in app layout rendering, to avoid
......@@ -492,10 +512,47 @@ export async function continueFizzStream(
validateRootLayout.getTree
)
: null,
].filter(nonNullable)
])
}
return transforms.reduce(
(readable, transform) => readable.pipeThrough(transform),
renderStream
)
type ContinuePostponedStreamOptions = Pick<
ContinueStreamOptions,
| '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 {
},
renderOpts: {
supportsDynamicHTML: true,
// App Route's cannot be postponed.
ppr: false,
},
}
......
......@@ -53,8 +53,11 @@ export function unstable_cache<T extends Callback>(
...store,
fetchCache: 'only-no-store',
urlPathname: store?.urlPathname || '/',
isStaticGeneration: !!store?.isStaticGeneration,
isUnstableCacheCallback: true,
isStaticGeneration: store?.isStaticGeneration === true,
experimental: {
ppr: store?.experimental?.ppr === true,
},
},
async () => {
const tags = validateTags(
......
......@@ -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/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_USERLAND'
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 = '') {
'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.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.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`,
......
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