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 { ...@@ -72,6 +72,7 @@ pub struct NextSegmentConfig {
pub fetch_cache: Option<NextSegmentFetchCache>, pub fetch_cache: Option<NextSegmentFetchCache>,
pub runtime: Option<NextRuntime>, pub runtime: Option<NextRuntime>,
pub preferred_region: Option<Vec<String>>, pub preferred_region: Option<Vec<String>>,
pub experimental_ppr: Option<bool>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -93,6 +94,7 @@ impl NextSegmentConfig { ...@@ -93,6 +94,7 @@ impl NextSegmentConfig {
fetch_cache, fetch_cache,
runtime, runtime,
preferred_region, preferred_region,
experimental_ppr,
} = self; } = self;
*dynamic = dynamic.or(parent.dynamic); *dynamic = dynamic.or(parent.dynamic);
*dynamic_params = dynamic_params.or(parent.dynamic_params); *dynamic_params = dynamic_params.or(parent.dynamic_params);
...@@ -100,6 +102,7 @@ impl NextSegmentConfig { ...@@ -100,6 +102,7 @@ impl NextSegmentConfig {
*fetch_cache = fetch_cache.or(parent.fetch_cache); *fetch_cache = fetch_cache.or(parent.fetch_cache);
*runtime = runtime.or(parent.runtime); *runtime = runtime.or(parent.runtime);
*preferred_region = preferred_region.take().or(parent.preferred_region.clone()); *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 /// Applies a config from a paralllel route to this config, returning an
...@@ -133,6 +136,7 @@ impl NextSegmentConfig { ...@@ -133,6 +136,7 @@ impl NextSegmentConfig {
fetch_cache, fetch_cache,
runtime, runtime,
preferred_region, preferred_region,
experimental_ppr,
} = self; } = self;
merge_parallel(dynamic, &parallel_config.dynamic, "dynamic")?; merge_parallel(dynamic, &parallel_config.dynamic, "dynamic")?;
merge_parallel( merge_parallel(
...@@ -148,6 +152,11 @@ impl NextSegmentConfig { ...@@ -148,6 +152,11 @@ impl NextSegmentConfig {
&parallel_config.preferred_region, &parallel_config.preferred_region,
"referredRegion", "referredRegion",
)?; )?;
merge_parallel(
experimental_ppr,
&parallel_config.experimental_ppr,
"experimental_ppr",
)?;
Ok(()) Ok(())
} }
} }
...@@ -422,6 +431,15 @@ fn parse_config_value( ...@@ -422,6 +431,15 @@ fn parse_config_value(
config.preferred_region = Some(preferred_region); 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 { ...@@ -520,7 +520,7 @@ pub struct ExperimentalConfig {
output_file_tracing_root: Option<String>, output_file_tracing_root: Option<String>,
/// Using this feature will enable the `react@experimental` for the `app` /// Using this feature will enable the `react@experimental` for the `app`
/// directory. /// directory.
ppr: Option<bool>, ppr: Option<ExperimentalPartialPrerendering>,
taint: Option<bool>, taint: Option<bool>,
proxy_timeout: Option<f64>, proxy_timeout: Option<f64>,
/// enables the minification of server code. /// enables the minification of server code.
...@@ -542,6 +542,49 @@ pub struct ExperimentalConfig { ...@@ -542,6 +542,49 @@ pub struct ExperimentalConfig {
worker_threads: Option<bool>, 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)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct SubResourceIntegrity { pub struct SubResourceIntegrity {
...@@ -572,6 +615,25 @@ pub enum EsmExternals { ...@@ -572,6 +615,25 @@ pub enum EsmExternals {
Bool(bool), 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)] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ServerActions { pub struct ServerActions {
...@@ -934,7 +996,19 @@ impl NextConfig { ...@@ -934,7 +996,19 @@ impl NextConfig {
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn enable_ppr(self: Vc<Self>) -> Result<Vc<bool>> { 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] #[turbo_tasks::function]
......
...@@ -314,7 +314,7 @@ async function tryToReadFile(filePath: string, shouldThrow: boolean) { ...@@ -314,7 +314,7 @@ async function tryToReadFile(filePath: string, shouldThrow: boolean) {
export function getMiddlewareMatchers( export function getMiddlewareMatchers(
matcherOrMatchers: unknown, matcherOrMatchers: unknown,
nextConfig: NextConfig nextConfig: Pick<NextConfig, 'basePath' | 'i18n'>
): MiddlewareMatcher[] { ): MiddlewareMatcher[] {
let matchers: unknown[] = [] let matchers: unknown[] = []
if (Array.isArray(matcherOrMatchers)) { if (Array.isArray(matcherOrMatchers)) {
......
...@@ -187,6 +187,10 @@ import { traceMemoryUsage } from '../lib/memory/trace' ...@@ -187,6 +187,10 @@ import { traceMemoryUsage } from '../lib/memory/trace'
import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils' import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import uploadTrace from '../trace/upload-trace' import uploadTrace from '../trace/upload-trace'
import {
checkIsAppPPREnabled,
checkIsRoutePPREnabled,
} from '../server/lib/experimental/ppr'
interface ExperimentalBypassForInfo { interface ExperimentalBypassForInfo {
experimentalBypassFor?: RouteHas[] experimentalBypassFor?: RouteHas[]
...@@ -1740,7 +1744,6 @@ export default async function build( ...@@ -1740,7 +1744,6 @@ export default async function build(
const additionalSsgPaths = new Map<string, Array<string>>() const additionalSsgPaths = new Map<string, Array<string>>()
const additionalSsgPathsEncoded = new Map<string, Array<string>>() const additionalSsgPathsEncoded = new Map<string, Array<string>>()
const appStaticPaths = 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 appStaticPathsEncoded = new Map<string, Array<string>>()
const appNormalizedPaths = new Map<string, string>() const appNormalizedPaths = new Map<string, string>()
const appDynamicParamPaths = new Set<string>() const appDynamicParamPaths = new Set<string>()
...@@ -1808,7 +1811,7 @@ export default async function build( ...@@ -1808,7 +1811,7 @@ export default async function build(
minimalMode: ciEnvironment.hasNextSupport, minimalMode: ciEnvironment.hasNextSupport,
allowedRevalidateHeaderKeys: allowedRevalidateHeaderKeys:
config.experimental.allowedRevalidateHeaderKeys, config.experimental.allowedRevalidateHeaderKeys,
experimental: { ppr: config.experimental.ppr === true }, isAppPPREnabled: checkIsAppPPREnabled(config.experimental.ppr),
}) })
incrementalCacheIpcPort = cacheInitialization.ipcPort incrementalCacheIpcPort = cacheInitialization.ipcPort
...@@ -1886,7 +1889,7 @@ export default async function build( ...@@ -1886,7 +1889,7 @@ export default async function build(
locales: config.i18n?.locales, locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output, nextConfigOutput: config.output,
ppr: config.experimental.ppr === true, pprConfig: config.experimental.ppr,
}) })
) )
...@@ -1984,7 +1987,7 @@ export default async function build( ...@@ -1984,7 +1987,7 @@ export default async function build(
computedManifestData computedManifestData
) )
let isPPR = false let isRoutePPREnabled = false
let isSSG = false let isSSG = false
let isStatic = false let isStatic = false
let isServerComponent = false let isServerComponent = false
...@@ -2099,7 +2102,7 @@ export default async function build( ...@@ -2099,7 +2102,7 @@ export default async function build(
: config.experimental.isrFlushToDisk, : config.experimental.isrFlushToDisk,
maxMemoryCacheSize: config.cacheMaxMemorySize, maxMemoryCacheSize: config.cacheMaxMemorySize,
nextConfigOutput: config.output, nextConfigOutput: config.output,
ppr: config.experimental.ppr === true, pprConfig: config.experimental.ppr,
}) })
} }
) )
...@@ -2118,8 +2121,8 @@ export default async function build( ...@@ -2118,8 +2121,8 @@ export default async function build(
// If this route can be partially pre-rendered, then // If this route can be partially pre-rendered, then
// mark it as such and mark that it can be // mark it as such and mark that it can be
// generated server-side. // generated server-side.
if (workerResult.isPPR) { if (workerResult.isRoutePPREnabled) {
isPPR = workerResult.isPPR isRoutePPREnabled = workerResult.isRoutePPREnabled
isSSG = true isSSG = true
isStatic = true isStatic = true
...@@ -2174,7 +2177,6 @@ export default async function build( ...@@ -2174,7 +2177,6 @@ export default async function build(
]) ])
isStatic = true isStatic = true
} else if ( } else if (
isDynamic &&
!hasGenerateStaticParams && !hasGenerateStaticParams &&
(appConfig.dynamic === 'error' || (appConfig.dynamic === 'error' ||
appConfig.dynamic === 'force-static') appConfig.dynamic === 'force-static')
...@@ -2182,7 +2184,7 @@ export default async function build( ...@@ -2182,7 +2184,7 @@ export default async function build(
appStaticPaths.set(originalAppPath, []) appStaticPaths.set(originalAppPath, [])
appStaticPathsEncoded.set(originalAppPath, []) appStaticPathsEncoded.set(originalAppPath, [])
isStatic = true isStatic = true
isPPR = false isRoutePPREnabled = false
} }
} }
} }
...@@ -2193,18 +2195,6 @@ export default async function build( ...@@ -2193,18 +2195,6 @@ export default async function build(
appDynamicParamPaths.add(originalAppPath) appDynamicParamPaths.add(originalAppPath)
} }
appDefaultConfigs.set(originalAppPath, appConfig) 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 { } else {
if (isEdgeRuntime(pageRuntime)) { if (isEdgeRuntime(pageRuntime)) {
...@@ -2328,7 +2318,7 @@ export default async function build( ...@@ -2328,7 +2318,7 @@ export default async function build(
totalSize, totalSize,
isStatic, isStatic,
isSSG, isSSG,
isPPR, isRoutePPREnabled,
isHybridAmp, isHybridAmp,
ssgPageRoutes, ssgPageRoutes,
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
...@@ -2623,34 +2613,24 @@ export default async function build( ...@@ -2623,34 +2613,24 @@ export default async function build(
// revalidate periods and dynamicParams settings // revalidate periods and dynamicParams settings
appStaticPaths.forEach((routes, originalAppPath) => { appStaticPaths.forEach((routes, originalAppPath) => {
const encodedRoutes = appStaticPathsEncoded.get(originalAppPath) const encodedRoutes = appStaticPathsEncoded.get(originalAppPath)
const appConfig = appDefaultConfigs.get(originalAppPath) || {} const appConfig = appDefaultConfigs.get(originalAppPath)
routes.forEach((route, routeIdx) => { routes.forEach((route, routeIdx) => {
defaultMap[route] = { defaultMap[route] = {
page: originalAppPath, page: originalAppPath,
query: { __nextSsgPath: encodedRoutes?.[routeIdx] }, query: { __nextSsgPath: encodedRoutes?.[routeIdx] },
_isDynamicError: appConfig.dynamic === 'error', _isDynamicError: appConfig?.dynamic === 'error',
_isAppDir: true, _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) { if (i18n) {
for (const page of [ for (const page of [
...staticPages, ...staticPages,
...@@ -2682,6 +2662,7 @@ export default async function build( ...@@ -2682,6 +2662,7 @@ export default async function build(
} }
} }
} }
return defaultMap return defaultMap
}, },
} }
...@@ -2752,8 +2733,9 @@ export default async function build( ...@@ -2752,8 +2733,9 @@ export default async function build(
// When this is an app page and PPR is enabled, the route supports // When this is an app page and PPR is enabled, the route supports
// partial pre-rendering. // partial pre-rendering.
const experimentalPPR = const experimentalPPR: true | undefined =
!isRouteHandler && config.experimental.ppr === true !isRouteHandler &&
checkIsRoutePPREnabled(config.experimental.ppr, appConfig)
? true ? true
: undefined : undefined
......
import type { NextConfig, NextConfigComplete } from '../server/config-shared' 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 { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import type { AssetBinding } from './webpack/loaders/get-module-build-info' import type { AssetBinding } from './webpack/loaders/get-module-build-info'
import type { import type {
...@@ -87,6 +88,7 @@ import { interopDefault } from '../lib/interop-default' ...@@ -87,6 +88,7 @@ import { interopDefault } from '../lib/interop-default'
import type { PageExtensions } from './page-extensions-type' import type { PageExtensions } from './page-extensions-type'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path' import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import { isInterceptionRouteAppPath } from '../server/future/helpers/interception-routes' import { isInterceptionRouteAppPath } from '../server/future/helpers/interception-routes'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
...@@ -347,7 +349,10 @@ export interface PageInfo { ...@@ -347,7 +349,10 @@ export interface PageInfo {
totalSize: number totalSize: number
isStatic: boolean isStatic: boolean
isSSG: boolean isSSG: boolean
isPPR: boolean /**
* If true, it means that the route has partial prerendering enabled.
*/
isRoutePPREnabled: boolean
ssgPageRoutes: string[] | null ssgPageRoutes: string[] | null
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
pageDuration: number | undefined pageDuration: number | undefined
...@@ -489,7 +494,7 @@ export async function printTreeView( ...@@ -489,7 +494,7 @@ export async function printTreeView(
symbol = ' ' symbol = ' '
} else if (isEdgeRuntime(pageInfo?.runtime)) { } else if (isEdgeRuntime(pageInfo?.runtime)) {
symbol = 'ƒ' symbol = 'ƒ'
} else if (pageInfo?.isPPR) { } else if (pageInfo?.isRoutePPREnabled) {
if ( if (
// If the page has an empty prelude, then it's equivalent to a dynamic page // If the page has an empty prelude, then it's equivalent to a dynamic page
pageInfo?.hasEmptyPrelude || pageInfo?.hasEmptyPrelude ||
...@@ -1180,6 +1185,13 @@ export type AppConfig = { ...@@ -1180,6 +1185,13 @@ export type AppConfig = {
dynamic?: AppConfigDynamic dynamic?: AppConfigDynamic
fetchCache?: 'force-cache' | 'only-cache' fetchCache?: 'force-cache' | 'only-cache'
preferredRegion?: string 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[]> type Params = Record<string, string | string[]>
...@@ -1197,10 +1209,12 @@ type GenerateParamsResult = { ...@@ -1197,10 +1209,12 @@ type GenerateParamsResult = {
export type GenerateParamsResults = GenerateParamsResult[] export type GenerateParamsResults = GenerateParamsResult[]
export const collectAppConfig = (mod: any): AppConfig | undefined => { const collectAppConfig = (
mod: Partial<AppConfig> | undefined
): AppConfig | undefined => {
let hasConfig = false let hasConfig = false
const config: AppConfig = {} const config: AppConfig = {}
if (typeof mod?.revalidate !== 'undefined') { if (typeof mod?.revalidate !== 'undefined') {
config.revalidate = mod.revalidate config.revalidate = mod.revalidate
hasConfig = true hasConfig = true
...@@ -1221,8 +1235,14 @@ export const collectAppConfig = (mod: any): AppConfig | undefined => { ...@@ -1221,8 +1235,14 @@ export const collectAppConfig = (mod: any): AppConfig | undefined => {
config.preferredRegion = mod.preferredRegion config.preferredRegion = mod.preferredRegion
hasConfig = true hasConfig = true
} }
if (typeof mod?.experimental_ppr !== 'undefined') {
config.experimental_ppr = mod.experimental_ppr
hasConfig = true
}
return hasConfig ? config : undefined if (!hasConfig) return undefined
return config
} }
/** /**
...@@ -1313,7 +1333,6 @@ export async function buildAppStaticPaths({ ...@@ -1313,7 +1333,6 @@ export async function buildAppStaticPaths({
requestHeaders, requestHeaders,
maxMemoryCacheSize, maxMemoryCacheSize,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
ppr,
ComponentMod, ComponentMod,
}: { }: {
dir: string dir: string
...@@ -1326,7 +1345,6 @@ export async function buildAppStaticPaths({ ...@@ -1326,7 +1345,6 @@ export async function buildAppStaticPaths({
cacheHandler?: string cacheHandler?: string
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
ppr: boolean
ComponentMod: AppPageModule ComponentMod: AppPageModule
}) { }) {
ComponentMod.patchFetch() ComponentMod.patchFetch()
...@@ -1361,7 +1379,7 @@ export async function buildAppStaticPaths({ ...@@ -1361,7 +1379,7 @@ export async function buildAppStaticPaths({
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
requestHeaders, requestHeaders,
minimalMode: ciEnvironment.hasNextSupport, minimalMode: ciEnvironment.hasNextSupport,
experimental: { ppr }, isAppPPREnabled: false,
}) })
return StaticGenerationAsyncStorageWrapper.wrap( return StaticGenerationAsyncStorageWrapper.wrap(
...@@ -1373,8 +1391,6 @@ export async function buildAppStaticPaths({ ...@@ -1373,8 +1391,6 @@ export async function buildAppStaticPaths({
incrementalCache, incrementalCache,
supportsDynamicHTML: true, supportsDynamicHTML: true,
isRevalidate: false, isRevalidate: false,
// building static paths should never postpone
experimental: { ppr: false },
}, },
}, },
async () => { async () => {
...@@ -1488,7 +1504,7 @@ export async function isPageStatic({ ...@@ -1488,7 +1504,7 @@ export async function isPageStatic({
isrFlushToDisk, isrFlushToDisk,
maxMemoryCacheSize, maxMemoryCacheSize,
cacheHandler, cacheHandler,
ppr, pprConfig,
}: { }: {
dir: string dir: string
page: string page: string
...@@ -1507,9 +1523,9 @@ export async function isPageStatic({ ...@@ -1507,9 +1523,9 @@ export async function isPageStatic({
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
cacheHandler?: string cacheHandler?: string
nextConfigOutput: 'standalone' | 'export' nextConfigOutput: 'standalone' | 'export'
ppr: boolean pprConfig: ExperimentalPPRConfig | undefined
}): Promise<{ }): Promise<{
isPPR?: boolean isRoutePPREnabled?: boolean
isStatic?: boolean isStatic?: boolean
isAmpOnly?: boolean isAmpOnly?: boolean
isHybridAmp?: boolean isHybridAmp?: boolean
...@@ -1584,13 +1600,9 @@ export async function isPageStatic({ ...@@ -1584,13 +1600,9 @@ export async function isPageStatic({
const routeModule: RouteModule = const routeModule: RouteModule =
componentsResult.ComponentMod?.routeModule componentsResult.ComponentMod?.routeModule
let supportsPPR = false let isRoutePPREnabled: boolean = false
if (pageType === 'app') { if (pageType === 'app') {
if (ppr && routeModule.definition.kind === RouteKind.APP_PAGE) {
supportsPPR = true
}
const ComponentMod: AppPageModule = componentsResult.ComponentMod const ComponentMod: AppPageModule = componentsResult.ComponentMod
isClientComponent = isClientReference(componentsResult.ComponentMod) isClientComponent = isClientReference(componentsResult.ComponentMod)
...@@ -1620,6 +1632,7 @@ export async function isPageStatic({ ...@@ -1620,6 +1632,7 @@ export async function isPageStatic({
fetchCache, fetchCache,
preferredRegion, preferredRegion,
revalidate: curRevalidate, revalidate: curRevalidate,
experimental_ppr,
} = curGenParams?.config || {} } = curGenParams?.config || {}
// TODO: should conflicting configs here throw an error // TODO: should conflicting configs here throw an error
...@@ -1633,6 +1646,11 @@ export async function isPageStatic({ ...@@ -1633,6 +1646,11 @@ export async function isPageStatic({
if (typeof builtConfig.fetchCache === 'undefined') { if (typeof builtConfig.fetchCache === 'undefined') {
builtConfig.fetchCache = fetchCache 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 // any revalidate number overrides false
// shorter revalidate overrides longer (initially) // shorter revalidate overrides longer (initially)
...@@ -1657,10 +1675,18 @@ export async function isPageStatic({ ...@@ -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 // If force dynamic was set and we don't have PPR enabled, then set the
// revalidate to 0. // revalidate to 0.
// TODO: (PPR) remove this once PPR is enabled by default // 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 appConfig.revalidate = 0
} }
...@@ -1679,7 +1705,6 @@ export async function isPageStatic({ ...@@ -1679,7 +1705,6 @@ export async function isPageStatic({
isrFlushToDisk, isrFlushToDisk,
maxMemoryCacheSize, maxMemoryCacheSize,
cacheHandler, cacheHandler,
ppr,
ComponentMod, ComponentMod,
})) }))
} }
...@@ -1757,21 +1782,13 @@ export async function isPageStatic({ ...@@ -1757,21 +1782,13 @@ export async function isPageStatic({
// When PPR is enabled, any route may be completely static, so // When PPR is enabled, any route may be completely static, so
// mark this route as static. // mark this route as static.
let isPPR = false if (isRoutePPREnabled) {
if (supportsPPR) {
isPPR = true
isStatic = true 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 { return {
isStatic, isStatic,
isPPR, isRoutePPREnabled,
isHybridAmp: config.amp === 'hybrid', isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true, isAmpOnly: config.amp === true,
prerenderRoutes, prerenderRoutes,
......
...@@ -5,6 +5,7 @@ import type { ...@@ -5,6 +5,7 @@ import type {
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info' import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { needsExperimentalReact } from '../../../lib/needs-experimental-react' import { needsExperimentalReact } from '../../../lib/needs-experimental-react'
import { checkIsAppPPREnabled } from '../../../server/lib/experimental/ppr'
function errorIfEnvConflicted(config: NextConfigComplete, key: string) { function errorIfEnvConflicted(config: NextConfigComplete, key: string) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key) const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
...@@ -165,7 +166,7 @@ export function getDefineEnv({ ...@@ -165,7 +166,7 @@ export function getDefineEnv({
? 'nodejs' ? 'nodejs'
: '', : '',
'process.env.NEXT_MINIMAL': '', '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_DEPLOYMENT_ID': config.deploymentId || false,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '', 'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',
'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [], 'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],
......
...@@ -80,6 +80,7 @@ checkFields<Diff<{ ...@@ -80,6 +80,7 @@ checkFields<Diff<{
generateMetadata?: Function generateMetadata?: Function
viewport?: any viewport?: any
generateViewport?: Function generateViewport?: Function
experimental_ppr?: boolean
` `
} }
}, TEntry, ''>>() }, TEntry, ''>>()
......
...@@ -14,7 +14,7 @@ export async function createIncrementalCache({ ...@@ -14,7 +14,7 @@ export async function createIncrementalCache({
distDir, distDir,
dir, dir,
enabledDirectories, enabledDirectories,
experimental, isAppPPREnabled,
flushToDisk, flushToDisk,
}: { }: {
cacheHandler?: string cacheHandler?: string
...@@ -23,7 +23,7 @@ export async function createIncrementalCache({ ...@@ -23,7 +23,7 @@ export async function createIncrementalCache({
distDir: string distDir: string
dir: string dir: string
enabledDirectories: NextEnabledDirectories enabledDirectories: NextEnabledDirectories
experimental: { ppr: boolean } isAppPPREnabled: boolean
flushToDisk?: boolean flushToDisk?: boolean
}) { }) {
// Custom cache handler overrides. // Custom cache handler overrides.
...@@ -60,7 +60,7 @@ export async function createIncrementalCache({ ...@@ -60,7 +60,7 @@ export async function createIncrementalCache({
serverDistDir: path.join(distDir, 'server'), serverDistDir: path.join(distDir, 'server'),
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
minimalMode: hasNextSupport, minimalMode: hasNextSupport,
experimental, isAppPPREnabled,
}) })
;(globalThis as any).__incrementalCache = incrementalCache ;(globalThis as any).__incrementalCache = incrementalCache
......
...@@ -57,6 +57,7 @@ import { validateRevalidate } from '../server/lib/patch-fetch' ...@@ -57,6 +57,7 @@ import { validateRevalidate } from '../server/lib/patch-fetch'
import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace' import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace'
import { createProgress } from '../build/progress' import { createProgress } from '../build/progress'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { checkIsAppPPREnabled } from '../server/lib/experimental/ppr'
export class ExportError extends Error { export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR' code = 'NEXT_EXPORT_ERROR'
...@@ -422,7 +423,7 @@ export async function exportAppImpl( ...@@ -422,7 +423,7 @@ export async function exportAppImpl(
strictNextHead: !!nextConfig.experimental.strictNextHead, strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.deploymentId, deploymentId: nextConfig.deploymentId,
experimental: { experimental: {
ppr: nextConfig.experimental.ppr === true, isAppPPREnabled: checkIsAppPPREnabled(nextConfig.experimental.ppr),
missingSuspenseWithCSRBailout: missingSuspenseWithCSRBailout:
nextConfig.experimental.missingSuspenseWithCSRBailout === true, nextConfig.experimental.missingSuspenseWithCSRBailout === true,
swrDelta: nextConfig.experimental.swrDelta, swrDelta: nextConfig.experimental.swrDelta,
......
...@@ -64,7 +64,7 @@ export async function exportAppPage( ...@@ -64,7 +64,7 @@ export async function exportAppPage(
const { flightData, revalidate = false, postponed, fetchTags } = metadata const { flightData, revalidate = false, postponed, fetchTags } = metadata
// Ensure we don't postpone without having PPR enabled. // 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') throw new Error('Invariant: page postponed without PPR being enabled')
} }
...@@ -93,8 +93,9 @@ export async function exportAppPage( ...@@ -93,8 +93,9 @@ export async function exportAppPage(
} }
// If PPR is enabled, we want to emit a prefetch rsc file for the page // 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 // instead of the standard rsc. This is because the standard rsc will
// contain the dynamic data. // contain the dynamic data. We do this if any routes have PPR enabled so
else if (renderOpts.experimental.ppr) { // 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 // If PPR is enabled, we should emit the flight data as the prefetch
// payload. // payload.
await fileWriter( await fileWriter(
...@@ -113,12 +114,6 @@ export async function exportAppPage( ...@@ -113,12 +114,6 @@ export async function exportAppPage(
const headers: OutgoingHttpHeaders = { ...metadata.headers } 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) { if (fetchTags) {
headers[NEXT_CACHE_TAGS_HEADER] = fetchTags headers[NEXT_CACHE_TAGS_HEADER] = fetchTags
} }
...@@ -133,10 +128,11 @@ export async function exportAppPage( ...@@ -133,10 +128,11 @@ export async function exportAppPage(
const isParallelRoute = /\/@\w+/.test(page) const isParallelRoute = /\/@\w+/.test(page)
const isNonSuccessfulStatusCode = res.statusCode > 300 const isNonSuccessfulStatusCode = res.statusCode > 300
// When PPR is enabled, we don't always send 200 for routes that have been // 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 // pregenerated, so we should grab the status code from the mocked
// response. // response.
let status: number | undefined = renderOpts.experimental.ppr let status: number | undefined = renderOpts.experimental.isRoutePPREnabled
? res.statusCode ? res.statusCode
: undefined : undefined
......
...@@ -64,7 +64,6 @@ export async function exportAppRoute( ...@@ -64,7 +64,6 @@ export async function exportAppRoute(
notFoundRoutes: [], notFoundRoutes: [],
}, },
renderOpts: { renderOpts: {
experimental: { ppr: false },
originalPathname: page, originalPathname: page,
nextExport: true, nextExport: true,
supportsDynamicHTML: false, supportsDynamicHTML: false,
......
...@@ -83,13 +83,13 @@ async function exportPageImpl( ...@@ -83,13 +83,13 @@ async function exportPageImpl(
// Check if this is an `app/` page. // Check if this is an `app/` page.
_isAppDir: isAppDir = false, _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. // Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false, _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. // Pull the original query out.
query: originalQuery = {}, query: originalQuery = {},
} = pathMap } = pathMap
...@@ -231,8 +231,7 @@ async function exportPageImpl( ...@@ -231,8 +231,7 @@ async function exportPageImpl(
distDir, distDir,
dir, dir,
enabledDirectories, enabledDirectories,
// PPR is not available for Pages. isAppPPREnabled: input.renderOpts.experimental.isAppPPREnabled,
experimental: { ppr: false },
// skip writing to disk in minimal mode for now, pending some // skip writing to disk in minimal mode for now, pending some
// changes to better support it // changes to better support it
flushToDisk: !hasNextSupport, flushToDisk: !hasNextSupport,
...@@ -271,6 +270,10 @@ async function exportPageImpl( ...@@ -271,6 +270,10 @@ async function exportPageImpl(
locale, locale,
supportsDynamicHTML: false, supportsDynamicHTML: false,
originalPathname: page, originalPathname: page,
experimental: {
...input.renderOpts.experimental,
isRoutePPREnabled,
},
} }
if (hasNextSupport) { if (hasNextSupport) {
......
...@@ -707,10 +707,29 @@ async function renderToHTMLOrFlightImpl( ...@@ -707,10 +707,29 @@ async function renderToHTMLOrFlightImpl(
const isNextExport = !!renderOpts.nextExport const isNextExport = !!renderOpts.nextExport
const { staticGenerationStore, requestStore } = baseCtx const { staticGenerationStore, requestStore } = baseCtx
const { isStaticGeneration } = staticGenerationStore 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 = * Sets the headers on the response object. If we're generating static HTML,
renderOpts.experimental.ppr && isStaticGeneration * 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({ const serverComponentsErrorHandler = createErrorHandler({
source: ErrorHandlerSource.serverComponents, source: ErrorHandlerSource.serverComponents,
...@@ -788,7 +807,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -788,7 +807,7 @@ async function renderToHTMLOrFlightImpl(
const shouldProvideFlightRouterState = const shouldProvideFlightRouterState =
isRSCRequest && isRSCRequest &&
(!isPrefetchRSCRequest || (!isPrefetchRSCRequest ||
!renderOpts.experimental.ppr || !isRoutePPREnabled ||
// Interception routes currently depend on the flight router state to // Interception routes currently depend on the flight router state to
// extract dynamic params. // extract dynamic params.
isInterceptionRouteAppPath(pagePath)) isInterceptionRouteAppPath(pagePath))
...@@ -950,28 +969,22 @@ async function renderToHTMLOrFlightImpl( ...@@ -950,28 +969,22 @@ async function renderToHTMLOrFlightImpl(
const isResume = !!renderOpts.postponed const isResume = !!renderOpts.postponed
const onHeaders = staticGenerationStore.prerenderState const onHeaders =
? // During prerender we write headers to metadata // During prerenders, we want to capture the headers created so we can
(headers: Headers) => { // persist them to the metadata.
headers.forEach((value, key) => { staticGenerationStore.prerenderState ||
metadata.headers ??= {} // During static generation and during resumes we don't
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 // ask React to emit headers. For Resume this is just not supported
// For static generation we know there will be an entire HTML document // For static generation we know there will be an entire HTML document
// output and so moving from tag to header for preloading can only // output and so moving from tag to header for preloading can only
// server to alter preloading priorities in unwanted ways // server to alter preloading priorities in unwanted ways
undefined (!isStaticGeneration && !isResume)
: // During dynamic renders that are not resumes we write ? (headers: Headers) => {
// early headers to the response
(headers: Headers) => {
headers.forEach((value, key) => { headers.forEach((value, key) => {
res.appendHeader(key, value) setHeader(key, value)
}) })
} }
: undefined
const getServerInsertedHTML = makeGetServerInsertedHTML({ const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills, polyfills,
...@@ -981,7 +994,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -981,7 +994,7 @@ async function renderToHTMLOrFlightImpl(
}) })
const renderer = createStaticRenderer({ const renderer = createStaticRenderer({
ppr: renderOpts.experimental.ppr, isRoutePPREnabled,
isStaticGeneration, isStaticGeneration,
// If provided, the postpone state should be parsed as JSON so it can be // If provided, the postpone state should be parsed as JSON so it can be
// provided to React. // provided to React.
...@@ -1086,7 +1099,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1086,7 +1099,7 @@ async function renderToHTMLOrFlightImpl(
// We postponed but nothing dynamic was used. We resume the render now and immediately abort it // 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 // so we can set all the postponed boundaries to client render mode before we store the HTML response
const resumeRenderer = createStaticRenderer({ const resumeRenderer = createStaticRenderer({
ppr: true, isRoutePPREnabled,
isStaticGeneration: false, isStaticGeneration: false,
postponed: getDynamicHTMLPostponedState(postponed), postponed: getDynamicHTMLPostponedState(postponed),
streamOptions: { streamOptions: {
...@@ -1232,14 +1245,14 @@ async function renderToHTMLOrFlightImpl( ...@@ -1232,14 +1245,14 @@ async function renderToHTMLOrFlightImpl(
// If there were mutable cookies set, we need to set them on the // If there were mutable cookies set, we need to set them on the
// response. // response.
if (appendMutableCookies(headers, err.mutableCookies)) { if (appendMutableCookies(headers, err.mutableCookies)) {
res.setHeader('set-cookie', Array.from(headers.values())) setHeader('set-cookie', Array.from(headers.values()))
} }
} }
const redirectUrl = addPathPrefix( const redirectUrl = addPathPrefix(
getURLFromRedirectError(err), getURLFromRedirectError(err),
renderOpts.basePath renderOpts.basePath
) )
res.setHeader('Location', redirectUrl) setHeader('Location', redirectUrl)
} }
const is404 = res.statusCode === 404 const is404 = res.statusCode === 404
......
...@@ -413,7 +413,7 @@ async function createComponentTreeInternal({ ...@@ -413,7 +413,7 @@ async function createComponentTreeInternal({
// possible during both prefetches and dynamic navigations. But during // possible during both prefetches and dynamic navigations. But during
// the beta period, we should be clear about this trade off in our // the beta period, we should be clear about this trade off in our
// communications. // communications.
!experimental.ppr !experimental.isRoutePPREnabled
) { ) {
// Don't prefetch this child. This will trigger a lazy fetch by the // Don't prefetch this child. This will trigger a lazy fetch by the
// client router. // client router.
......
...@@ -111,10 +111,10 @@ export function getDynamicDataPostponedState(): DynamicDataPostponedState { ...@@ -111,10 +111,10 @@ export function getDynamicDataPostponedState(): DynamicDataPostponedState {
type Options = { type Options = {
/** /**
* Whether or not PPR is enabled. This is used to determine which renderer to * Whether or not PPR is enabled for this page. This is used to determine
* use. * which renderer to use.
*/ */
ppr: boolean isRoutePPREnabled: boolean
/** /**
* Whether or not this is a static generation render. This is used to * Whether or not this is a static generation render. This is used to
...@@ -138,7 +138,7 @@ type Options = { ...@@ -138,7 +138,7 @@ type Options = {
} }
export function createStaticRenderer({ export function createStaticRenderer({
ppr, isRoutePPREnabled,
isStaticGeneration, isStaticGeneration,
postponed, postponed,
streamOptions: { streamOptions: {
...@@ -152,7 +152,7 @@ export function createStaticRenderer({ ...@@ -152,7 +152,7 @@ export function createStaticRenderer({
formState, formState,
}, },
}: Options): Renderer { }: Options): Renderer {
if (ppr) { if (isRoutePPREnabled) {
if (isStaticGeneration) { if (isStaticGeneration) {
// This is a Prerender // This is a Prerender
return new StaticRenderer({ return new StaticRenderer({
......
...@@ -159,7 +159,16 @@ export interface RenderOptsPartial { ...@@ -159,7 +159,16 @@ export interface RenderOptsPartial {
params?: ParsedUrlQuery params?: ParsedUrlQuery
isPrefetch?: boolean isPrefetch?: boolean
experimental: { 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 missingSuspenseWithCSRBailout: boolean
swrDelta: SwrDelta | undefined swrDelta: SwrDelta | undefined
} }
......
...@@ -113,7 +113,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -113,7 +113,7 @@ export async function walkTreeWithFlightRouterState({
const shouldSkipComponentTree = const shouldSkipComponentTree =
// loading.tsx has no effect on prefetching when PPR is enabled // loading.tsx has no effect on prefetching when PPR is enabled
!experimental.ppr && !experimental.isRoutePPREnabled &&
isPrefetch && isPrefetch &&
!Boolean(components.loading) && !Boolean(components.loading) &&
(flightRouterState || (flightRouterState ||
......
...@@ -16,7 +16,7 @@ export type StaticGenerationContext = { ...@@ -16,7 +16,7 @@ export type StaticGenerationContext = {
fetchCache?: StaticGenerationStore['fetchCache'] fetchCache?: StaticGenerationStore['fetchCache']
isServerAction?: boolean isServerAction?: boolean
waitUntil?: Promise<any> waitUntil?: Promise<any>
experimental: { ppr: boolean; missingSuspenseWithCSRBailout?: boolean } experimental?: Pick<RenderOptsPartial['experimental'], 'isRoutePPREnabled'>
/** /**
* Fetch metrics attached in patch-fetch.ts * Fetch metrics attached in patch-fetch.ts
...@@ -77,7 +77,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -77,7 +77,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
!renderOpts.isServerAction !renderOpts.isServerAction
const prerenderState: StaticGenerationStore['prerenderState'] = const prerenderState: StaticGenerationStore['prerenderState'] =
isStaticGeneration && renderOpts.experimental.ppr isStaticGeneration && renderOpts.experimental?.isRoutePPREnabled
? createPrerenderState(renderOpts.isDebugPPRSkeleton) ? createPrerenderState(renderOpts.isDebugPPRSkeleton)
: null : null
......
...@@ -12,7 +12,11 @@ import type { ...@@ -12,7 +12,11 @@ import type {
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { RenderOptsPartial as PagesRenderOptsPartial } from './render' import type { RenderOptsPartial as PagesRenderOptsPartial } from './render'
import type { RenderOptsPartial as AppRenderOptsPartial } from './app-render/types' import type { RenderOptsPartial as AppRenderOptsPartial } from './app-render/types'
import type { ResponseCacheBase, ResponseCacheEntry } from './response-cache' import type {
ResponseCacheBase,
ResponseCacheEntry,
ResponseGenerator,
} from './response-cache'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import { import {
NormalizeError, NormalizeError,
...@@ -138,6 +142,7 @@ import { toRoute } from './lib/to-route' ...@@ -138,6 +142,7 @@ import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers' import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'
import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header' import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'
import { checkIsAppPPREnabled } from './lib/experimental/ppr'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -472,14 +477,16 @@ export default abstract class Server< ...@@ -472,14 +477,16 @@ export default abstract class Server<
this.enabledDirectories = this.getEnabledDirectories(dev) this.enabledDirectories = this.getEnabledDirectories(dev)
const isAppPPREnabled =
this.enabledDirectories.app &&
checkIsAppPPREnabled(this.nextConfig.experimental.ppr)
this.normalizers = { this.normalizers = {
// We should normalize the pathname from the RSC prefix only in minimal // We should normalize the pathname from the RSC prefix only in minimal
// mode as otherwise that route is not exposed external to the server as // mode as otherwise that route is not exposed external to the server as
// we instead only rely on the headers. // we instead only rely on the headers.
postponed: postponed:
this.enabledDirectories.app && isAppPPREnabled && this.minimalMode
this.nextConfig.experimental.ppr &&
this.minimalMode
? new PostponedPathnameNormalizer() ? new PostponedPathnameNormalizer()
: undefined, : undefined,
rsc: rsc:
...@@ -487,9 +494,7 @@ export default abstract class Server< ...@@ -487,9 +494,7 @@ export default abstract class Server<
? new RSCPathnameNormalizer() ? new RSCPathnameNormalizer()
: undefined, : undefined,
prefetchRSC: prefetchRSC:
this.enabledDirectories.app && isAppPPREnabled && this.minimalMode
this.nextConfig.experimental.ppr &&
this.minimalMode
? new PrefetchRSCPathnameNormalizer() ? new PrefetchRSCPathnameNormalizer()
: undefined, : undefined,
data: this.enabledDirectories.pages data: this.enabledDirectories.pages
...@@ -549,9 +554,7 @@ export default abstract class Server< ...@@ -549,9 +554,7 @@ export default abstract class Server<
// @ts-expect-error internal field not publicly exposed // @ts-expect-error internal field not publicly exposed
isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile, isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,
experimental: { experimental: {
ppr: isAppPPREnabled,
this.enabledDirectories.app &&
this.nextConfig.experimental.ppr === true,
missingSuspenseWithCSRBailout: missingSuspenseWithCSRBailout:
this.nextConfig.experimental.missingSuspenseWithCSRBailout === true, this.nextConfig.experimental.missingSuspenseWithCSRBailout === true,
swrDelta: this.nextConfig.experimental.swrDelta, swrDelta: this.nextConfig.experimental.swrDelta,
...@@ -1942,16 +1945,53 @@ export default abstract class Server< ...@@ -1942,16 +1945,53 @@ export default abstract class Server<
// Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later // Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
const isRSCRequest = isRSCRequestCheck(req) const isRSCRequest = isRSCRequestCheck(req)
const { routeModule } = components
/**
* If the route being rendered is an app page, and the ppr feature has been
* enabled, then the given route _could_ support PPR.
*/
const couldSupportPPR: boolean =
typeof routeModule !== 'undefined' &&
isAppPageRouteModule(routeModule) &&
this.renderOpts.experimental.isAppPPREnabled
// If this is a request that's rendering an app page that support's PPR,
// then if we're in development mode (or using the experimental test
// proxy) and the query parameter is set, then we should render the
// skeleton. We assume that if the page _could_ support it, we should
// show the skeleton in development. Ideally we would check the appConfig
// to see if this page has it enabled or not, but that would require
// plumbing the appConfig through to the server during development.
const isDebugPPRSkeleton =
query.__nextppronly &&
couldSupportPPR &&
(this.renderOpts.dev || this.experimentalTestProxy)
? true
: false
// This page supports PPR if it has `experimentalPPR` set to `true` in the
// prerender manifest and this is an app page.
const isRoutePPREnabled: boolean =
couldSupportPPR &&
((
prerenderManifest.routes[pathname] ??
prerenderManifest.dynamicRoutes[pathname]
)?.experimentalPPR === true ||
isDebugPPRSkeleton)
// If we're in minimal mode, then try to get the postponed information from // If we're in minimal mode, then try to get the postponed information from
// the request metadata. If available, use it for resuming the postponed // the request metadata. If available, use it for resuming the postponed
// render. // render.
const minimalPostponed = getRequestMeta(req, 'postponed') const minimalPostponed = isRoutePPREnabled
? getRequestMeta(req, 'postponed')
: undefined
// If PPR is enabled, and this is a RSC request (but not a prefetch), then // If PPR is enabled, and this is a RSC request (but not a prefetch), then
// we can use this fact to only generate the flight data for the request // we can use this fact to only generate the flight data for the request
// because we can't cache the HTML (as it's also dynamic). // because we can't cache the HTML (as it's also dynamic).
const isDynamicRSCRequest = const isDynamicRSCRequest =
opts.experimental.ppr && isRSCRequest && !isPrefetchRSCRequest isRoutePPREnabled && isRSCRequest && !isPrefetchRSCRequest
// we need to ensure the status code if /404 is visited directly // we need to ensure the status code if /404 is visited directly
if (is404Page && !isDataReq && !isRSCRequest) { if (is404Page && !isDataReq && !isRSCRequest) {
...@@ -1991,9 +2031,9 @@ export default abstract class Server< ...@@ -1991,9 +2031,9 @@ export default abstract class Server<
} }
} }
if (!query.amp) { // Ensure that if the `amp` query parameter is falsy that we remove it from
delete query.amp // the query object. This ensures it won't be found by the `in` operator.
} if ('amp' in query && !query.amp) delete query.amp
if (opts.supportsDynamicHTML === true) { if (opts.supportsDynamicHTML === true) {
const isBotRequest = isBot(req.headers['user-agent'] || '') const isBotRequest = isBot(req.headers['user-agent'] || '')
...@@ -2185,10 +2225,9 @@ export default abstract class Server< ...@@ -2185,10 +2225,9 @@ export default abstract class Server<
| 'https', | 'https',
})) }))
// TODO: investigate, this is not safe across multiple concurrent requests
incrementalCache?.resetRequestCache() incrementalCache?.resetRequestCache()
const { routeModule } = components
type Renderer = (context: { type Renderer = (context: {
/** /**
* The postponed data for this render. This is only provided when resuming * The postponed data for this render. This is only provided when resuming
...@@ -2197,14 +2236,6 @@ export default abstract class Server< ...@@ -2197,14 +2236,6 @@ export default abstract class Server<
postponed: string | undefined postponed: string | undefined
}) => Promise<ResponseCacheEntry | null> }) => Promise<ResponseCacheEntry | null>
// allow debugging the skeleton in dev with PPR
// instead of continuing to resume stream right away
const isDebugPPRSkeleton = Boolean(
this.nextConfig.experimental.ppr &&
(this.renderOpts.dev || this.experimentalTestProxy) &&
query.__nextppronly
)
const doRender: Renderer = async ({ postponed }) => { const doRender: Renderer = async ({ postponed }) => {
// In development, we always want to generate dynamic HTML. // In development, we always want to generate dynamic HTML.
let supportsDynamicHTML: boolean = let supportsDynamicHTML: boolean =
...@@ -2271,7 +2302,10 @@ export default abstract class Server< ...@@ -2271,7 +2302,10 @@ export default abstract class Server<
query: origQuery, query: origQuery,
}) })
: resolvedUrl, : resolvedUrl,
experimental: {
...opts.experimental,
isRoutePPREnabled,
},
supportsDynamicHTML, supportsDynamicHTML,
isOnDemandRevalidate, isOnDemandRevalidate,
isDraftMode: isPreviewMode, isDraftMode: isPreviewMode,
...@@ -2310,8 +2344,6 @@ export default abstract class Server< ...@@ -2310,8 +2344,6 @@ export default abstract class Server<
params: opts.params, params: opts.params,
prerenderManifest, prerenderManifest,
renderOpts: { renderOpts: {
// App Route's cannot postpone, so don't enable it.
experimental: { ppr: false },
originalPathname: components.ComponentMod.originalPathname, originalPathname: components.ComponentMod.originalPathname,
supportsDynamicHTML, supportsDynamicHTML,
incrementalCache, incrementalCache,
...@@ -2451,7 +2483,7 @@ export default abstract class Server< ...@@ -2451,7 +2483,7 @@ export default abstract class Server<
isSSG && isSSG &&
metadata.revalidate === 0 && metadata.revalidate === 0 &&
!this.renderOpts.dev && !this.renderOpts.dev &&
!renderOpts.experimental.ppr !isRoutePPREnabled
) { ) {
const staticBailoutInfo = metadata.staticBailoutInfo const staticBailoutInfo = metadata.staticBailoutInfo
...@@ -2510,9 +2542,7 @@ export default abstract class Server< ...@@ -2510,9 +2542,7 @@ export default abstract class Server<
} }
} }
const cacheEntry = await this.responseCache.get( const responseGenerator: ResponseGenerator = async (
ssgCacheKey,
async (
hasResolved, hasResolved,
previousCacheEntry, previousCacheEntry,
isRevalidating isRevalidating
...@@ -2531,10 +2561,7 @@ export default abstract class Server< ...@@ -2531,10 +2561,7 @@ export default abstract class Server<
: { staticPaths: undefined, fallbackMode: false }) : { staticPaths: undefined, fallbackMode: false })
} }
if ( if (fallbackMode === 'static' && isBot(req.headers['user-agent'] || '')) {
fallbackMode === 'static' &&
isBot(req.headers['user-agent'] || '')
) {
fallbackMode = 'blocking' fallbackMode = 'blocking'
} }
...@@ -2666,7 +2693,11 @@ export default abstract class Server< ...@@ -2666,7 +2693,11 @@ export default abstract class Server<
? result.revalidate ? result.revalidate
: /* default to minimum revalidate (this should be an invariant) */ 1, : /* default to minimum revalidate (this should be an invariant) */ 1,
} }
}, }
const cacheEntry = await this.responseCache.get(
ssgCacheKey,
responseGenerator,
{ {
routeKind: routeModule?.definition.kind, routeKind: routeModule?.definition.kind,
incrementalCache, incrementalCache,
...@@ -2688,7 +2719,8 @@ export default abstract class Server< ...@@ -2688,7 +2719,8 @@ export default abstract class Server<
} }
const didPostpone = const didPostpone =
cacheEntry.value?.kind === 'PAGE' && !!cacheEntry.value.postponed cacheEntry.value?.kind === 'PAGE' &&
typeof cacheEntry.value.postponed === 'string'
if ( if (
isSSG && isSSG &&
...@@ -2736,7 +2768,7 @@ export default abstract class Server< ...@@ -2736,7 +2768,7 @@ export default abstract class Server<
this.minimalMode && this.minimalMode &&
isRSCRequest && isRSCRequest &&
!isPrefetchRSCRequest && !isPrefetchRSCRequest &&
opts.experimental.ppr isRoutePPREnabled
) { ) {
revalidate = 0 revalidate = 0
} else if ( } else if (
...@@ -2897,7 +2929,7 @@ export default abstract class Server< ...@@ -2897,7 +2929,7 @@ export default abstract class Server<
// If the request is a data request, then we shouldn't set the status code // If the request is a data request, then we shouldn't set the status code
// from the response because it should always be 200. This should be gated // from the response because it should always be 200. This should be gated
// behind the experimental PPR flag. // behind the experimental PPR flag.
if (cachedData.status && (!isDataReq || !opts.experimental.ppr)) { if (cachedData.status && (!isDataReq || !isRoutePPREnabled)) {
res.statusCode = cachedData.status res.statusCode = cachedData.status
} }
......
...@@ -35,8 +35,8 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record( ...@@ -35,8 +35,8 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
query: z.any(), // NextParsedUrlQuery query: z.any(), // NextParsedUrlQuery
// private optional properties // private optional properties
_isAppDir: z.boolean().optional(), _isAppDir: z.boolean().optional(),
_isAppPrefetch: z.boolean().optional(),
_isDynamicError: z.boolean().optional(), _isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(),
}) })
) )
...@@ -313,7 +313,10 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -313,7 +313,10 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
parallelServerCompiles: z.boolean().optional(), parallelServerCompiles: z.boolean().optional(),
parallelServerBuildTraces: 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(), taint: z.boolean().optional(),
prerenderEarlyExit: z.boolean().optional(), prerenderEarlyExit: z.boolean().optional(),
proxyTimeout: z.number().gte(0).optional(), proxyTimeout: z.number().gte(0).optional(),
......
...@@ -12,6 +12,7 @@ import type { NextParsedUrlQuery } from './request-meta' ...@@ -12,6 +12,7 @@ import type { NextParsedUrlQuery } from './request-meta'
import type { SizeLimit } from '../types' import type { SizeLimit } from '../types'
import type { SwrDelta } from './lib/revalidate' import type { SwrDelta } from './lib/revalidate'
import type { SupportedTestRunners } from '../cli/next-test' import type { SupportedTestRunners } from '../cli/next-test'
import type { ExperimentalPPRConfig } from './lib/experimental/ppr'
export type NextConfigComplete = Required<NextConfig> & { export type NextConfigComplete = Required<NextConfig> & {
images: Required<ImageConfigComplete> images: Required<ImageConfigComplete>
...@@ -382,7 +383,7 @@ export interface ExperimentalConfig { ...@@ -382,7 +383,7 @@ export interface ExperimentalConfig {
/** /**
* Using this feature will enable the `react@experimental` for the `app` directory. * Using this feature will enable the `react@experimental` for the `app` directory.
*/ */
ppr?: boolean ppr?: ExperimentalPPRConfig
/** /**
* Enables experimental taint APIs in React. * Enables experimental taint APIs in React.
...@@ -466,9 +467,21 @@ export type ExportPathMap = { ...@@ -466,9 +467,21 @@ export type ExportPathMap = {
[path: string]: { [path: string]: {
page: string page: string
query?: NextParsedUrlQuery query?: NextParsedUrlQuery
/**
* @internal
*/
_isAppDir?: boolean _isAppDir?: boolean
_isAppPrefetch?: boolean
/**
* @internal
*/
_isDynamicError?: boolean _isDynamicError?: boolean
/**
* @internal
*/
_isRoutePPREnabled?: boolean
} }
} }
......
...@@ -715,7 +715,6 @@ export default class DevServer extends Server { ...@@ -715,7 +715,6 @@ export default class DevServer extends Server {
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix, fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk, isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize, maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
ppr: this.nextConfig.experimental.ppr === true,
}) })
return pathsResult return pathsResult
} finally { } finally {
......
...@@ -38,7 +38,6 @@ export async function loadStaticPaths({ ...@@ -38,7 +38,6 @@ export async function loadStaticPaths({
maxMemoryCacheSize, maxMemoryCacheSize,
requestHeaders, requestHeaders,
cacheHandler, cacheHandler,
ppr,
}: { }: {
dir: string dir: string
distDir: string distDir: string
...@@ -54,7 +53,6 @@ export async function loadStaticPaths({ ...@@ -54,7 +53,6 @@ export async function loadStaticPaths({
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
cacheHandler?: string cacheHandler?: string
ppr: boolean
}): Promise<{ }): Promise<{
paths?: string[] paths?: string[]
encodedPaths?: string[] encodedPaths?: string[]
...@@ -109,7 +107,6 @@ export async function loadStaticPaths({ ...@@ -109,7 +107,6 @@ export async function loadStaticPaths({
isrFlushToDisk, isrFlushToDisk,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
maxMemoryCacheSize, maxMemoryCacheSize,
ppr,
ComponentMod: components.ComponentMod, 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< ...@@ -19,7 +19,12 @@ type FileSystemCacheContext = Omit<
> & { > & {
fs: CacheFs fs: CacheFs
serverDistDir: string 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 = { type TagsManifest = {
...@@ -37,7 +42,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -37,7 +42,7 @@ export default class FileSystemCache implements CacheHandler {
private pagesDir: boolean private pagesDir: boolean
private tagsManifestPath?: string private tagsManifestPath?: string
private revalidatedTags: string[] private revalidatedTags: string[]
private readonly experimental: { ppr: boolean } private readonly isAppPPREnabled: boolean
private debug: boolean private debug: boolean
constructor(ctx: FileSystemCacheContext) { constructor(ctx: FileSystemCacheContext) {
...@@ -47,7 +52,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -47,7 +52,7 @@ export default class FileSystemCache implements CacheHandler {
this.appDir = !!ctx._appDir this.appDir = !!ctx._appDir
this.pagesDir = !!ctx._pagesDir this.pagesDir = !!ctx._pagesDir
this.revalidatedTags = ctx.revalidatedTags this.revalidatedTags = ctx.revalidatedTags
this.experimental = ctx.experimental this.isAppPPREnabled = ctx.isAppPPREnabled
this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
if (ctx.maxMemoryCacheSize && !memoryCache) { if (ctx.maxMemoryCacheSize && !memoryCache) {
...@@ -226,7 +231,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -226,7 +231,7 @@ export default class FileSystemCache implements CacheHandler {
? await this.fs.readFile( ? await this.fs.readFile(
this.getFilePath( this.getFilePath(
`${key}${ `${key}${
this.experimental.ppr ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX this.isAppPPREnabled ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX
}`, }`,
'app' 'app'
), ),
...@@ -370,7 +375,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -370,7 +375,7 @@ export default class FileSystemCache implements CacheHandler {
this.getFilePath( this.getFilePath(
`${key}${ `${key}${
isAppPath isAppPath
? this.experimental.ppr ? this.isAppPPREnabled
? RSC_PREFETCH_SUFFIX ? RSC_PREFETCH_SUFFIX
: RSC_SUFFIX : RSC_SUFFIX
: NEXT_DATA_SUFFIX : NEXT_DATA_SUFFIX
......
...@@ -31,7 +31,7 @@ export interface CacheHandlerContext { ...@@ -31,7 +31,7 @@ export interface CacheHandlerContext {
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
prerenderManifest?: PrerenderManifest prerenderManifest?: PrerenderManifest
revalidatedTags: string[] revalidatedTags: string[]
experimental: { ppr: boolean } isAppPPREnabled?: boolean
_appDir: boolean _appDir: boolean
_pagesDir: boolean _pagesDir: boolean
_requestHeaders: IncrementalCache['requestHeaders'] _requestHeaders: IncrementalCache['requestHeaders']
...@@ -104,7 +104,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -104,7 +104,7 @@ export class IncrementalCache implements IncrementalCacheType {
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
CurCacheHandler, CurCacheHandler,
allowedRevalidateHeaderKeys, allowedRevalidateHeaderKeys,
experimental, isAppPPREnabled,
}: { }: {
fs?: CacheFs fs?: CacheFs
dev: boolean dev: boolean
...@@ -121,7 +121,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -121,7 +121,7 @@ export class IncrementalCache implements IncrementalCacheType {
getPrerenderManifest: () => DeepReadonly<PrerenderManifest> getPrerenderManifest: () => DeepReadonly<PrerenderManifest>
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
CurCacheHandler?: typeof CacheHandler CurCacheHandler?: typeof CacheHandler
experimental: { ppr: boolean } isAppPPREnabled: boolean
}) { }) {
const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
this.hasCustomCacheHandler = Boolean(CurCacheHandler) this.hasCustomCacheHandler = Boolean(CurCacheHandler)
...@@ -193,7 +193,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -193,7 +193,7 @@ export class IncrementalCache implements IncrementalCacheType {
_appDir: !!appDir, _appDir: !!appDir,
_requestHeaders: requestHeaders, _requestHeaders: requestHeaders,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
experimental, isAppPPREnabled,
}) })
} }
} }
...@@ -429,7 +429,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -429,7 +429,7 @@ export class IncrementalCache implements IncrementalCacheType {
cacheKey: string, cacheKey: string,
ctx: { ctx: {
kindHint?: IncrementalCacheKindHint kindHint?: IncrementalCacheKindHint
revalidate?: number | false revalidate?: Revalidate
fetchUrl?: string fetchUrl?: string
fetchIdx?: number fetchIdx?: number
tags?: string[] tags?: string[]
...@@ -551,7 +551,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -551,7 +551,7 @@ export class IncrementalCache implements IncrementalCacheType {
pathname: string, pathname: string,
data: IncrementalCacheValue | null, data: IncrementalCacheValue | null,
ctx: { ctx: {
revalidate?: number | false revalidate?: Revalidate
fetchCache?: boolean fetchCache?: boolean
fetchUrl?: string fetchUrl?: string
fetchIdx?: number fetchIdx?: number
......
...@@ -391,7 +391,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -391,7 +391,7 @@ export default class NextNodeServer extends BaseServer<
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk, !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => this.getPrerenderManifest(), getPrerenderManifest: () => this.getPrerenderManifest(),
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
experimental: this.renderOpts.experimental, isAppPPREnabled: this.renderOpts.experimental.isAppPPREnabled,
}) })
} }
......
...@@ -93,8 +93,8 @@ export default class NextWebServer extends BaseServer< ...@@ -93,8 +93,8 @@ export default class NextWebServer extends BaseServer<
CurCacheHandler: CurCacheHandler:
this.serverOptions.webServerConfig.incrementalCacheHandler, this.serverOptions.webServerConfig.incrementalCacheHandler,
getPrerenderManifest: () => this.getPrerenderManifest(), getPrerenderManifest: () => this.getPrerenderManifest(),
// PPR is not supported in the edge runtime. // PPR is not supported in the Edge runtime.
experimental: { ppr: false }, isAppPPREnabled: false,
}) })
} }
protected getResponseCache() { protected getResponseCache() {
......
...@@ -104,8 +104,6 @@ export class EdgeRouteModuleWrapper { ...@@ -104,8 +104,6 @@ export class EdgeRouteModuleWrapper {
}, },
renderOpts: { renderOpts: {
supportsDynamicHTML: true, supportsDynamicHTML: true,
// App Route's cannot be postponed.
experimental: { ppr: false },
}, },
} }
......
...@@ -317,6 +317,7 @@ describe('ppr-full', () => { ...@@ -317,6 +317,7 @@ describe('ppr-full', () => {
if (signal === 'redirect()') { if (signal === 'redirect()') {
const location = res.headers.get('location') const location = res.headers.get('location')
expect(location).not.toBeNull()
expect(typeof location).toEqual('string') expect(typeof location).toEqual('string')
// The URL returned in `Location` is absolute, so we need to parse it // 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', () => { ...@@ -15,9 +15,7 @@ describe('FileSystemCache', () => {
fs: nodeFs, fs: nodeFs,
serverDistDir: cacheDir, serverDistDir: cacheDir,
revalidatedTags: [], revalidatedTags: [],
experimental: { isAppPPREnabled: false,
ppr: false,
},
}) })
const binary = await fs.readFile( const binary = await fs.readFile(
...@@ -37,7 +35,7 @@ describe('FileSystemCache', () => { ...@@ -37,7 +35,7 @@ describe('FileSystemCache', () => {
{} {}
) )
expect((await fsCache.get('icon.png')).value).toEqual({ expect((await fsCache.get('icon.png'))?.value).toEqual({
body: binary, body: binary,
headers: { headers: {
'Content-Type': 'image/png', 'Content-Type': 'image/png',
...@@ -57,9 +55,7 @@ describe('FileSystemCache (isrMemory 0)', () => { ...@@ -57,9 +55,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
fs: nodeFs, fs: nodeFs,
serverDistDir: cacheDir, serverDistDir: cacheDir,
revalidatedTags: [], revalidatedTags: [],
experimental: { isAppPPREnabled: false,
ppr: false,
},
maxMemoryCacheSize: 0, // disable memory cache maxMemoryCacheSize: 0, // disable memory cache
}) })
...@@ -90,7 +86,7 @@ describe('FileSystemCache (isrMemory 0)', () => { ...@@ -90,7 +86,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
kindHint: 'fetch', kindHint: 'fetch',
}) })
expect(res.value).toEqual({ expect(res?.value).toEqual({
kind: 'FETCH', kind: 'FETCH',
data: { data: {
headers: {}, headers: {},
...@@ -119,7 +115,7 @@ describe('FileSystemCache (isrMemory 0)', () => { ...@@ -119,7 +115,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
kindHint: 'fetch', kindHint: 'fetch',
}) })
expect(res.value).toEqual({ expect(res?.value).toEqual({
kind: 'FETCH', kind: 'FETCH',
data: { headers: {}, body: '1700056381', status: 200, url: '' }, data: { headers: {}, body: '1700056381', status: 200, url: '' },
revalidate: 30, 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