Unverified Commit cdb41545 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

[PPR] Enable incremental adoption (#63847)

Enabling Partial Prerendering (PPR) for an entire application is
ideally, the goal for teams wanting to test out the feature or adopt it
in their applications to get ready for when it becomes the default
rendering pattern. For large applications, with many routes the new
behaviours of old API's may prove a difficult pill to swallow all at
once.

This aims to enable incremental adoption of PPR for pages and routes
that want to support it in a similar way to how existing segment-level
configurations. Segments can now add:

```ts
export const experimental_ppr = true
```

To enable PPR for that segment and those descending segments. Any subset
of those routes that have it enabled can add:

```ts
export const experimental_ppr = false
```

<details>
<summary>An aside on the choice of <code>experimental_ppr</code>
name</summary>
<blockquote>
<p>It is against common JS semantics to use snake-case, and preference
is given to camel-case instead. The choice to make this snake-case was
to re-enforce that this is an experimental feature, an ugly incremental
path, and ideally, developers should aim to remove all references of it
from their codebase.</p>
<p>Additionally, this mirrors what we've done for unstable API's like
`unstable_cache`.</p>
</blockquote>
</details> 

To disable PPR for that segment and those descending segments. To use
this new option, the `experimental.ppr` configuration in
`next.config.js` must be set to `"incremental"`:

```js
// next.config.js
module.exports = {
  experimental: {
    ppr: "incremental",
  },
} 
```

If a segment does not export a `experimental_ppr` boolean, it is
inferred from it's parent. If no parent has it defined, it's default
value is `false` and therefore disabled.

Once all your segments have PPR enabled via this config, it would be
considered safe for teams to set their `experimental.ppr` value in the
`next.config.js` to `true`, enabling it for the entire app and for all
future routes.

### Aside

I also took the liberty to rename `isPPR` and `supportsPPR` to be the
clearer `isAppPPREnabled` and `isRoutePPREnabled`.

---------
Co-authored-by: 's avatarHendrik Liebau <mail@hendrik-liebau.de>
parent 53c08431
......@@ -72,6 +72,7 @@ pub struct NextSegmentConfig {
pub fetch_cache: Option<NextSegmentFetchCache>,
pub runtime: Option<NextRuntime>,
pub preferred_region: Option<Vec<String>>,
pub experimental_ppr: Option<bool>,
}
#[turbo_tasks::value_impl]
......@@ -93,6 +94,7 @@ impl NextSegmentConfig {
fetch_cache,
runtime,
preferred_region,
experimental_ppr,
} = self;
*dynamic = dynamic.or(parent.dynamic);
*dynamic_params = dynamic_params.or(parent.dynamic_params);
......@@ -100,6 +102,7 @@ impl NextSegmentConfig {
*fetch_cache = fetch_cache.or(parent.fetch_cache);
*runtime = runtime.or(parent.runtime);
*preferred_region = preferred_region.take().or(parent.preferred_region.clone());
*experimental_ppr = experimental_ppr.or(parent.experimental_ppr);
}
/// Applies a config from a paralllel route to this config, returning an
......@@ -133,6 +136,7 @@ impl NextSegmentConfig {
fetch_cache,
runtime,
preferred_region,
experimental_ppr,
} = self;
merge_parallel(dynamic, &parallel_config.dynamic, "dynamic")?;
merge_parallel(
......@@ -148,6 +152,11 @@ impl NextSegmentConfig {
&parallel_config.preferred_region,
"referredRegion",
)?;
merge_parallel(
experimental_ppr,
&parallel_config.experimental_ppr,
"experimental_ppr",
)?;
Ok(())
}
}
......@@ -422,6 +431,15 @@ fn parse_config_value(
config.preferred_region = Some(preferred_region);
}
"experimental_ppr" => {
let value = eval_context.eval(init);
let Some(val) = value.as_bool() else {
invalid_config("`experimental_ppr` needs to be a static boolean", &value);
return;
};
config.experimental_ppr = Some(val);
}
_ => {}
}
}
......
......@@ -520,7 +520,7 @@ pub struct ExperimentalConfig {
output_file_tracing_root: Option<String>,
/// Using this feature will enable the `react@experimental` for the `app`
/// directory.
ppr: Option<bool>,
ppr: Option<ExperimentalPartialPrerendering>,
taint: Option<bool>,
proxy_timeout: Option<f64>,
/// enables the minification of server code.
......@@ -542,6 +542,49 @@ pub struct ExperimentalConfig {
worker_threads: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
#[serde(rename_all = "lowercase")]
pub enum ExperimentalPartialPrerenderingIncrementalValue {
Incremental,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)]
#[serde(untagged)]
pub enum ExperimentalPartialPrerendering {
Incremental(ExperimentalPartialPrerenderingIncrementalValue),
Boolean(bool),
}
#[test]
fn test_parse_experimental_partial_prerendering() {
let json = serde_json::json!({
"ppr": "incremental"
});
let config: ExperimentalConfig = serde_json::from_value(json).unwrap();
assert_eq!(
config.ppr,
Some(ExperimentalPartialPrerendering::Incremental(
ExperimentalPartialPrerenderingIncrementalValue::Incremental
))
);
let json = serde_json::json!({
"ppr": true
});
let config: ExperimentalConfig = serde_json::from_value(json).unwrap();
assert_eq!(
config.ppr,
Some(ExperimentalPartialPrerendering::Boolean(true))
);
// Expect if we provide a random string, it will fail.
let json = serde_json::json!({
"ppr": "random"
});
let config = serde_json::from_value::<ExperimentalConfig>(json);
assert!(config.is_err());
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")]
pub struct SubResourceIntegrity {
......@@ -572,6 +615,25 @@ pub enum EsmExternals {
Bool(bool),
}
// Test for esm externals deserialization.
#[test]
fn test_esm_externals_deserialization() {
let json = serde_json::json!({
"esmExternals": true
});
let config: ExperimentalConfig = serde_json::from_value(json).unwrap();
assert_eq!(config.esm_externals, Some(EsmExternals::Bool(true)));
let json = serde_json::json!({
"esmExternals": "loose"
});
let config: ExperimentalConfig = serde_json::from_value(json).unwrap();
assert_eq!(
config.esm_externals,
Some(EsmExternals::Loose(EsmExternalsValue::Loose))
);
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")]
pub struct ServerActions {
......@@ -934,7 +996,19 @@ impl NextConfig {
#[turbo_tasks::function]
pub async fn enable_ppr(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(self.await?.experimental.ppr.unwrap_or(false)))
Ok(Vc::cell(
self.await?
.experimental
.ppr
.as_ref()
.map(|ppr| match ppr {
ExperimentalPartialPrerendering::Incremental(
ExperimentalPartialPrerenderingIncrementalValue::Incremental,
) => true,
ExperimentalPartialPrerendering::Boolean(b) => *b,
})
.unwrap_or(false),
))
}
#[turbo_tasks::function]
......
......@@ -314,7 +314,7 @@ async function tryToReadFile(filePath: string, shouldThrow: boolean) {
export function getMiddlewareMatchers(
matcherOrMatchers: unknown,
nextConfig: NextConfig
nextConfig: Pick<NextConfig, 'basePath' | 'i18n'>
): MiddlewareMatcher[] {
let matchers: unknown[] = []
if (Array.isArray(matcherOrMatchers)) {
......
......@@ -187,6 +187,10 @@ import { traceMemoryUsage } from '../lib/memory/trace'
import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import uploadTrace from '../trace/upload-trace'
import {
checkIsAppPPREnabled,
checkIsRoutePPREnabled,
} from '../server/lib/experimental/ppr'
interface ExperimentalBypassForInfo {
experimentalBypassFor?: RouteHas[]
......@@ -1740,7 +1744,6 @@ export default async function build(
const additionalSsgPaths = new Map<string, Array<string>>()
const additionalSsgPathsEncoded = new Map<string, Array<string>>()
const appStaticPaths = new Map<string, Array<string>>()
const appPrefetchPaths = new Map<string, string>()
const appStaticPathsEncoded = new Map<string, Array<string>>()
const appNormalizedPaths = new Map<string, string>()
const appDynamicParamPaths = new Set<string>()
......@@ -1808,7 +1811,7 @@ export default async function build(
minimalMode: ciEnvironment.hasNextSupport,
allowedRevalidateHeaderKeys:
config.experimental.allowedRevalidateHeaderKeys,
experimental: { ppr: config.experimental.ppr === true },
isAppPPREnabled: checkIsAppPPREnabled(config.experimental.ppr),
})
incrementalCacheIpcPort = cacheInitialization.ipcPort
......@@ -1886,7 +1889,7 @@ export default async function build(
locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output,
ppr: config.experimental.ppr === true,
pprConfig: config.experimental.ppr,
})
)
......@@ -1984,7 +1987,7 @@ export default async function build(
computedManifestData
)
let isPPR = false
let isRoutePPREnabled = false
let isSSG = false
let isStatic = false
let isServerComponent = false
......@@ -2099,7 +2102,7 @@ export default async function build(
: config.experimental.isrFlushToDisk,
maxMemoryCacheSize: config.cacheMaxMemorySize,
nextConfigOutput: config.output,
ppr: config.experimental.ppr === true,
pprConfig: config.experimental.ppr,
})
}
)
......@@ -2118,8 +2121,8 @@ export default async function build(
// If this route can be partially pre-rendered, then
// mark it as such and mark that it can be
// generated server-side.
if (workerResult.isPPR) {
isPPR = workerResult.isPPR
if (workerResult.isRoutePPREnabled) {
isRoutePPREnabled = workerResult.isRoutePPREnabled
isSSG = true
isStatic = true
......@@ -2174,7 +2177,6 @@ export default async function build(
])
isStatic = true
} else if (
isDynamic &&
!hasGenerateStaticParams &&
(appConfig.dynamic === 'error' ||
appConfig.dynamic === 'force-static')
......@@ -2182,7 +2184,7 @@ export default async function build(
appStaticPaths.set(originalAppPath, [])
appStaticPathsEncoded.set(originalAppPath, [])
isStatic = true
isPPR = false
isRoutePPREnabled = false
}
}
}
......@@ -2193,18 +2195,6 @@ export default async function build(
appDynamicParamPaths.add(originalAppPath)
}
appDefaultConfigs.set(originalAppPath, appConfig)
// Only generate the app prefetch rsc if the route is
// an app page.
if (
!isStatic &&
!isAppRouteRoute(originalAppPath) &&
!isDynamicRoute(originalAppPath) &&
!isPPR &&
!isInterceptionRoute
) {
appPrefetchPaths.set(originalAppPath, page)
}
}
} else {
if (isEdgeRuntime(pageRuntime)) {
......@@ -2328,7 +2318,7 @@ export default async function build(
totalSize,
isStatic,
isSSG,
isPPR,
isRoutePPREnabled,
isHybridAmp,
ssgPageRoutes,
initialRevalidateSeconds: false,
......@@ -2623,34 +2613,24 @@ export default async function build(
// revalidate periods and dynamicParams settings
appStaticPaths.forEach((routes, originalAppPath) => {
const encodedRoutes = appStaticPathsEncoded.get(originalAppPath)
const appConfig = appDefaultConfigs.get(originalAppPath) || {}
const appConfig = appDefaultConfigs.get(originalAppPath)
routes.forEach((route, routeIdx) => {
defaultMap[route] = {
page: originalAppPath,
query: { __nextSsgPath: encodedRoutes?.[routeIdx] },
_isDynamicError: appConfig.dynamic === 'error',
_isDynamicError: appConfig?.dynamic === 'error',
_isAppDir: true,
_isRoutePPREnabled: appConfig
? checkIsRoutePPREnabled(
config.experimental.ppr,
appConfig
)
: undefined,
}
})
})
// Ensure we don't generate explicit app prefetches while in PPR.
if (config.experimental.ppr && appPrefetchPaths.size > 0) {
throw new Error(
"Invariant: explicit app prefetches shouldn't generated with PPR"
)
}
for (const [originalAppPath, page] of appPrefetchPaths) {
defaultMap[page] = {
page: originalAppPath,
query: {},
_isAppDir: true,
_isAppPrefetch: true,
}
}
if (i18n) {
for (const page of [
...staticPages,
......@@ -2682,6 +2662,7 @@ export default async function build(
}
}
}
return defaultMap
},
}
......@@ -2752,8 +2733,9 @@ export default async function build(
// When this is an app page and PPR is enabled, the route supports
// partial pre-rendering.
const experimentalPPR =
!isRouteHandler && config.experimental.ppr === true
const experimentalPPR: true | undefined =
!isRouteHandler &&
checkIsRoutePPREnabled(config.experimental.ppr, appConfig)
? true
: undefined
......
import type { NextConfig, NextConfigComplete } from '../server/config-shared'
import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr'
import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import type { AssetBinding } from './webpack/loaders/get-module-build-info'
import type {
......@@ -87,6 +88,7 @@ import { interopDefault } from '../lib/interop-default'
import type { PageExtensions } from './page-extensions-type'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import { isInterceptionRouteAppPath } from '../server/future/helpers/interception-routes'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
export type ROUTER_TYPE = 'pages' | 'app'
......@@ -347,7 +349,10 @@ export interface PageInfo {
totalSize: number
isStatic: boolean
isSSG: boolean
isPPR: boolean
/**
* If true, it means that the route has partial prerendering enabled.
*/
isRoutePPREnabled: boolean
ssgPageRoutes: string[] | null
initialRevalidateSeconds: number | false
pageDuration: number | undefined
......@@ -489,7 +494,7 @@ export async function printTreeView(
symbol = ' '
} else if (isEdgeRuntime(pageInfo?.runtime)) {
symbol = 'ƒ'
} else if (pageInfo?.isPPR) {
} else if (pageInfo?.isRoutePPREnabled) {
if (
// If the page has an empty prelude, then it's equivalent to a dynamic page
pageInfo?.hasEmptyPrelude ||
......@@ -1180,6 +1185,13 @@ export type AppConfig = {
dynamic?: AppConfigDynamic
fetchCache?: 'force-cache' | 'only-cache'
preferredRegion?: string
/**
* When true, the page will be served using partial prerendering.
* This setting will only take affect if it's enabled via
* the `experimental.ppr = "incremental"` option.
*/
experimental_ppr?: boolean
}
type Params = Record<string, string | string[]>
......@@ -1197,10 +1209,12 @@ type GenerateParamsResult = {
export type GenerateParamsResults = GenerateParamsResult[]
export const collectAppConfig = (mod: any): AppConfig | undefined => {
const collectAppConfig = (
mod: Partial<AppConfig> | undefined
): AppConfig | undefined => {
let hasConfig = false
const config: AppConfig = {}
if (typeof mod?.revalidate !== 'undefined') {
config.revalidate = mod.revalidate
hasConfig = true
......@@ -1221,8 +1235,14 @@ export const collectAppConfig = (mod: any): AppConfig | undefined => {
config.preferredRegion = mod.preferredRegion
hasConfig = true
}
if (typeof mod?.experimental_ppr !== 'undefined') {
config.experimental_ppr = mod.experimental_ppr
hasConfig = true
}
if (!hasConfig) return undefined
return hasConfig ? config : undefined
return config
}
/**
......@@ -1313,7 +1333,6 @@ export async function buildAppStaticPaths({
requestHeaders,
maxMemoryCacheSize,
fetchCacheKeyPrefix,
ppr,
ComponentMod,
}: {
dir: string
......@@ -1326,7 +1345,6 @@ export async function buildAppStaticPaths({
cacheHandler?: string
maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders']
ppr: boolean
ComponentMod: AppPageModule
}) {
ComponentMod.patchFetch()
......@@ -1361,7 +1379,7 @@ export async function buildAppStaticPaths({
CurCacheHandler: CacheHandler,
requestHeaders,
minimalMode: ciEnvironment.hasNextSupport,
experimental: { ppr },
isAppPPREnabled: false,
})
return StaticGenerationAsyncStorageWrapper.wrap(
......@@ -1373,8 +1391,6 @@ export async function buildAppStaticPaths({
incrementalCache,
supportsDynamicHTML: true,
isRevalidate: false,
// building static paths should never postpone
experimental: { ppr: false },
},
},
async () => {
......@@ -1488,7 +1504,7 @@ export async function isPageStatic({
isrFlushToDisk,
maxMemoryCacheSize,
cacheHandler,
ppr,
pprConfig,
}: {
dir: string
page: string
......@@ -1507,9 +1523,9 @@ export async function isPageStatic({
maxMemoryCacheSize?: number
cacheHandler?: string
nextConfigOutput: 'standalone' | 'export'
ppr: boolean
pprConfig: ExperimentalPPRConfig | undefined
}): Promise<{
isPPR?: boolean
isRoutePPREnabled?: boolean
isStatic?: boolean
isAmpOnly?: boolean
isHybridAmp?: boolean
......@@ -1584,13 +1600,9 @@ export async function isPageStatic({
const routeModule: RouteModule =
componentsResult.ComponentMod?.routeModule
let supportsPPR = false
let isRoutePPREnabled: boolean = false
if (pageType === 'app') {
if (ppr && routeModule.definition.kind === RouteKind.APP_PAGE) {
supportsPPR = true
}
const ComponentMod: AppPageModule = componentsResult.ComponentMod
isClientComponent = isClientReference(componentsResult.ComponentMod)
......@@ -1620,6 +1632,7 @@ export async function isPageStatic({
fetchCache,
preferredRegion,
revalidate: curRevalidate,
experimental_ppr,
} = curGenParams?.config || {}
// TODO: should conflicting configs here throw an error
......@@ -1633,6 +1646,11 @@ export async function isPageStatic({
if (typeof builtConfig.fetchCache === 'undefined') {
builtConfig.fetchCache = fetchCache
}
// If partial prerendering has been set, only override it if the current value is
// provided as it's resolved from root layout to leaf page.
if (typeof experimental_ppr !== 'undefined') {
builtConfig.experimental_ppr = experimental_ppr
}
// any revalidate number overrides false
// shorter revalidate overrides longer (initially)
......@@ -1657,10 +1675,18 @@ export async function isPageStatic({
)
}
// A page supports partial prerendering if it is an app page and either
// the whole app has PPR enabled or this page has PPR enabled when we're
// in incremental mode.
isRoutePPREnabled =
routeModule.definition.kind === RouteKind.APP_PAGE &&
!isInterceptionRouteAppPath(page) &&
checkIsRoutePPREnabled(pprConfig, appConfig)
// If force dynamic was set and we don't have PPR enabled, then set the
// revalidate to 0.
// TODO: (PPR) remove this once PPR is enabled by default
if (appConfig.dynamic === 'force-dynamic' && !supportsPPR) {
if (appConfig.dynamic === 'force-dynamic' && !isRoutePPREnabled) {
appConfig.revalidate = 0
}
......@@ -1679,7 +1705,6 @@ export async function isPageStatic({
isrFlushToDisk,
maxMemoryCacheSize,
cacheHandler,
ppr,
ComponentMod,
}))
}
......@@ -1757,21 +1782,13 @@ export async function isPageStatic({
// When PPR is enabled, any route may be completely static, so
// mark this route as static.
let isPPR = false
if (supportsPPR) {
isPPR = true
if (isRoutePPREnabled) {
isStatic = true
}
// interception routes depend on `Next-URL` and `Next-Router-State-Tree` request headers and thus cannot be prerendered
if (isInterceptionRouteAppPath(page)) {
isStatic = false
isPPR = false
}
return {
isStatic,
isPPR,
isRoutePPREnabled,
isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true,
prerenderRoutes,
......
......@@ -5,6 +5,7 @@ import type {
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { needsExperimentalReact } from '../../../lib/needs-experimental-react'
import { checkIsAppPPREnabled } from '../../../server/lib/experimental/ppr'
function errorIfEnvConflicted(config: NextConfigComplete, key: string) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
......@@ -165,7 +166,7 @@ export function getDefineEnv({
? 'nodejs'
: '',
'process.env.NEXT_MINIMAL': '',
'process.env.__NEXT_PPR': config.experimental.ppr === true,
'process.env.__NEXT_PPR': checkIsAppPPREnabled(config.experimental.ppr),
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',
'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],
......
......@@ -80,6 +80,7 @@ checkFields<Diff<{
generateMetadata?: Function
viewport?: any
generateViewport?: Function
experimental_ppr?: boolean
`
}
}, TEntry, ''>>()
......
......@@ -14,7 +14,7 @@ export async function createIncrementalCache({
distDir,
dir,
enabledDirectories,
experimental,
isAppPPREnabled,
flushToDisk,
}: {
cacheHandler?: string
......@@ -23,7 +23,7 @@ export async function createIncrementalCache({
distDir: string
dir: string
enabledDirectories: NextEnabledDirectories
experimental: { ppr: boolean }
isAppPPREnabled: boolean
flushToDisk?: boolean
}) {
// Custom cache handler overrides.
......@@ -60,7 +60,7 @@ export async function createIncrementalCache({
serverDistDir: path.join(distDir, 'server'),
CurCacheHandler: CacheHandler,
minimalMode: hasNextSupport,
experimental,
isAppPPREnabled,
})
;(globalThis as any).__incrementalCache = incrementalCache
......
......@@ -57,6 +57,7 @@ import { validateRevalidate } from '../server/lib/patch-fetch'
import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace'
import { createProgress } from '../build/progress'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { checkIsAppPPREnabled } from '../server/lib/experimental/ppr'
export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR'
......@@ -422,7 +423,7 @@ export async function exportAppImpl(
strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.deploymentId,
experimental: {
ppr: nextConfig.experimental.ppr === true,
isAppPPREnabled: checkIsAppPPREnabled(nextConfig.experimental.ppr),
missingSuspenseWithCSRBailout:
nextConfig.experimental.missingSuspenseWithCSRBailout === true,
swrDelta: nextConfig.experimental.swrDelta,
......
......@@ -64,7 +64,7 @@ export async function exportAppPage(
const { flightData, revalidate = false, postponed, fetchTags } = metadata
// Ensure we don't postpone without having PPR enabled.
if (postponed && !renderOpts.experimental.ppr) {
if (postponed && !renderOpts.experimental.isRoutePPREnabled) {
throw new Error('Invariant: page postponed without PPR being enabled')
}
......@@ -93,8 +93,9 @@ export async function exportAppPage(
}
// If PPR is enabled, we want to emit a prefetch rsc file for the page
// instead of the standard rsc. This is because the standard rsc will
// contain the dynamic data.
else if (renderOpts.experimental.ppr) {
// contain the dynamic data. We do this if any routes have PPR enabled so
// that the cache read/write is the same.
else if (renderOpts.experimental.isAppPPREnabled) {
// If PPR is enabled, we should emit the flight data as the prefetch
// payload.
await fileWriter(
......@@ -113,12 +114,6 @@ export async function exportAppPage(
const headers: OutgoingHttpHeaders = { ...metadata.headers }
// When PPR is enabled, we should grab the headers from the mocked response
// and add it to the headers.
if (renderOpts.experimental.ppr) {
Object.assign(headers, res.getHeaders())
}
if (fetchTags) {
headers[NEXT_CACHE_TAGS_HEADER] = fetchTags
}
......@@ -133,10 +128,11 @@ export async function exportAppPage(
const isParallelRoute = /\/@\w+/.test(page)
const isNonSuccessfulStatusCode = res.statusCode > 300
// When PPR is enabled, we don't always send 200 for routes that have been
// pregenerated, so we should grab the status code from the mocked
// response.
let status: number | undefined = renderOpts.experimental.ppr
let status: number | undefined = renderOpts.experimental.isRoutePPREnabled
? res.statusCode
: undefined
......
......@@ -64,7 +64,6 @@ export async function exportAppRoute(
notFoundRoutes: [],
},
renderOpts: {
experimental: { ppr: false },
originalPathname: page,
nextExport: true,
supportsDynamicHTML: false,
......
......@@ -83,13 +83,13 @@ async function exportPageImpl(
// Check if this is an `app/` page.
_isAppDir: isAppDir = false,
// TODO: use this when we've re-enabled app prefetching https://github.com/vercel/next.js/pull/58609
// // Check if this is an `app/` prefix request.
// _isAppPrefetch: isAppPrefetch = false,
// Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false,
// If this page supports partial prerendering, then we need to pass that to
// the renderOpts.
_isRoutePPREnabled: isRoutePPREnabled,
// Pull the original query out.
query: originalQuery = {},
} = pathMap
......@@ -231,8 +231,7 @@ async function exportPageImpl(
distDir,
dir,
enabledDirectories,
// PPR is not available for Pages.
experimental: { ppr: false },
isAppPPREnabled: input.renderOpts.experimental.isAppPPREnabled,
// skip writing to disk in minimal mode for now, pending some
// changes to better support it
flushToDisk: !hasNextSupport,
......@@ -271,6 +270,10 @@ async function exportPageImpl(
locale,
supportsDynamicHTML: false,
originalPathname: page,
experimental: {
...input.renderOpts.experimental,
isRoutePPREnabled,
},
}
if (hasNextSupport) {
......
......@@ -707,10 +707,29 @@ async function renderToHTMLOrFlightImpl(
const isNextExport = !!renderOpts.nextExport
const { staticGenerationStore, requestStore } = baseCtx
const { isStaticGeneration } = staticGenerationStore
// when static generation fails during PPR, we log the errors separately. We intentionally
// silence the error logger in this case to avoid double logging.
const silenceStaticGenerationErrors =
renderOpts.experimental.ppr && isStaticGeneration
/**
* Sets the headers on the response object. If we're generating static HTML,
* we store the headers in the metadata object as well so that they can be
* persisted.
*/
const setHeader = isStaticGeneration
? (name: string, value: string | string[]) => {
res.setHeader(name, value)
metadata.headers ??= {}
metadata.headers[name] = res.getHeader(name)
return res
}
: res.setHeader.bind(res)
const isRoutePPREnabled = renderOpts.experimental.isRoutePPREnabled === true
// When static generation fails during PPR, we log the errors separately. We
// intentionally silence the error logger in this case to avoid double
// logging.
const silenceStaticGenerationErrors = isRoutePPREnabled && isStaticGeneration
const serverComponentsErrorHandler = createErrorHandler({
source: ErrorHandlerSource.serverComponents,
......@@ -788,7 +807,7 @@ async function renderToHTMLOrFlightImpl(
const shouldProvideFlightRouterState =
isRSCRequest &&
(!isPrefetchRSCRequest ||
!renderOpts.experimental.ppr ||
!isRoutePPREnabled ||
// Interception routes currently depend on the flight router state to
// extract dynamic params.
isInterceptionRouteAppPath(pagePath))
......@@ -950,28 +969,22 @@ async function renderToHTMLOrFlightImpl(
const isResume = !!renderOpts.postponed
const onHeaders = staticGenerationStore.prerenderState
? // During prerender we write headers to metadata
(headers: Headers) => {
headers.forEach((value, key) => {
metadata.headers ??= {}
metadata.headers[key] = value
})
}
: isStaticGeneration || isResume
? // During static generation and during resumes we don't
// ask React to emit headers. For Resume this is just not supported
// For static generation we know there will be an entire HTML document
// output and so moving from tag to header for preloading can only
// server to alter preloading priorities in unwanted ways
undefined
: // During dynamic renders that are not resumes we write
// early headers to the response
(headers: Headers) => {
headers.forEach((value, key) => {
res.appendHeader(key, value)
})
}
const onHeaders =
// During prerenders, we want to capture the headers created so we can
// persist them to the metadata.
staticGenerationStore.prerenderState ||
// During static generation and during resumes we don't
// ask React to emit headers. For Resume this is just not supported
// For static generation we know there will be an entire HTML document
// output and so moving from tag to header for preloading can only
// server to alter preloading priorities in unwanted ways
(!isStaticGeneration && !isResume)
? (headers: Headers) => {
headers.forEach((value, key) => {
setHeader(key, value)
})
}
: undefined
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
......@@ -981,7 +994,7 @@ async function renderToHTMLOrFlightImpl(
})
const renderer = createStaticRenderer({
ppr: renderOpts.experimental.ppr,
isRoutePPREnabled,
isStaticGeneration,
// If provided, the postpone state should be parsed as JSON so it can be
// provided to React.
......@@ -1086,7 +1099,7 @@ async function renderToHTMLOrFlightImpl(
// We postponed but nothing dynamic was used. We resume the render now and immediately abort it
// so we can set all the postponed boundaries to client render mode before we store the HTML response
const resumeRenderer = createStaticRenderer({
ppr: true,
isRoutePPREnabled,
isStaticGeneration: false,
postponed: getDynamicHTMLPostponedState(postponed),
streamOptions: {
......@@ -1232,14 +1245,14 @@ async function renderToHTMLOrFlightImpl(
// If there were mutable cookies set, we need to set them on the
// response.
if (appendMutableCookies(headers, err.mutableCookies)) {
res.setHeader('set-cookie', Array.from(headers.values()))
setHeader('set-cookie', Array.from(headers.values()))
}
}
const redirectUrl = addPathPrefix(
getURLFromRedirectError(err),
renderOpts.basePath
)
res.setHeader('Location', redirectUrl)
setHeader('Location', redirectUrl)
}
const is404 = res.statusCode === 404
......
......@@ -413,7 +413,7 @@ async function createComponentTreeInternal({
// possible during both prefetches and dynamic navigations. But during
// the beta period, we should be clear about this trade off in our
// communications.
!experimental.ppr
!experimental.isRoutePPREnabled
) {
// Don't prefetch this child. This will trigger a lazy fetch by the
// client router.
......
......@@ -111,10 +111,10 @@ export function getDynamicDataPostponedState(): DynamicDataPostponedState {
type Options = {
/**
* Whether or not PPR is enabled. This is used to determine which renderer to
* use.
* Whether or not PPR is enabled for this page. This is used to determine
* which renderer to use.
*/
ppr: boolean
isRoutePPREnabled: boolean
/**
* Whether or not this is a static generation render. This is used to
......@@ -138,7 +138,7 @@ type Options = {
}
export function createStaticRenderer({
ppr,
isRoutePPREnabled,
isStaticGeneration,
postponed,
streamOptions: {
......@@ -152,7 +152,7 @@ export function createStaticRenderer({
formState,
},
}: Options): Renderer {
if (ppr) {
if (isRoutePPREnabled) {
if (isStaticGeneration) {
// This is a Prerender
return new StaticRenderer({
......
......@@ -159,7 +159,16 @@ export interface RenderOptsPartial {
params?: ParsedUrlQuery
isPrefetch?: boolean
experimental: {
ppr: boolean
/**
* When true, some routes support partial prerendering (PPR).
*/
isAppPPREnabled: boolean
/**
* When true, it indicates that the current page supports partial
* prerendering.
*/
isRoutePPREnabled?: boolean
missingSuspenseWithCSRBailout: boolean
swrDelta: SwrDelta | undefined
}
......
......@@ -113,7 +113,7 @@ export async function walkTreeWithFlightRouterState({
const shouldSkipComponentTree =
// loading.tsx has no effect on prefetching when PPR is enabled
!experimental.ppr &&
!experimental.isRoutePPREnabled &&
isPrefetch &&
!Boolean(components.loading) &&
(flightRouterState ||
......
......@@ -16,7 +16,7 @@ export type StaticGenerationContext = {
fetchCache?: StaticGenerationStore['fetchCache']
isServerAction?: boolean
waitUntil?: Promise<any>
experimental: { ppr: boolean; missingSuspenseWithCSRBailout?: boolean }
experimental?: Pick<RenderOptsPartial['experimental'], 'isRoutePPREnabled'>
/**
* Fetch metrics attached in patch-fetch.ts
......@@ -77,7 +77,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
!renderOpts.isServerAction
const prerenderState: StaticGenerationStore['prerenderState'] =
isStaticGeneration && renderOpts.experimental.ppr
isStaticGeneration && renderOpts.experimental?.isRoutePPREnabled
? createPrerenderState(renderOpts.isDebugPPRSkeleton)
: null
......
This diff is collapsed.
......@@ -35,8 +35,8 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
query: z.any(), // NextParsedUrlQuery
// private optional properties
_isAppDir: z.boolean().optional(),
_isAppPrefetch: z.boolean().optional(),
_isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(),
})
)
......@@ -313,7 +313,10 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(),
parallelServerCompiles: z.boolean().optional(),
parallelServerBuildTraces: z.boolean().optional(),
ppr: z.boolean().optional(),
ppr: z
.union([z.boolean(), z.literal('incremental')])
.readonly()
.optional(),
taint: z.boolean().optional(),
prerenderEarlyExit: z.boolean().optional(),
proxyTimeout: z.number().gte(0).optional(),
......
......@@ -12,6 +12,7 @@ import type { NextParsedUrlQuery } from './request-meta'
import type { SizeLimit } from '../types'
import type { SwrDelta } from './lib/revalidate'
import type { SupportedTestRunners } from '../cli/next-test'
import type { ExperimentalPPRConfig } from './lib/experimental/ppr'
export type NextConfigComplete = Required<NextConfig> & {
images: Required<ImageConfigComplete>
......@@ -382,7 +383,7 @@ export interface ExperimentalConfig {
/**
* Using this feature will enable the `react@experimental` for the `app` directory.
*/
ppr?: boolean
ppr?: ExperimentalPPRConfig
/**
* Enables experimental taint APIs in React.
......@@ -466,9 +467,21 @@ export type ExportPathMap = {
[path: string]: {
page: string
query?: NextParsedUrlQuery
/**
* @internal
*/
_isAppDir?: boolean
_isAppPrefetch?: boolean
/**
* @internal
*/
_isDynamicError?: boolean
/**
* @internal
*/
_isRoutePPREnabled?: boolean
}
}
......
......@@ -715,7 +715,6 @@ export default class DevServer extends Server {
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
ppr: this.nextConfig.experimental.ppr === true,
})
return pathsResult
} finally {
......
......@@ -38,7 +38,6 @@ export async function loadStaticPaths({
maxMemoryCacheSize,
requestHeaders,
cacheHandler,
ppr,
}: {
dir: string
distDir: string
......@@ -54,7 +53,6 @@ export async function loadStaticPaths({
maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders']
cacheHandler?: string
ppr: boolean
}): Promise<{
paths?: string[]
encodedPaths?: string[]
......@@ -109,7 +107,6 @@ export async function loadStaticPaths({
isrFlushToDisk,
fetchCacheKeyPrefix,
maxMemoryCacheSize,
ppr,
ComponentMod: components.ComponentMod,
})
}
......
/**
* If set to `incremental`, only those leaf pages that export
* `experimental_ppr = true` will have partial prerendering enabled. If any
* page exports this value as `false` or does not export it at all will not
* have partial prerendering enabled. If set to a boolean, it the options for
* `experimental_ppr` will be ignored.
*/
export type ExperimentalPPRConfig = boolean | 'incremental'
/**
* Returns true if partial prerendering is enabled for the application. It does
* not tell you if a given route has PPR enabled, as that requires analysis of
* the route's configuration.
*
* @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.
*/
export function checkIsAppPPREnabled(
config: ExperimentalPPRConfig | undefined
): boolean {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config
// If the config is a string, it must be 'incremental' to enable partial
// prerendering.
if (config === 'incremental') return true
return false
}
/**
* Returns true if partial prerendering is supported for the current page with
* the provided app configuration. If the application doesn't have partial
* prerendering enabled, this function will always return false. If you want to
* check if the application has partial prerendering enabled
*
* @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.
*/
export function checkIsRoutePPREnabled(
config: ExperimentalPPRConfig | undefined,
appConfig: {
experimental_ppr?: boolean
}
): boolean {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config
// If the config is a string, it must be 'incremental' to enable partial
// prerendering.
if (config === 'incremental' && appConfig.experimental_ppr === true) {
return true
}
return false
}
......@@ -19,7 +19,12 @@ type FileSystemCacheContext = Omit<
> & {
fs: CacheFs
serverDistDir: string
experimental: { ppr: boolean }
/**
* isAppPPREnabled is true when PPR has been enabled either globally or just for
* some pages via the `incremental` option.
*/
isAppPPREnabled: boolean
}
type TagsManifest = {
......@@ -37,7 +42,7 @@ export default class FileSystemCache implements CacheHandler {
private pagesDir: boolean
private tagsManifestPath?: string
private revalidatedTags: string[]
private readonly experimental: { ppr: boolean }
private readonly isAppPPREnabled: boolean
private debug: boolean
constructor(ctx: FileSystemCacheContext) {
......@@ -47,7 +52,7 @@ export default class FileSystemCache implements CacheHandler {
this.appDir = !!ctx._appDir
this.pagesDir = !!ctx._pagesDir
this.revalidatedTags = ctx.revalidatedTags
this.experimental = ctx.experimental
this.isAppPPREnabled = ctx.isAppPPREnabled
this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
if (ctx.maxMemoryCacheSize && !memoryCache) {
......@@ -226,7 +231,7 @@ export default class FileSystemCache implements CacheHandler {
? await this.fs.readFile(
this.getFilePath(
`${key}${
this.experimental.ppr ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX
this.isAppPPREnabled ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX
}`,
'app'
),
......@@ -370,7 +375,7 @@ export default class FileSystemCache implements CacheHandler {
this.getFilePath(
`${key}${
isAppPath
? this.experimental.ppr
? this.isAppPPREnabled
? RSC_PREFETCH_SUFFIX
: RSC_SUFFIX
: NEXT_DATA_SUFFIX
......
......@@ -31,7 +31,7 @@ export interface CacheHandlerContext {
fetchCacheKeyPrefix?: string
prerenderManifest?: PrerenderManifest
revalidatedTags: string[]
experimental: { ppr: boolean }
isAppPPREnabled?: boolean
_appDir: boolean
_pagesDir: boolean
_requestHeaders: IncrementalCache['requestHeaders']
......@@ -104,7 +104,7 @@ export class IncrementalCache implements IncrementalCacheType {
fetchCacheKeyPrefix,
CurCacheHandler,
allowedRevalidateHeaderKeys,
experimental,
isAppPPREnabled,
}: {
fs?: CacheFs
dev: boolean
......@@ -121,7 +121,7 @@ export class IncrementalCache implements IncrementalCacheType {
getPrerenderManifest: () => DeepReadonly<PrerenderManifest>
fetchCacheKeyPrefix?: string
CurCacheHandler?: typeof CacheHandler
experimental: { ppr: boolean }
isAppPPREnabled: boolean
}) {
const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
this.hasCustomCacheHandler = Boolean(CurCacheHandler)
......@@ -193,7 +193,7 @@ export class IncrementalCache implements IncrementalCacheType {
_appDir: !!appDir,
_requestHeaders: requestHeaders,
fetchCacheKeyPrefix,
experimental,
isAppPPREnabled,
})
}
}
......@@ -429,7 +429,7 @@ export class IncrementalCache implements IncrementalCacheType {
cacheKey: string,
ctx: {
kindHint?: IncrementalCacheKindHint
revalidate?: number | false
revalidate?: Revalidate
fetchUrl?: string
fetchIdx?: number
tags?: string[]
......@@ -551,7 +551,7 @@ export class IncrementalCache implements IncrementalCacheType {
pathname: string,
data: IncrementalCacheValue | null,
ctx: {
revalidate?: number | false
revalidate?: Revalidate
fetchCache?: boolean
fetchUrl?: string
fetchIdx?: number
......
......@@ -391,7 +391,7 @@ export default class NextNodeServer extends BaseServer<
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => this.getPrerenderManifest(),
CurCacheHandler: CacheHandler,
experimental: this.renderOpts.experimental,
isAppPPREnabled: this.renderOpts.experimental.isAppPPREnabled,
})
}
......
......@@ -93,8 +93,8 @@ export default class NextWebServer extends BaseServer<
CurCacheHandler:
this.serverOptions.webServerConfig.incrementalCacheHandler,
getPrerenderManifest: () => this.getPrerenderManifest(),
// PPR is not supported in the edge runtime.
experimental: { ppr: false },
// PPR is not supported in the Edge runtime.
isAppPPREnabled: false,
})
}
protected getResponseCache() {
......
......@@ -104,8 +104,6 @@ export class EdgeRouteModuleWrapper {
},
renderOpts: {
supportsDynamicHTML: true,
// App Route's cannot be postponed.
experimental: { ppr: false },
},
}
......
......@@ -317,6 +317,7 @@ describe('ppr-full', () => {
if (signal === 'redirect()') {
const location = res.headers.get('location')
expect(location).not.toBeNull()
expect(typeof location).toEqual('string')
// The URL returned in `Location` is absolute, so we need to parse it
......
export { default } from '../../lib/page'
export const experimental_ppr = false
export { default } from '../../../lib/page'
export { default } from '../../../../lib/page'
export const experimental_ppr = false
export { default } from '../../../../lib/page'
export const experimental_ppr = true
export { default } from '../../lib/page'
export const experimental_ppr = true
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export { default } from '../../../../../lib/page'
export const experimental_ppr = false
export { default } from '../../../../../lib/page'
export const experimental_ppr = true
export const experimental_ppr = false
export default function Layout({ children }) {
return children
}
export { default } from '../../../../lib/page'
export { default } from '../../../../../lib/page'
export const experimental_ppr = false
export { default } from '../../../../../lib/page'
export const experimental_ppr = true
export const experimental_ppr = true
export default function Layout({ children }) {
return children
}
export { default, generateStaticParams } from '../../../lib/page'
export const dynamicParams = false
export { default, generateStaticParams } from '../../../../lib/page'
export const experimental_ppr = false
export const dynamicParams = false
export { default, generateStaticParams } from '../../../../lib/page'
export const experimental_ppr = true
export const dynamicParams = false
export { default } from '../lib/page'
import { unstable_noStore } from 'next/cache'
import Link from 'next/link'
import { Suspense } from 'react'
function Dynamic() {
unstable_noStore()
return <div id="dynamic">Dynamic</div>
}
export default function Page() {
return (
<>
<li>
<Link href="/">Root</Link>
<Link href="/enabled">Enabled</Link>
<Link href="/disabled">Disabled</Link>
</li>
<Suspense fallback={<div id="fallback">Loading...</div>}>
<Dynamic />
</Suspense>
</>
)
}
export const slugs = ['a', 'b', 'c']
export const generateStaticParams = () => {
return slugs.map((slug) => ({ slug }))
}
/**
* @type {import('next').NextConfig}
*/
module.exports = {
experimental: {
ppr: 'incremental',
},
}
import { nextTestSetup, isNextDev } from 'e2e-utils'
type Route = {
route: string
enabled: boolean
pathnames: string[]
}
const routes: ReadonlyArray<Route> = [
{
route: '/',
pathnames: ['/'],
enabled: false,
},
{
route: '/disabled',
pathnames: ['/disabled'],
enabled: false,
},
{
route: '/enabled',
pathnames: ['/enabled'],
enabled: true,
},
{
route: '/omitted/[slug]',
pathnames: ['/omitted/a', '/omitted/b', '/omitted/c'],
enabled: false,
},
{
route: '/omitted/disabled/[slug]',
pathnames: [
'/omitted/disabled/a',
'/omitted/disabled/b',
'/omitted/disabled/c',
],
enabled: false,
},
{
route: '/omitted/enabled/[slug]',
pathnames: [
'/omitted/enabled/a',
'/omitted/enabled/b',
'/omitted/enabled/c',
],
enabled: true,
},
{
route: '/dynamic/[slug]',
pathnames: ['/dynamic/a', '/dynamic/b', '/dynamic/c'],
enabled: false,
},
{
route: '/dynamic/disabled/[slug]',
pathnames: [
'/dynamic/disabled/a',
'/dynamic/disabled/b',
'/dynamic/disabled/c',
],
enabled: false,
},
{
route: '/dynamic/enabled/[slug]',
pathnames: [
'/dynamic/enabled/a',
'/dynamic/enabled/b',
'/dynamic/enabled/c',
],
enabled: true,
},
{
route: '/nested/enabled/[slug]',
pathnames: ['/nested/enabled/a', '/nested/enabled/b', '/nested/enabled/c'],
enabled: true,
},
{
route: '/nested/enabled/disabled/[slug]',
pathnames: [
'/nested/enabled/disabled/a',
'/nested/enabled/disabled/b',
'/nested/enabled/disabled/c',
],
enabled: false,
},
{
route: '/nested/enabled/enabled/[slug]',
pathnames: [
'/nested/enabled/enabled/a',
'/nested/enabled/enabled/b',
'/nested/enabled/enabled/c',
],
enabled: true,
},
{
route: '/nested/disabled/[slug]',
pathnames: [
'/nested/disabled/a',
'/nested/disabled/b',
'/nested/disabled/c',
],
enabled: false,
},
{
route: '/nested/disabled/disabled/[slug]',
pathnames: [
'/nested/disabled/disabled/a',
'/nested/disabled/disabled/b',
'/nested/disabled/disabled/c',
],
enabled: false,
},
{
route: '/nested/disabled/enabled/[slug]',
pathnames: [
'/nested/disabled/enabled/a',
'/nested/disabled/enabled/b',
'/nested/disabled/enabled/c',
],
enabled: true,
},
]
describe('ppr-incremental', () => {
// We don't perform static builds and partial prerendering in development
// mode.
if (isNextDev) return it.skip('should skip next dev', () => {})
const { next } = nextTestSetup({ files: __dirname })
describe('ppr disabled', () => {
describe.each(routes.filter(({ enabled }) => !enabled))(
'$route',
({ pathnames }) => {
// When PPR is disabled, we won't include the fallback in the initial
// load because the dynamic render will not suspend.
describe('should render without the fallback in the initial load', () => {
it.each(pathnames)('%s', async (pathname) => {
const $ = await next.render$(pathname)
expect($('#fallback')).toHaveLength(0)
})
})
describe('should not have the dynamic content hidden', () => {
it.each(pathnames)('%s', async (pathname) => {
const $ = await next.render$(pathname)
expect($('#dynamic')).toHaveLength(1)
expect($('#dynamic').parent('[hidden]')).toHaveLength(0)
})
})
}
)
})
describe('ppr enabled', () => {
describe.each(routes.filter(({ enabled }) => enabled))(
'$route',
({ pathnames }) => {
// When PPR is enabled, we will always include the fallback in the
// initial load because the dynamic component uses `unstable_noStore()`.
describe('should render with the fallback in the initial load', () => {
it.each(pathnames)('%s', async (pathname) => {
const $ = await next.render$(pathname)
expect($('#fallback')).toHaveLength(1)
})
})
describe('should have the dynamic content hidden', () => {
it.each(pathnames)('%s', async (pathname) => {
const $ = await next.render$(pathname)
expect($('#dynamic')).toHaveLength(1)
expect($('#dynamic').parent('[hidden]')).toHaveLength(1)
})
})
}
)
})
})
......@@ -15,9 +15,7 @@ describe('FileSystemCache', () => {
fs: nodeFs,
serverDistDir: cacheDir,
revalidatedTags: [],
experimental: {
ppr: false,
},
isAppPPREnabled: false,
})
const binary = await fs.readFile(
......@@ -37,7 +35,7 @@ describe('FileSystemCache', () => {
{}
)
expect((await fsCache.get('icon.png')).value).toEqual({
expect((await fsCache.get('icon.png'))?.value).toEqual({
body: binary,
headers: {
'Content-Type': 'image/png',
......@@ -57,9 +55,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
fs: nodeFs,
serverDistDir: cacheDir,
revalidatedTags: [],
experimental: {
ppr: false,
},
isAppPPREnabled: false,
maxMemoryCacheSize: 0, // disable memory cache
})
......@@ -90,7 +86,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
kindHint: 'fetch',
})
expect(res.value).toEqual({
expect(res?.value).toEqual({
kind: 'FETCH',
data: {
headers: {},
......@@ -119,7 +115,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
kindHint: 'fetch',
})
expect(res.value).toEqual({
expect(res?.value).toEqual({
kind: 'FETCH',
data: { headers: {}, body: '1700056381', status: 200, url: '' },
revalidate: 30,
......
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