Unverified Commit bf726d3c authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Introduce standalone `experimental.useCache` flag (#75240)

parent 8b71caa9
...@@ -49,7 +49,7 @@ pub async fn get_next_client_transforms_rules( ...@@ -49,7 +49,7 @@ pub async fn get_next_client_transforms_rules(
rules.push(get_debug_fn_name_rule(enable_mdx_rs)); rules.push(get_debug_fn_name_rule(enable_mdx_rs));
} }
let dynamic_io_enabled = *next_config.enable_dynamic_io().await?; let use_cache_enabled = *next_config.enable_use_cache().await?;
let cache_kinds = next_config.cache_kinds().to_resolved().await?; let cache_kinds = next_config.cache_kinds().to_resolved().await?;
let mut is_app_dir = false; let mut is_app_dir = false;
...@@ -77,7 +77,7 @@ pub async fn get_next_client_transforms_rules( ...@@ -77,7 +77,7 @@ pub async fn get_next_client_transforms_rules(
ActionsTransform::Client, ActionsTransform::Client,
encryption_key, encryption_key,
enable_mdx_rs, enable_mdx_rs,
dynamic_io_enabled, use_cache_enabled,
cache_kinds, cache_kinds,
)); ));
} }
......
...@@ -666,6 +666,7 @@ pub struct ExperimentalConfig { ...@@ -666,6 +666,7 @@ pub struct ExperimentalConfig {
react_compiler: Option<ReactCompilerOptionsOrBoolean>, react_compiler: Option<ReactCompilerOptionsOrBoolean>,
#[serde(rename = "dynamicIO")] #[serde(rename = "dynamicIO")]
dynamic_io: Option<bool>, dynamic_io: Option<bool>,
use_cache: Option<bool>,
// --- // ---
// UNSUPPORTED // UNSUPPORTED
// --- // ---
...@@ -1408,6 +1409,18 @@ impl NextConfig { ...@@ -1408,6 +1409,18 @@ impl NextConfig {
Vc::cell(self.experimental.dynamic_io.unwrap_or(false)) Vc::cell(self.experimental.dynamic_io.unwrap_or(false))
} }
#[turbo_tasks::function]
pub fn enable_use_cache(&self) -> Vc<bool> {
Vc::cell(
self.experimental
.use_cache
// "use cache" was originally implicitly enabled with the
// dynamicIO flag, so we transfer the value for dynamicIO to the
// explicit useCache flag to ensure backwards compatibility.
.unwrap_or(self.experimental.dynamic_io.unwrap_or(false)),
)
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn cache_kinds(&self) -> Vc<CacheKinds> { pub fn cache_kinds(&self) -> Vc<CacheKinds> {
Vc::cell( Vc::cell(
......
...@@ -77,7 +77,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -77,7 +77,7 @@ pub async fn get_next_server_transforms_rules(
)); ));
} }
let dynamic_io_enabled = *next_config.enable_dynamic_io().await?; let use_cache_enabled = *next_config.enable_use_cache().await?;
let cache_kinds = next_config.cache_kinds().to_resolved().await?; let cache_kinds = next_config.cache_kinds().to_resolved().await?;
let mut is_app_dir = false; let mut is_app_dir = false;
...@@ -115,7 +115,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -115,7 +115,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Client, ActionsTransform::Client,
encryption_key, encryption_key,
mdx_rs, mdx_rs,
dynamic_io_enabled, use_cache_enabled,
cache_kinds, cache_kinds,
)); ));
...@@ -128,7 +128,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -128,7 +128,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server, ActionsTransform::Server,
encryption_key, encryption_key,
mdx_rs, mdx_rs,
dynamic_io_enabled, use_cache_enabled,
cache_kinds, cache_kinds,
)); ));
...@@ -141,7 +141,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -141,7 +141,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server, ActionsTransform::Server,
encryption_key, encryption_key,
mdx_rs, mdx_rs,
dynamic_io_enabled, use_cache_enabled,
cache_kinds, cache_kinds,
)); ));
......
...@@ -21,14 +21,14 @@ pub fn get_server_actions_transform_rule( ...@@ -21,14 +21,14 @@ pub fn get_server_actions_transform_rule(
transform: ActionsTransform, transform: ActionsTransform,
encryption_key: ResolvedVc<RcStr>, encryption_key: ResolvedVc<RcStr>,
enable_mdx_rs: bool, enable_mdx_rs: bool,
dynamic_io_enabled: bool, use_cache_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>, cache_kinds: ResolvedVc<CacheKinds>,
) -> ModuleRule { ) -> ModuleRule {
let transformer = let transformer =
EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextServerActions { EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextServerActions {
transform, transform,
encryption_key, encryption_key,
dynamic_io_enabled, use_cache_enabled,
cache_kinds, cache_kinds,
}) as _)); }) as _));
ModuleRule::new( ModuleRule::new(
...@@ -44,7 +44,7 @@ pub fn get_server_actions_transform_rule( ...@@ -44,7 +44,7 @@ pub fn get_server_actions_transform_rule(
struct NextServerActions { struct NextServerActions {
transform: ActionsTransform, transform: ActionsTransform,
encryption_key: ResolvedVc<RcStr>, encryption_key: ResolvedVc<RcStr>,
dynamic_io_enabled: bool, use_cache_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>, cache_kinds: ResolvedVc<CacheKinds>,
} }
...@@ -56,7 +56,7 @@ impl CustomTransformer for NextServerActions { ...@@ -56,7 +56,7 @@ impl CustomTransformer for NextServerActions {
&FileName::Real(ctx.file_path_str.into()), &FileName::Real(ctx.file_path_str.into()),
Config { Config {
is_react_server_layer: matches!(self.transform, ActionsTransform::Server), is_react_server_layer: matches!(self.transform, ActionsTransform::Server),
dynamic_io_enabled: self.dynamic_io_enabled, use_cache_enabled: self.use_cache_enabled,
hash_salt: self.encryption_key.await?.to_string(), hash_salt: self.encryption_key.await?.to_string(),
cache_kinds: self.cache_kinds.await?.clone_value(), cache_kinds: self.cache_kinds.await?.clone_value(),
}, },
......
...@@ -31,7 +31,7 @@ use turbo_rcstr::RcStr; ...@@ -31,7 +31,7 @@ use turbo_rcstr::RcStr;
#[serde(deny_unknown_fields, rename_all = "camelCase")] #[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config { pub struct Config {
pub is_react_server_layer: bool, pub is_react_server_layer: bool,
pub dynamic_io_enabled: bool, pub use_cache_enabled: bool,
pub hash_salt: String, pub hash_salt: String,
pub cache_kinds: FxHashSet<RcStr>, pub cache_kinds: FxHashSet<RcStr>,
} }
...@@ -104,7 +104,7 @@ enum ServerActionsErrorKind { ...@@ -104,7 +104,7 @@ enum ServerActionsErrorKind {
span: Span, span: Span,
cache_kind: RcStr, cache_kind: RcStr,
}, },
UseCacheWithoutDynamicIO { UseCacheWithoutExperimentalFlag {
span: Span, span: Span,
directive: String, directive: String,
}, },
...@@ -2684,8 +2684,8 @@ impl DirectiveVisitor<'_> { ...@@ -2684,8 +2684,8 @@ impl DirectiveVisitor<'_> {
location: self.location.clone(), location: self.location.clone(),
}); });
} else if self.is_allowed_position { } else if self.is_allowed_position {
if !self.config.dynamic_io_enabled { if !self.config.use_cache_enabled {
emit_error(ServerActionsErrorKind::UseCacheWithoutDynamicIO { emit_error(ServerActionsErrorKind::UseCacheWithoutExperimentalFlag {
span: *span, span: *span,
directive: value.to_string(), directive: value.to_string(),
}); });
...@@ -3094,11 +3094,11 @@ fn emit_error(error_kind: ServerActionsErrorKind) { ...@@ -3094,11 +3094,11 @@ fn emit_error(error_kind: ServerActionsErrorKind) {
"# "#
}, },
), ),
ServerActionsErrorKind::UseCacheWithoutDynamicIO { span, directive } => ( ServerActionsErrorKind::UseCacheWithoutExperimentalFlag { span, directive } => (
span, span,
formatdoc! { formatdoc! {
r#" r#"
To use "{directive}", please enable the experimental feature flag "dynamicIO" in your Next.js config. To use "{directive}", please enable the experimental feature flag "useCache" in your Next.js config.
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
"# "#
......
...@@ -186,7 +186,7 @@ fn react_server_actions_server_errors(input: PathBuf) { ...@@ -186,7 +186,7 @@ fn react_server_actions_server_errors(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true, use_cache_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(), cache_kinds: FxHashSet::default(),
}, },
...@@ -227,7 +227,7 @@ fn react_server_actions_client_errors(input: PathBuf) { ...@@ -227,7 +227,7 @@ fn react_server_actions_client_errors(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: true, use_cache_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(), cache_kinds: FxHashSet::default(),
}, },
...@@ -286,7 +286,7 @@ fn use_cache_not_allowed(input: PathBuf) { ...@@ -286,7 +286,7 @@ fn use_cache_not_allowed(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: false, use_cache_enabled: false,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]), cache_kinds: FxHashSet::from_iter(["x".into()]),
}, },
......
x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config. x To use "use cache", please enable the experimental feature flag "useCache" in your Next.js config.
| |
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage | Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
| |
......
x To use "use cache: x", please enable the experimental feature flag "dynamicIO" in your Next.js config. x To use "use cache: x", please enable the experimental feature flag "useCache" in your Next.js config.
| |
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage | Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
| |
......
...@@ -567,7 +567,7 @@ fn server_actions_server_fixture(input: PathBuf) { ...@@ -567,7 +567,7 @@ fn server_actions_server_fixture(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true, use_cache_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]), cache_kinds: FxHashSet::from_iter(["x".into()]),
}, },
...@@ -601,7 +601,7 @@ fn next_font_with_directive_fixture(input: PathBuf) { ...@@ -601,7 +601,7 @@ fn next_font_with_directive_fixture(input: PathBuf) {
&FileName::Real("/app/test.tsx".into()), &FileName::Real("/app/test.tsx".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true, use_cache_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(), cache_kinds: FxHashSet::default(),
}, },
...@@ -628,7 +628,7 @@ fn server_actions_client_fixture(input: PathBuf) { ...@@ -628,7 +628,7 @@ fn server_actions_client_fixture(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: true, use_cache_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::default(), cache_kinds: FxHashSet::default(),
}, },
...@@ -931,7 +931,7 @@ fn test_source_maps(input: PathBuf) { ...@@ -931,7 +931,7 @@ fn test_source_maps(input: PathBuf) {
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
server_actions::Config { server_actions::Config {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: true, use_cache_enabled: true,
hash_salt: "".into(), hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter([]), cache_kinds: FxHashSet::from_iter([]),
}, },
......
...@@ -6,6 +6,7 @@ related: ...@@ -6,6 +6,7 @@ related:
title: Related title: Related
description: View related API references. description: View related API references.
links: links:
- app/api-reference/config/next-config-js/useCache
- app/api-reference/config/next-config-js/dynamicIO - app/api-reference/config/next-config-js/dynamicIO
- app/api-reference/config/next-config-js/cacheLife - app/api-reference/config/next-config-js/cacheLife
- app/api-reference/functions/cacheTag - app/api-reference/functions/cacheTag
...@@ -17,14 +18,14 @@ The `use cache` directive designates a component and/or a function to be cached. ...@@ -17,14 +18,14 @@ The `use cache` directive designates a component and/or a function to be cached.
## Usage ## Usage
Enable support for the `use cache` directive with the [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO) flag in your `next.config.ts` file: Enable support for the `use cache` directive with the [`useCache`](/docs/app/api-reference/config/next-config-js/useCache) flag in your `next.config.ts` file:
```ts filename="next.config.ts" switcher ```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
experimental: { experimental: {
dynamicIO: true, useCache: true,
}, },
} }
...@@ -35,13 +36,15 @@ export default nextConfig ...@@ -35,13 +36,15 @@ export default nextConfig
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
dynamicIO: true, useCache: true,
}, },
} }
module.exports = nextConfig module.exports = nextConfig
``` ```
Additionally, `use cache` directives are also enabled when the [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO) flag is set.
Then, you can use the `use cache` directive at the file, component, or function level: Then, you can use the `use cache` directive at the file, component, or function level:
```tsx ```tsx
...@@ -75,7 +78,6 @@ export async function getData() { ...@@ -75,7 +78,6 @@ export async function getData() {
- The return value of the cacheable function must also be serializable. This ensures that the cached data can be stored and retrieved correctly. - The return value of the cacheable function must also be serializable. This ensures that the cached data can be stored and retrieved correctly.
- Functions that use the `use cache` directive must not have any side-effects, such as modifying state, directly manipulating the DOM, or setting timers to execute code at intervals. - Functions that use the `use cache` directive must not have any side-effects, such as modifying state, directly manipulating the DOM, or setting timers to execute code at intervals.
- If used alongside [Partial Prerendering](/docs/app/building-your-application/rendering/partial-prerendering), segments that have `use cache` will be prerendered as part of the static HTML shell. - If used alongside [Partial Prerendering](/docs/app/building-your-application/rendering/partial-prerendering), segments that have `use cache` will be prerendered as part of the static HTML shell.
- The `use cache` directive will be available separately from the [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO) flag in the future.
- Unlike [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) which only supports JSON data, `use cache` can cache any serializable data React can render, including the render output of components. - Unlike [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) which only supports JSON data, `use cache` can cache any serializable data React can render, including the render output of components.
## Examples ## Examples
......
---
title: useCache
description: Learn how to enable the useCache flag in Next.js.
version: canary
---
The `useCache` flag is an experimental feature in Next.js that enables the [`use cache` directive](/docs/app/api-reference/directives/use-cache) to be used independently of [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO). When enabled, you can use `use cache` in your application even if `dynamicIO` is turned off.
## Usage
To enable the `useCache` flag, set it to `true` in the `experimental` section of your `next.config.ts` file:
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useCache: true,
},
}
export default nextConfig
```
When `useCache` is enabled, you can use the following cache functions and configurations:
- The [`use cache` directive](/docs/app/api-reference/directives/use-cache)
- The [`cacheLife` function](/docs/app/api-reference/config/next-config-js/cacheLife) with `use cache`
- The [`cacheTag` function](/docs/app/api-reference/functions/cacheTag)
...@@ -624,5 +624,7 @@ ...@@ -624,5 +624,7 @@
"623": "Invalid quality prop (%s) on \\`next/image\\` does not match \\`images.qualities\\` configured in your \\`next.config.js\\`\\nSee more info: https://nextjs.org/docs/messages/next-image-unconfigured-qualities", "623": "Invalid quality prop (%s) on \\`next/image\\` does not match \\`images.qualities\\` configured in your \\`next.config.js\\`\\nSee more info: https://nextjs.org/docs/messages/next-image-unconfigured-qualities",
"624": "Internal Next.js Error: createMutableActionQueue was called more than once", "624": "Internal Next.js Error: createMutableActionQueue was called more than once",
"625": "Server Actions are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features", "625": "Server Actions are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features",
"626": "Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features" "626": "Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features",
"627": "cacheLife() is only available with the experimental.useCache config.",
"628": "cacheTag() is only available with the experimental.useCache config."
} }
...@@ -304,7 +304,6 @@ export async function buildAppStaticPaths({ ...@@ -304,7 +304,6 @@ export async function buildAppStaticPaths({
const incrementalCache = await createIncrementalCache({ const incrementalCache = await createIncrementalCache({
dir, dir,
distDir, distDir,
dynamicIO,
cacheHandler, cacheHandler,
cacheHandlers, cacheHandlers,
requestHeaders, requestHeaders,
......
...@@ -71,6 +71,7 @@ function getBaseSWCOptions({ ...@@ -71,6 +71,7 @@ function getBaseSWCOptions({
bundleLayer, bundleLayer,
isDynamicIo, isDynamicIo,
cacheHandlers, cacheHandlers,
useCacheEnabled,
}: { }: {
filename: string filename: string
jest?: boolean jest?: boolean
...@@ -89,6 +90,7 @@ function getBaseSWCOptions({ ...@@ -89,6 +90,7 @@ function getBaseSWCOptions({
bundleLayer?: WebpackLayerName bundleLayer?: WebpackLayerName
isDynamicIo?: boolean isDynamicIo?: boolean
cacheHandlers?: ExperimentalConfig['cacheHandlers'] cacheHandlers?: ExperimentalConfig['cacheHandlers']
useCacheEnabled?: boolean
}) { }) {
const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer) const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer)
const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer) const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer)
...@@ -216,7 +218,7 @@ function getBaseSWCOptions({ ...@@ -216,7 +218,7 @@ function getBaseSWCOptions({
isAppRouterPagesLayer && !jest isAppRouterPagesLayer && !jest
? { ? {
isReactServerLayer, isReactServerLayer,
dynamicIoEnabled: isDynamicIo, useCacheEnabled,
hashSalt: serverReferenceHashSalt, hashSalt: serverReferenceHashSalt,
cacheKinds: cacheHandlers ? Object.keys(cacheHandlers) : [], cacheKinds: cacheHandlers ? Object.keys(cacheHandlers) : [],
} }
...@@ -364,6 +366,7 @@ export function getLoaderSWCOptions({ ...@@ -364,6 +366,7 @@ export function getLoaderSWCOptions({
bundleLayer, bundleLayer,
esm, esm,
cacheHandlers, cacheHandlers,
useCacheEnabled,
}: { }: {
filename: string filename: string
development: boolean development: boolean
...@@ -389,6 +392,7 @@ export function getLoaderSWCOptions({ ...@@ -389,6 +392,7 @@ export function getLoaderSWCOptions({
serverReferenceHashSalt: string serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName bundleLayer?: WebpackLayerName
cacheHandlers: ExperimentalConfig['cacheHandlers'] cacheHandlers: ExperimentalConfig['cacheHandlers']
useCacheEnabled?: boolean
}) { }) {
let baseOptions: any = getBaseSWCOptions({ let baseOptions: any = getBaseSWCOptions({
filename, filename,
...@@ -407,6 +411,7 @@ export function getLoaderSWCOptions({ ...@@ -407,6 +411,7 @@ export function getLoaderSWCOptions({
esm: !!esm, esm: !!esm,
isDynamicIo, isDynamicIo,
cacheHandlers, cacheHandlers,
useCacheEnabled,
}) })
baseOptions.fontLoaders = { baseOptions.fontLoaders = {
fontLoaders: ['next/font/local', 'next/font/google'], fontLoaders: ['next/font/local', 'next/font/google'],
......
...@@ -1006,7 +1006,6 @@ export async function isPageStatic({ ...@@ -1006,7 +1006,6 @@ export async function isPageStatic({
cacheHandlers, cacheHandlers,
distDir, distDir,
dir, dir,
dynamicIO,
flushToDisk: isrFlushToDisk, flushToDisk: isrFlushToDisk,
cacheMaxMemorySize: maxMemoryCacheSize, cacheMaxMemorySize: maxMemoryCacheSize,
}) })
......
...@@ -149,6 +149,7 @@ async function loaderTransform( ...@@ -149,6 +149,7 @@ async function loaderTransform(
bundleLayer, bundleLayer,
esm, esm,
cacheHandlers: nextConfig.experimental?.cacheHandlers, cacheHandlers: nextConfig.experimental?.cacheHandlers,
useCacheEnabled: nextConfig.experimental?.useCache,
}) })
const programmaticOptions = { const programmaticOptions = {
......
...@@ -146,6 +146,7 @@ export function getDefineEnv({ ...@@ -146,6 +146,7 @@ export function getDefineEnv({
const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr) const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const isDynamicIOEnabled = !!config.experimental.dynamicIO const isDynamicIOEnabled = !!config.experimental.dynamicIO
const isUseCacheEnabled = !!config.experimental.useCache
const defineEnv: DefineEnv = { const defineEnv: DefineEnv = {
// internal field to identify the plugin config // internal field to identify the plugin config
...@@ -189,6 +190,7 @@ export function getDefineEnv({ ...@@ -189,6 +190,7 @@ export function getDefineEnv({
), ),
'process.env.__NEXT_PPR': isPPREnabled, 'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_DYNAMIC_IO': isDynamicIOEnabled, 'process.env.__NEXT_DYNAMIC_IO': isDynamicIOEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
'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 ?? '',
...(isTurbopack ...(isTurbopack
......
...@@ -9,7 +9,6 @@ import DefaultCacheHandler from '../../server/lib/cache-handlers/default' ...@@ -9,7 +9,6 @@ import DefaultCacheHandler from '../../server/lib/cache-handlers/default'
export async function createIncrementalCache({ export async function createIncrementalCache({
cacheHandler, cacheHandler,
dynamicIO,
cacheMaxMemorySize, cacheMaxMemorySize,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
distDir, distDir,
...@@ -18,7 +17,6 @@ export async function createIncrementalCache({ ...@@ -18,7 +17,6 @@ export async function createIncrementalCache({
cacheHandlers, cacheHandlers,
requestHeaders, requestHeaders,
}: { }: {
dynamicIO: boolean
cacheHandler?: string cacheHandler?: string
cacheMaxMemorySize?: number cacheMaxMemorySize?: number
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
...@@ -60,7 +58,6 @@ export async function createIncrementalCache({ ...@@ -60,7 +58,6 @@ export async function createIncrementalCache({
dev: false, dev: false,
requestHeaders: requestHeaders || {}, requestHeaders: requestHeaders || {},
flushToDisk, flushToDisk,
dynamicIO,
maxMemoryCacheSize: cacheMaxMemorySize, maxMemoryCacheSize: cacheMaxMemorySize,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
getPrerenderManifest: () => ({ getPrerenderManifest: () => ({
......
...@@ -373,7 +373,6 @@ export async function exportPages( ...@@ -373,7 +373,6 @@ export async function exportPages(
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
distDir, distDir,
dir, dir,
dynamicIO: Boolean(nextConfig.experimental.dynamicIO),
// 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,
......
...@@ -669,6 +669,9 @@ async function warmupDevRender( ...@@ -669,6 +669,9 @@ async function warmupDevRender(
const renderController = new AbortController() const renderController = new AbortController()
const prerenderController = new AbortController() const prerenderController = new AbortController()
const cacheSignal = new CacheSignal() const cacheSignal = new CacheSignal()
// TODO(useCache): Should this be a PrerenderStorePPR if dynamicIO is not
// enabled?
const prerenderStore: PrerenderStore = { const prerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
phase: 'render', phase: 'render',
......
...@@ -2654,10 +2654,10 @@ export default abstract class Server< ...@@ -2654,10 +2654,10 @@ export default abstract class Server<
} }
// TODO: adapt for putting the RDC inside the postponed data // TODO: adapt for putting the RDC inside the postponed data
// If we're in dev, and this isn't s prefetch or a server action, // If we're in dev, and this isn't a prefetch or a server action,
// we should seed the resume data cache. // we should seed the resume data cache.
if ( if (
this.nextConfig.experimental.dynamicIO && this.nextConfig.experimental.useCache &&
this.renderOpts.dev && this.renderOpts.dev &&
!isPrefetchRSCRequest && !isPrefetchRSCRequest &&
!isServerAction !isServerAction
......
...@@ -443,6 +443,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -443,6 +443,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
newDevOverlay: z.boolean().optional(), newDevOverlay: z.boolean().optional(),
streamingMetadata: z.boolean().optional(), streamingMetadata: z.boolean().optional(),
htmlLimitedBots: z.instanceof(RegExp).optional(), htmlLimitedBots: z.instanceof(RegExp).optional(),
useCache: z.boolean().optional(),
}) })
.optional(), .optional(),
exportPathMap: z exportPathMap: z
......
...@@ -607,6 +607,11 @@ export interface ExperimentalConfig { ...@@ -607,6 +607,11 @@ export interface ExperimentalConfig {
* Besides the default behavior, Next.js act differently on serving metadata to bots based on their capability. * Besides the default behavior, Next.js act differently on serving metadata to bots based on their capability.
*/ */
htmlLimitedBots?: RegExp htmlLimitedBots?: RegExp
/**
* Enables the use of the `"use cache"` directive.
*/
useCache?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
...@@ -1237,6 +1242,7 @@ export const defaultConfig: NextConfig = { ...@@ -1237,6 +1242,7 @@ export const defaultConfig: NextConfig = {
newDevOverlay: false, newDevOverlay: false,
streamingMetadata: false, streamingMetadata: false,
htmlLimitedBots: undefined, htmlLimitedBots: undefined,
useCache: undefined,
}, },
bundlePagesRouterDependencies: false, bundlePagesRouterDependencies: false,
} }
......
...@@ -1017,6 +1017,13 @@ function assignDefaults( ...@@ -1017,6 +1017,13 @@ function assignDefaults(
result.experimental.htmlLimitedBots = HTML_LIMITED_BOT_UA_RE_STRING result.experimental.htmlLimitedBots = HTML_LIMITED_BOT_UA_RE_STRING
} }
// "use cache" was originally implicitly enabled with the dynamicIO flag, so
// we transfer the value for dynamicIO to the explicit useCache flag to ensure
// backwards compatibility.
if (result.experimental.useCache === undefined) {
result.experimental.useCache = result.experimental.dynamicIO
}
return result return result
} }
......
...@@ -81,7 +81,6 @@ export async function loadStaticPaths({ ...@@ -81,7 +81,6 @@ export async function loadStaticPaths({
await createIncrementalCache({ await createIncrementalCache({
dir, dir,
distDir, distDir,
dynamicIO: false,
cacheHandler, cacheHandler,
cacheHandlers, cacheHandlers,
requestHeaders, requestHeaders,
......
...@@ -80,7 +80,6 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -80,7 +80,6 @@ export class IncrementalCache implements IncrementalCacheType {
readonly fetchCacheKeyPrefix?: string readonly fetchCacheKeyPrefix?: string
readonly revalidatedTags?: string[] readonly revalidatedTags?: string[]
readonly isOnDemandRevalidate?: boolean readonly isOnDemandRevalidate?: boolean
readonly hasDynamicIO?: boolean
private readonly locks = new Map<string, Promise<void>>() private readonly locks = new Map<string, Promise<void>>()
...@@ -93,7 +92,6 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -93,7 +92,6 @@ export class IncrementalCache implements IncrementalCacheType {
constructor({ constructor({
fs, fs,
dev, dev,
dynamicIO,
flushToDisk, flushToDisk,
minimalMode, minimalMode,
serverDistDir, serverDistDir,
...@@ -107,7 +105,6 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -107,7 +105,6 @@ export class IncrementalCache implements IncrementalCacheType {
}: { }: {
fs?: CacheFs fs?: CacheFs
dev: boolean dev: boolean
dynamicIO: boolean
minimalMode?: boolean minimalMode?: boolean
serverDistDir?: string serverDistDir?: string
flushToDisk?: boolean flushToDisk?: boolean
...@@ -152,7 +149,6 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -152,7 +149,6 @@ export class IncrementalCache implements IncrementalCacheType {
maxMemoryCacheSize = parseInt(process.env.__NEXT_TEST_MAX_ISR_CACHE, 10) maxMemoryCacheSize = parseInt(process.env.__NEXT_TEST_MAX_ISR_CACHE, 10)
} }
this.dev = dev this.dev = dev
this.hasDynamicIO = dynamicIO
this.disableForTestmode = process.env.NEXT_PRIVATE_TEST_PROXY === 'true' this.disableForTestmode = process.env.NEXT_PRIVATE_TEST_PROXY === 'true'
// this is a hack to avoid Webpack knowing this is equal to this.minimalMode // this is a hack to avoid Webpack knowing this is equal to this.minimalMode
// because we replace this.minimalMode to true in production bundles. // because we replace this.minimalMode to true in production bundles.
...@@ -404,9 +400,9 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -404,9 +400,9 @@ export class IncrementalCache implements IncrementalCacheType {
isFallback: boolean | undefined isFallback: boolean | undefined
} }
): Promise<IncrementalCacheEntry | null> { ): Promise<IncrementalCacheEntry | null> {
// unlike other caches if we have a cacheScope we use it even if // Unlike other caches if we have a resume data cache, we use it even if
// testmode would normally disable it or if requestHeaders say 'no-cache'. // testmode would normally disable it or if requestHeaders say 'no-cache'.
if (this.hasDynamicIO && ctx.kind === IncrementalCacheKind.FETCH) { if (ctx.kind === IncrementalCacheKind.FETCH) {
const workUnitStore = workUnitAsyncStorageInstance.getStore() const workUnitStore = workUnitAsyncStorageInstance.getStore()
const resumeDataCache = workUnitStore const resumeDataCache = workUnitStore
? getRenderResumeDataCache(workUnitStore) ? getRenderResumeDataCache(workUnitStore)
...@@ -547,11 +543,12 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -547,11 +543,12 @@ export class IncrementalCache implements IncrementalCacheType {
isFallback?: boolean isFallback?: boolean
} }
) { ) {
// Even if we otherwise disable caching for testMode or if no fetchCache is configured // Even if we otherwise disable caching for testMode or if no fetchCache is
// we still always stash results in the cacheScope if one exists. This is because this // configured we still always stash results in the resume data cache if one
// is a transient in memory cache that populates caches ahead of a dynamic render in dev mode // exists. This is because this is a transient in memory cache that
// to allow the RSC debug info to have the right environment associated to it. // populates caches ahead of a dynamic render in dev mode to allow the RSC
if (this.hasDynamicIO && data?.kind === CachedRouteKind.FETCH) { // debug info to have the right environment associated to it.
if (data?.kind === CachedRouteKind.FETCH) {
const workUnitStore = workUnitAsyncStorageInstance.getStore() const workUnitStore = workUnitAsyncStorageInstance.getStore()
const prerenderResumeDataCache = workUnitStore const prerenderResumeDataCache = workUnitStore
? getPrerenderResumeDataCache(workUnitStore) ? getPrerenderResumeDataCache(workUnitStore)
......
...@@ -430,7 +430,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -430,7 +430,6 @@ export default class NextNodeServer extends BaseServer<
dev, dev,
requestHeaders, requestHeaders,
requestProtocol, requestProtocol,
dynamicIO: Boolean(this.nextConfig.experimental.dynamicIO),
allowedRevalidateHeaderKeys: allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys, this.nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: this.minimalMode, minimalMode: this.minimalMode,
......
...@@ -85,9 +85,9 @@ function validateCacheLife(profile: CacheLife) { ...@@ -85,9 +85,9 @@ function validateCacheLife(profile: CacheLife) {
} }
export function cacheLife(profile: CacheLifeProfiles | CacheLife): void { export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
if (!process.env.__NEXT_DYNAMIC_IO) { if (!process.env.__NEXT_USE_CACHE) {
throw new Error( throw new Error(
'cacheLife() is only available with the experimental.dynamicIO config.' 'cacheLife() is only available with the experimental.useCache config.'
) )
} }
......
...@@ -2,9 +2,9 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte ...@@ -2,9 +2,9 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { validateTags } from '../lib/patch-fetch' import { validateTags } from '../lib/patch-fetch'
export function cacheTag(...tags: string[]): void { export function cacheTag(...tags: string[]): void {
if (!process.env.__NEXT_DYNAMIC_IO) { if (!process.env.__NEXT_USE_CACHE) {
throw new Error( throw new Error(
'cacheTag() is only available with the experimental.dynamicIO config.' 'cacheTag() is only available with the experimental.useCache config.'
) )
} }
......
...@@ -79,7 +79,6 @@ export default class NextWebServer extends BaseServer< ...@@ -79,7 +79,6 @@ export default class NextWebServer extends BaseServer<
return new IncrementalCache({ return new IncrementalCache({
dev, dev,
requestHeaders, requestHeaders,
dynamicIO: Boolean(this.nextConfig.experimental.dynamicIO),
requestProtocol: 'https', requestProtocol: 'https',
allowedRevalidateHeaderKeys: allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys, this.nextConfig.experimental.allowedRevalidateHeaderKeys,
......
...@@ -9,11 +9,11 @@ import { ...@@ -9,11 +9,11 @@ import {
} from 'next-test-utils' } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
const nextConfigWithDynamicIO: NextConfig = { const nextConfigWithUseCache: NextConfig = {
experimental: { dynamicIO: true }, experimental: { useCache: true },
} }
describe('use-cache-without-dynamic-io', () => { describe('use-cache-without-experimental-flag', () => {
const { next, isNextStart, isTurbopack, skipped } = nextTestSetup({ const { next, isNextStart, isTurbopack, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'dev', skipStart: process.env.NEXT_TEST_MODE !== 'dev',
...@@ -44,7 +44,7 @@ describe('use-cache-without-dynamic-io', () => { ...@@ -44,7 +44,7 @@ describe('use-cache-without-dynamic-io', () => {
3 | export default async function Page() { 3 | export default async function Page() {
4 | return <p>hello world</p> 4 | return <p>hello world</p>
To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config. To use "use cache", please enable the experimental feature flag "useCache" in your Next.js config.
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
...@@ -57,7 +57,7 @@ describe('use-cache-without-dynamic-io', () => { ...@@ -57,7 +57,7 @@ describe('use-cache-without-dynamic-io', () => {
expect(buildOutput).toMatchInlineSnapshot(` expect(buildOutput).toMatchInlineSnapshot(`
" "
./app/page.tsx ./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config. Error: x To use "use cache", please enable the experimental feature flag "useCache" in your Next.js config.
| |
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage | Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
| |
...@@ -102,7 +102,7 @@ describe('use-cache-without-dynamic-io', () => { ...@@ -102,7 +102,7 @@ describe('use-cache-without-dynamic-io', () => {
3 | export default async function Page() { 3 | export default async function Page() {
4 | return <p>hello world</p> 4 | return <p>hello world</p>
To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config. To use "use cache", please enable the experimental feature flag "useCache" in your Next.js config.
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage" Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage"
`) `)
...@@ -110,7 +110,7 @@ describe('use-cache-without-dynamic-io', () => { ...@@ -110,7 +110,7 @@ describe('use-cache-without-dynamic-io', () => {
expect(errorSource).toMatchInlineSnapshot(` expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx "./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config. Error: x To use "use cache", please enable the experimental feature flag "useCache" in your Next.js config.
| |
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage | Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
| |
...@@ -134,14 +134,14 @@ describe('use-cache-without-dynamic-io', () => { ...@@ -134,14 +134,14 @@ describe('use-cache-without-dynamic-io', () => {
3 | export default async function Page() { 3 | export default async function Page() {
4 | return <p>hello world</p> 4 | return <p>hello world</p>
To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config. To use "use cache", please enable the experimental feature flag "useCache" in your Next.js config.
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage" Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage"
`) `)
} else { } else {
expect(errorSource).toMatchInlineSnapshot(` expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx "./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config. Error: x To use "use cache", please enable the experimental feature flag "useCache" in your Next.js config.
| |
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage | Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
| |
...@@ -157,14 +157,14 @@ describe('use-cache-without-dynamic-io', () => { ...@@ -157,14 +157,14 @@ describe('use-cache-without-dynamic-io', () => {
} }
}) })
it('should recover from the build error if dynamicIO flag is set', async () => { it('should recover from the build error if useCache flag is set', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await assertHasRedbox(browser) await assertHasRedbox(browser)
await next.patchFile( await next.patchFile(
'next.config.js', 'next.config.js',
`module.exports = ${JSON.stringify(nextConfigWithDynamicIO)}`, `module.exports = ${JSON.stringify(nextConfigWithUseCache)}`,
() => () =>
retry(async () => { retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('hello world') expect(await browser.elementByCss('p').text()).toBe('hello world')
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
*/ */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
dynamicIO: true, useCache: true,
cacheLife: { cacheLife: {
frequent: { frequent: {
stale: 19, stale: 19,
......
...@@ -8228,10 +8228,10 @@ ...@@ -8228,10 +8228,10 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/e2e/app-dir/use-cache-without-dynamic-io/use-cache-without-dynamic-io.test.ts": { "test/e2e/app-dir/use-cache-without-experimental-flag/use-cache-without-experimental-flag.test.ts": {
"passed": [ "passed": [
"use-cache-without-dynamic-io should recover from the build error if dynamicIO flag is set", "use-cache-without-experimental-flag should recover from the build error if useCache flag is set",
"use-cache-without-dynamic-io should show a build error" "use-cache-without-experimental-flag should show a build error"
], ],
"failed": [], "failed": [],
"pending": [], "pending": [],
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