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(
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 mut is_app_dir = false;
......@@ -77,7 +77,7 @@ pub async fn get_next_client_transforms_rules(
ActionsTransform::Client,
encryption_key,
enable_mdx_rs,
dynamic_io_enabled,
use_cache_enabled,
cache_kinds,
));
}
......
......@@ -666,6 +666,7 @@ pub struct ExperimentalConfig {
react_compiler: Option<ReactCompilerOptionsOrBoolean>,
#[serde(rename = "dynamicIO")]
dynamic_io: Option<bool>,
use_cache: Option<bool>,
// ---
// UNSUPPORTED
// ---
......@@ -1408,6 +1409,18 @@ impl NextConfig {
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]
pub fn cache_kinds(&self) -> Vc<CacheKinds> {
Vc::cell(
......
......@@ -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 mut is_app_dir = false;
......@@ -115,7 +115,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Client,
encryption_key,
mdx_rs,
dynamic_io_enabled,
use_cache_enabled,
cache_kinds,
));
......@@ -128,7 +128,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server,
encryption_key,
mdx_rs,
dynamic_io_enabled,
use_cache_enabled,
cache_kinds,
));
......@@ -141,7 +141,7 @@ pub async fn get_next_server_transforms_rules(
ActionsTransform::Server,
encryption_key,
mdx_rs,
dynamic_io_enabled,
use_cache_enabled,
cache_kinds,
));
......
......@@ -21,14 +21,14 @@ pub fn get_server_actions_transform_rule(
transform: ActionsTransform,
encryption_key: ResolvedVc<RcStr>,
enable_mdx_rs: bool,
dynamic_io_enabled: bool,
use_cache_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>,
) -> ModuleRule {
let transformer =
EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextServerActions {
transform,
encryption_key,
dynamic_io_enabled,
use_cache_enabled,
cache_kinds,
}) as _));
ModuleRule::new(
......@@ -44,7 +44,7 @@ pub fn get_server_actions_transform_rule(
struct NextServerActions {
transform: ActionsTransform,
encryption_key: ResolvedVc<RcStr>,
dynamic_io_enabled: bool,
use_cache_enabled: bool,
cache_kinds: ResolvedVc<CacheKinds>,
}
......@@ -56,7 +56,7 @@ impl CustomTransformer for NextServerActions {
&FileName::Real(ctx.file_path_str.into()),
Config {
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(),
cache_kinds: self.cache_kinds.await?.clone_value(),
},
......
......@@ -31,7 +31,7 @@ use turbo_rcstr::RcStr;
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config {
pub is_react_server_layer: bool,
pub dynamic_io_enabled: bool,
pub use_cache_enabled: bool,
pub hash_salt: String,
pub cache_kinds: FxHashSet<RcStr>,
}
......@@ -104,7 +104,7 @@ enum ServerActionsErrorKind {
span: Span,
cache_kind: RcStr,
},
UseCacheWithoutDynamicIO {
UseCacheWithoutExperimentalFlag {
span: Span,
directive: String,
},
......@@ -2684,8 +2684,8 @@ impl DirectiveVisitor<'_> {
location: self.location.clone(),
});
} else if self.is_allowed_position {
if !self.config.dynamic_io_enabled {
emit_error(ServerActionsErrorKind::UseCacheWithoutDynamicIO {
if !self.config.use_cache_enabled {
emit_error(ServerActionsErrorKind::UseCacheWithoutExperimentalFlag {
span: *span,
directive: value.to_string(),
});
......@@ -3094,11 +3094,11 @@ fn emit_error(error_kind: ServerActionsErrorKind) {
"#
},
),
ServerActionsErrorKind::UseCacheWithoutDynamicIO { span, directive } => (
ServerActionsErrorKind::UseCacheWithoutExperimentalFlag { span, directive } => (
span,
formatdoc! {
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
"#
......
......@@ -186,7 +186,7 @@ fn react_server_actions_server_errors(input: PathBuf) {
&FileName::Real("/app/item.js".into()),
server_actions::Config {
is_react_server_layer: true,
dynamic_io_enabled: true,
use_cache_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
......@@ -227,7 +227,7 @@ fn react_server_actions_client_errors(input: PathBuf) {
&FileName::Real("/app/item.js".into()),
server_actions::Config {
is_react_server_layer: false,
dynamic_io_enabled: true,
use_cache_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
......@@ -286,7 +286,7 @@ fn use_cache_not_allowed(input: PathBuf) {
&FileName::Real("/app/item.js".into()),
server_actions::Config {
is_react_server_layer: true,
dynamic_io_enabled: false,
use_cache_enabled: false,
hash_salt: "".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
|
......
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
|
......
......@@ -567,7 +567,7 @@ fn server_actions_server_fixture(input: PathBuf) {
&FileName::Real("/app/item.js".into()),
server_actions::Config {
is_react_server_layer: true,
dynamic_io_enabled: true,
use_cache_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter(["x".into()]),
},
......@@ -601,7 +601,7 @@ fn next_font_with_directive_fixture(input: PathBuf) {
&FileName::Real("/app/test.tsx".into()),
server_actions::Config {
is_react_server_layer: true,
dynamic_io_enabled: true,
use_cache_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
......@@ -628,7 +628,7 @@ fn server_actions_client_fixture(input: PathBuf) {
&FileName::Real("/app/item.js".into()),
server_actions::Config {
is_react_server_layer: false,
dynamic_io_enabled: true,
use_cache_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
......@@ -931,7 +931,7 @@ fn test_source_maps(input: PathBuf) {
&FileName::Real("/app/item.js".into()),
server_actions::Config {
is_react_server_layer: true,
dynamic_io_enabled: true,
use_cache_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::from_iter([]),
},
......
......@@ -6,6 +6,7 @@ related:
title: Related
description: View related API references.
links:
- app/api-reference/config/next-config-js/useCache
- app/api-reference/config/next-config-js/dynamicIO
- app/api-reference/config/next-config-js/cacheLife
- app/api-reference/functions/cacheTag
......@@ -17,14 +18,14 @@ The `use cache` directive designates a component and/or a function to be cached.
## 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
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
useCache: true,
},
}
......@@ -35,13 +36,15 @@ export default nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
dynamicIO: true,
useCache: true,
},
}
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:
```tsx
......@@ -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.
- 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.
- 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.
## 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 @@
"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",
"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({
const incrementalCache = await createIncrementalCache({
dir,
distDir,
dynamicIO,
cacheHandler,
cacheHandlers,
requestHeaders,
......
......@@ -71,6 +71,7 @@ function getBaseSWCOptions({
bundleLayer,
isDynamicIo,
cacheHandlers,
useCacheEnabled,
}: {
filename: string
jest?: boolean
......@@ -89,6 +90,7 @@ function getBaseSWCOptions({
bundleLayer?: WebpackLayerName
isDynamicIo?: boolean
cacheHandlers?: ExperimentalConfig['cacheHandlers']
useCacheEnabled?: boolean
}) {
const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer)
const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer)
......@@ -216,7 +218,7 @@ function getBaseSWCOptions({
isAppRouterPagesLayer && !jest
? {
isReactServerLayer,
dynamicIoEnabled: isDynamicIo,
useCacheEnabled,
hashSalt: serverReferenceHashSalt,
cacheKinds: cacheHandlers ? Object.keys(cacheHandlers) : [],
}
......@@ -364,6 +366,7 @@ export function getLoaderSWCOptions({
bundleLayer,
esm,
cacheHandlers,
useCacheEnabled,
}: {
filename: string
development: boolean
......@@ -389,6 +392,7 @@ export function getLoaderSWCOptions({
serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName
cacheHandlers: ExperimentalConfig['cacheHandlers']
useCacheEnabled?: boolean
}) {
let baseOptions: any = getBaseSWCOptions({
filename,
......@@ -407,6 +411,7 @@ export function getLoaderSWCOptions({
esm: !!esm,
isDynamicIo,
cacheHandlers,
useCacheEnabled,
})
baseOptions.fontLoaders = {
fontLoaders: ['next/font/local', 'next/font/google'],
......
......@@ -1006,7 +1006,6 @@ export async function isPageStatic({
cacheHandlers,
distDir,
dir,
dynamicIO,
flushToDisk: isrFlushToDisk,
cacheMaxMemorySize: maxMemoryCacheSize,
})
......
......@@ -149,6 +149,7 @@ async function loaderTransform(
bundleLayer,
esm,
cacheHandlers: nextConfig.experimental?.cacheHandlers,
useCacheEnabled: nextConfig.experimental?.useCache,
})
const programmaticOptions = {
......
......@@ -146,6 +146,7 @@ export function getDefineEnv({
const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const isDynamicIOEnabled = !!config.experimental.dynamicIO
const isUseCacheEnabled = !!config.experimental.useCache
const defineEnv: DefineEnv = {
// internal field to identify the plugin config
......@@ -189,6 +190,7 @@ export function getDefineEnv({
),
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_DYNAMIC_IO': isDynamicIOEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',
...(isTurbopack
......
......@@ -9,7 +9,6 @@ import DefaultCacheHandler from '../../server/lib/cache-handlers/default'
export async function createIncrementalCache({
cacheHandler,
dynamicIO,
cacheMaxMemorySize,
fetchCacheKeyPrefix,
distDir,
......@@ -18,7 +17,6 @@ export async function createIncrementalCache({
cacheHandlers,
requestHeaders,
}: {
dynamicIO: boolean
cacheHandler?: string
cacheMaxMemorySize?: number
fetchCacheKeyPrefix?: string
......@@ -60,7 +58,6 @@ export async function createIncrementalCache({
dev: false,
requestHeaders: requestHeaders || {},
flushToDisk,
dynamicIO,
maxMemoryCacheSize: cacheMaxMemorySize,
fetchCacheKeyPrefix,
getPrerenderManifest: () => ({
......
......@@ -373,7 +373,6 @@ export async function exportPages(
fetchCacheKeyPrefix,
distDir,
dir,
dynamicIO: Boolean(nextConfig.experimental.dynamicIO),
// skip writing to disk in minimal mode for now, pending some
// changes to better support it
flushToDisk: !hasNextSupport,
......
......@@ -669,6 +669,9 @@ async function warmupDevRender(
const renderController = new AbortController()
const prerenderController = new AbortController()
const cacheSignal = new CacheSignal()
// TODO(useCache): Should this be a PrerenderStorePPR if dynamicIO is not
// enabled?
const prerenderStore: PrerenderStore = {
type: 'prerender',
phase: 'render',
......
......@@ -2654,10 +2654,10 @@ export default abstract class Server<
}
// 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.
if (
this.nextConfig.experimental.dynamicIO &&
this.nextConfig.experimental.useCache &&
this.renderOpts.dev &&
!isPrefetchRSCRequest &&
!isServerAction
......
......@@ -443,6 +443,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
newDevOverlay: z.boolean().optional(),
streamingMetadata: z.boolean().optional(),
htmlLimitedBots: z.instanceof(RegExp).optional(),
useCache: z.boolean().optional(),
})
.optional(),
exportPathMap: z
......
......@@ -607,6 +607,11 @@ export interface ExperimentalConfig {
* Besides the default behavior, Next.js act differently on serving metadata to bots based on their capability.
*/
htmlLimitedBots?: RegExp
/**
* Enables the use of the `"use cache"` directive.
*/
useCache?: boolean
}
export type ExportPathMap = {
......@@ -1237,6 +1242,7 @@ export const defaultConfig: NextConfig = {
newDevOverlay: false,
streamingMetadata: false,
htmlLimitedBots: undefined,
useCache: undefined,
},
bundlePagesRouterDependencies: false,
}
......
......@@ -1017,6 +1017,13 @@ function assignDefaults(
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
}
......
......@@ -81,7 +81,6 @@ export async function loadStaticPaths({
await createIncrementalCache({
dir,
distDir,
dynamicIO: false,
cacheHandler,
cacheHandlers,
requestHeaders,
......
......@@ -80,7 +80,6 @@ export class IncrementalCache implements IncrementalCacheType {
readonly fetchCacheKeyPrefix?: string
readonly revalidatedTags?: string[]
readonly isOnDemandRevalidate?: boolean
readonly hasDynamicIO?: boolean
private readonly locks = new Map<string, Promise<void>>()
......@@ -93,7 +92,6 @@ export class IncrementalCache implements IncrementalCacheType {
constructor({
fs,
dev,
dynamicIO,
flushToDisk,
minimalMode,
serverDistDir,
......@@ -107,7 +105,6 @@ export class IncrementalCache implements IncrementalCacheType {
}: {
fs?: CacheFs
dev: boolean
dynamicIO: boolean
minimalMode?: boolean
serverDistDir?: string
flushToDisk?: boolean
......@@ -152,7 +149,6 @@ export class IncrementalCache implements IncrementalCacheType {
maxMemoryCacheSize = parseInt(process.env.__NEXT_TEST_MAX_ISR_CACHE, 10)
}
this.dev = dev
this.hasDynamicIO = dynamicIO
this.disableForTestmode = process.env.NEXT_PRIVATE_TEST_PROXY === 'true'
// this is a hack to avoid Webpack knowing this is equal to this.minimalMode
// because we replace this.minimalMode to true in production bundles.
......@@ -404,9 +400,9 @@ export class IncrementalCache implements IncrementalCacheType {
isFallback: boolean | undefined
}
): 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'.
if (this.hasDynamicIO && ctx.kind === IncrementalCacheKind.FETCH) {
if (ctx.kind === IncrementalCacheKind.FETCH) {
const workUnitStore = workUnitAsyncStorageInstance.getStore()
const resumeDataCache = workUnitStore
? getRenderResumeDataCache(workUnitStore)
......@@ -547,11 +543,12 @@ export class IncrementalCache implements IncrementalCacheType {
isFallback?: boolean
}
) {
// Even if we otherwise disable caching for testMode or if no fetchCache is configured
// we still always stash results in the cacheScope if one exists. This is because this
// is a transient in memory cache that populates caches ahead of a dynamic render in dev mode
// to allow the RSC debug info to have the right environment associated to it.
if (this.hasDynamicIO && data?.kind === CachedRouteKind.FETCH) {
// Even if we otherwise disable caching for testMode or if no fetchCache is
// configured we still always stash results in the resume data cache if one
// exists. This is because this is a transient in memory cache that
// populates caches ahead of a dynamic render in dev mode to allow the RSC
// debug info to have the right environment associated to it.
if (data?.kind === CachedRouteKind.FETCH) {
const workUnitStore = workUnitAsyncStorageInstance.getStore()
const prerenderResumeDataCache = workUnitStore
? getPrerenderResumeDataCache(workUnitStore)
......
......@@ -430,7 +430,6 @@ export default class NextNodeServer extends BaseServer<
dev,
requestHeaders,
requestProtocol,
dynamicIO: Boolean(this.nextConfig.experimental.dynamicIO),
allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: this.minimalMode,
......
......@@ -85,9 +85,9 @@ function validateCacheLife(profile: CacheLife) {
}
export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
if (!process.env.__NEXT_DYNAMIC_IO) {
if (!process.env.__NEXT_USE_CACHE) {
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
import { validateTags } from '../lib/patch-fetch'
export function cacheTag(...tags: string[]): void {
if (!process.env.__NEXT_DYNAMIC_IO) {
if (!process.env.__NEXT_USE_CACHE) {
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<
return new IncrementalCache({
dev,
requestHeaders,
dynamicIO: Boolean(this.nextConfig.experimental.dynamicIO),
requestProtocol: 'https',
allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys,
......
......@@ -9,11 +9,11 @@ import {
} from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const nextConfigWithDynamicIO: NextConfig = {
experimental: { dynamicIO: true },
const nextConfigWithUseCache: NextConfig = {
experimental: { useCache: true },
}
describe('use-cache-without-dynamic-io', () => {
describe('use-cache-without-experimental-flag', () => {
const { next, isNextStart, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
......@@ -34,47 +34,47 @@ describe('use-cache-without-dynamic-io', () => {
if (isTurbopack) {
expect(buildOutput).toMatchInlineSnapshot(`
"Error: Turbopack build failed with 1 errors:
Page: {"type":"app","side":"server","page":"/page"}
./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache'
| ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
"Error: Turbopack build failed with 1 errors:
Page: {"type":"app","side":"server","page":"/page"}
./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache'
| ^^^^^^^^^^^
2 |
3 | export default async function Page() {
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
at <unknown> (./app/page.tsx:1:1)
"
at <unknown> (./app/page.tsx:1:1)
"
`)
} else {
expect(buildOutput).toMatchInlineSnapshot(`
"
./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
|
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----
Import trace for requested module:
./app/page.tsx
> Build failed because of webpack errors
"
"
./app/page.tsx
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
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----
Import trace for requested module:
./app/page.tsx
> Build failed because of webpack errors
"
`)
}
})
......@@ -102,69 +102,69 @@ describe('use-cache-without-dynamic-io', () => {
3 | export default async function Page() {
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"
`)
} else {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
|
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----"
`)
"./app/page.tsx
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
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----"
`)
}
} else {
if (isTurbopack) {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache'
| ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage"
`)
"./app/page.tsx:1:1
Ecmascript file had an error
> 1 | 'use cache'
| ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
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"
`)
} else {
expect(errorSource).toMatchInlineSnapshot(`
"./app/page.tsx
Error: x To use "use cache", please enable the experimental feature flag "dynamicIO" in your Next.js config.
|
| Read more: https://nextjs.org/docs/canary/app/api-reference/directives/use-cache#usage
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----"
`)
"./app/page.tsx
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
|
,-[1:1]
1 | 'use cache'
: ^^^^^^^^^^^
2 |
3 | export default async function Page() {
4 | return <p>hello world</p>
\`----"
`)
}
}
})
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('/')
await assertHasRedbox(browser)
await next.patchFile(
'next.config.js',
`module.exports = ${JSON.stringify(nextConfigWithDynamicIO)}`,
`module.exports = ${JSON.stringify(nextConfigWithUseCache)}`,
() =>
retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('hello world')
......
......@@ -3,7 +3,7 @@
*/
const nextConfig = {
experimental: {
dynamicIO: true,
useCache: true,
cacheLife: {
frequent: {
stale: 19,
......
......@@ -8228,10 +8228,10 @@
"flakey": [],
"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": [
"use-cache-without-dynamic-io should recover from the build error if dynamicIO flag is set",
"use-cache-without-dynamic-io should show a build error"
"use-cache-without-experimental-flag should recover from the build error if useCache flag is set",
"use-cache-without-experimental-flag should show a build error"
],
"failed": [],
"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