Unverified Commit 9dc2d469 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Introduce `'use cache: private'` (#81816)

parent f0bf674e
...@@ -56,7 +56,12 @@ impl CacheKinds { ...@@ -56,7 +56,12 @@ impl CacheKinds {
impl Default for CacheKinds { impl Default for CacheKinds {
fn default() -> Self { fn default() -> Self {
CacheKinds(["default", "remote"].iter().map(|&s| s.into()).collect()) CacheKinds(
["default", "remote", "private"]
.iter()
.map(|&s| s.into())
.collect(),
)
} }
} }
......
...@@ -731,5 +731,26 @@ ...@@ -731,5 +731,26 @@
"730": "Dynamic imports should not be instrumented in the edge runtime, because `cacheComponents` doesn't support it", "730": "Dynamic imports should not be instrumented in the edge runtime, because `cacheComponents` doesn't support it",
"731": "chainStreams requires at least one stream", "731": "chainStreams requires at least one stream",
"732": "dynamic responses cannot be unchunked. This is a bug in Next.js", "732": "dynamic responses cannot be unchunked. This is a bug in Next.js",
"733": "null responses cannot be unchunked" "733": "null responses cannot be unchunked",
"734": "createPrerenderParamsForClientSegment should not be called in cache contexts.",
"735": "%s must not be used within \"use cache\". It can only be nested inside of another %s.",
"736": "createParamsFromClient should not be called in cache contexts.",
"737": "Unexpected work unit store.",
"738": "createServerParamsForRoute should not be called in cache contexts.",
"739": "createSearchParamsFromClient should not be called in cache contexts.",
"740": "createServerPathnameForMetadata should not be called in cache contexts.",
"741": "%s must not be used within a client component. Next.js should be preventing %s from being allowed in client components statically, but did not in this case.",
"742": "Route %s used \"headers\" inside \"use cache: private\". Accessing \"headers\" inside a private cache scope is not supported. If you need this data inside a cached function use \"headers\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"743": "createServerParamsForServerSegment should not be called in cache contexts.",
"744": "%s must not be used within \\`unstable_cache()\\`.",
"745": "\\`%s\\` was called inside a cache scope. Next.js should be preventing %s from being included in server components statically, but did not in this case.",
"746": "createPrerenderSearchParamsForClientPage should not be called in cache contexts.",
"747": "createServerSearchParamsForServerPage should not be called in cache contexts.",
"748": "cacheLifeProfiles should always be provided.",
"749": "A private cache entry must not be retrieved from the cache handler.",
"750": "A default cacheLife profile must always be provided.",
"751": "%s cannot not be used outside of a request context.",
"752": "Route %s used \"connection\" inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"753": "Route %s used \"connection\" inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"754": "%s cannot be used outside of a request context."
} }
...@@ -228,7 +228,7 @@ function getBaseSWCOptions({ ...@@ -228,7 +228,7 @@ function getBaseSWCOptions({
isDevelopment: development, isDevelopment: development,
useCacheEnabled, useCacheEnabled,
hashSalt: serverReferenceHashSalt, hashSalt: serverReferenceHashSalt,
cacheKinds: ['default', 'remote'].concat( cacheKinds: ['default', 'remote', 'private'].concat(
cacheHandlers ? Object.keys(cacheHandlers) : [] cacheHandlers ? Object.keys(cacheHandlers) : []
), ),
} }
......
...@@ -18,6 +18,7 @@ export function bailoutToClientRendering(reason: string): void | never { ...@@ -18,6 +18,7 @@ export function bailoutToClientRendering(reason: string): void | never {
throw new BailoutToCSRError(reason) throw new BailoutToCSRError(reason)
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -1242,6 +1242,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1242,6 +1242,7 @@ async function renderToHTMLOrFlightImpl(
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'cache': case 'cache':
case 'private-cache':
return true return true
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
...@@ -1656,7 +1657,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -1656,7 +1657,10 @@ async function renderToHTMLOrFlightImpl(
metadata metadata
) )
if (workStore.invalidDynamicUsageError) { // Invalid dynamic usages should only error the request in development.
// In production, it's better to produce a result.
// (the dynamic error will still be thrown inside the component tree, but it's catchable by error boundaries)
if (workStore.invalidDynamicUsageError && workStore.dev) {
throw workStore.invalidDynamicUsageError throw workStore.invalidDynamicUsageError
} }
...@@ -2448,11 +2452,12 @@ async function spawnDynamicValidationInDev( ...@@ -2448,11 +2452,12 @@ async function spawnDynamicValidationInDev(
// We don't need to continue the prerender process if we already // We don't need to continue the prerender process if we already
// detected invalid dynamic usage in the initial prerender phase. // detected invalid dynamic usage in the initial prerender phase.
if (workStore.invalidDynamicUsageError) { const { invalidDynamicUsageError } = workStore
if (invalidDynamicUsageError) {
resolveValidation( resolveValidation(
<LogSafely <LogSafely
fn={() => { fn={() => {
console.error(workStore.invalidDynamicUsageError) console.error(invalidDynamicUsageError)
}} }}
/> />
) )
......
...@@ -297,13 +297,17 @@ async function createComponentTreeInternal({ ...@@ -297,13 +297,17 @@ async function createComponentTreeInternal({
case 'prerender': case 'prerender':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr': case 'prerender-ppr':
case 'cache':
if (workUnitStore.revalidate > defaultRevalidate) { if (workUnitStore.revalidate > defaultRevalidate) {
workUnitStore.revalidate = defaultRevalidate workUnitStore.revalidate = defaultRevalidate
} }
break break
case 'prerender-client':
case 'request': case 'request':
// A request store doesn't have a revalidate property.
break
// createComponentTree is not called for these stores:
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
...@@ -766,13 +770,6 @@ async function createComponentTreeInternal({ ...@@ -766,13 +770,6 @@ async function createComponentTreeInternal({
const UseCachePageComponent: React.ComponentType<UseCachePageComponentProps> = const UseCachePageComponent: React.ComponentType<UseCachePageComponentProps> =
PageComponent PageComponent
if (!experimental.cacheComponents) {
// The "use cache" wrapper takes care of converting this into an
// erroring search params promise when passing it to the original
// function.
searchParams = Promise.resolve({})
}
pageElement = ( pageElement = (
<UseCachePageComponent <UseCachePageComponent
params={params} params={params}
......
...@@ -43,6 +43,7 @@ import { ...@@ -43,6 +43,7 @@ import {
} from '../../lib/metadata/metadata-constants' } from '../../lib/metadata/metadata-constants'
import { scheduleOnNextTick } from '../../lib/scheduler' import { scheduleOnNextTick } from '../../lib/scheduler'
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error'
const hasPostpone = typeof React.unstable_postpone === 'function' const hasPostpone = typeof React.unstable_postpone === 'function'
...@@ -131,6 +132,9 @@ export function markCurrentScopeAsDynamic( ...@@ -131,6 +132,9 @@ export function markCurrentScopeAsDynamic(
// subtly different from reading a dynamic data source, which is // subtly different from reading a dynamic data source, which is
// forbidden inside a cache scope. // forbidden inside a cache scope.
return return
case 'private-cache':
// A private cache scope is already dynamic by definition.
return
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr': case 'prerender-ppr':
case 'request': case 'request':
...@@ -222,6 +226,9 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) { ...@@ -222,6 +226,9 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
// subtly different from reading a dynamic data source, which is // subtly different from reading a dynamic data source, which is
// forbidden inside a cache scope. // forbidden inside a cache scope.
return return
case 'private-cache':
// A private cache scope is already dynamic by definition.
return
case 'prerender': case 'prerender':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr': case 'prerender-ppr':
...@@ -537,6 +544,7 @@ export function createHangingInputAbortSignal( ...@@ -537,6 +544,7 @@ export function createHangingInputAbortSignal(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
return undefined return undefined
default: default:
...@@ -573,13 +581,13 @@ export function useDynamicRouteParams(expression: string) { ...@@ -573,13 +581,13 @@ export function useDynamicRouteParams(expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client': case 'prerender-client':
// We are in a prerender with cacheComponents semantics. We are going to // We are in a prerender with cacheComponents semantics. We are going to
// hang here and never resolve. This will cause the currently // hang here and never resolve. This will cause the currently
// rendering component to effectively be a dynamic hole. // rendering component to effectively be a dynamic hole.
React.use(makeHangingPromise(workUnitStore.renderSignal, expression)) React.use(makeHangingPromise(workUnitStore.renderSignal, expression))
break break
case 'prerender':
case 'prerender-ppr': case 'prerender-ppr':
return postponeWithTracking( return postponeWithTracking(
workStore.route, workStore.route,
...@@ -592,8 +600,12 @@ export function useDynamicRouteParams(expression: string) { ...@@ -592,8 +600,12 @@ export function useDynamicRouteParams(expression: string) {
workStore, workStore,
workUnitStore workUnitStore
) )
case 'request':
case 'cache': case 'cache':
case 'private-cache':
throw new InvariantError(
`\`${expression}\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
)
case 'request':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -272,6 +272,7 @@ export async function decryptActionBoundArgs( ...@@ -272,6 +272,7 @@ export async function decryptActionBoundArgs(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case undefined: case undefined:
return controller.close() return controller.close()
......
...@@ -68,6 +68,7 @@ export function useFlightStream<T>( ...@@ -68,6 +68,7 @@ export function useFlightStream<T>(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -27,7 +27,7 @@ export interface CommonWorkUnitStore { ...@@ -27,7 +27,7 @@ export interface CommonWorkUnitStore {
} }
export interface RequestStore extends CommonWorkUnitStore { export interface RequestStore extends CommonWorkUnitStore {
type: 'request' readonly type: 'request'
/** /**
* The URL of the request. This only specifies the pathname and the search * The URL of the request. This only specifies the pathname and the search
...@@ -82,15 +82,25 @@ export type PrerenderStoreModern = ...@@ -82,15 +82,25 @@ export type PrerenderStoreModern =
| PrerenderStoreModernClient | PrerenderStoreModernClient
| PrerenderStoreModernServer | PrerenderStoreModernServer
interface PrerenderStoreModernClient extends PrerenderStoreModernCommon { export interface PrerenderStoreModernClient extends PrerenderStoreModernCommon {
type: 'prerender-client' readonly type: 'prerender-client'
} }
interface PrerenderStoreModernServer extends PrerenderStoreModernCommon { export interface PrerenderStoreModernServer extends PrerenderStoreModernCommon {
type: 'prerender' readonly type: 'prerender'
} }
interface PrerenderStoreModernCommon extends CommonWorkUnitStore { export interface RevalidateStore {
// Collected revalidate times and tags for this document during the prerender.
revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.
expire: number // server expiration time
stale: number // client expiration time
tags: null | string[]
}
interface PrerenderStoreModernCommon
extends CommonWorkUnitStore,
RevalidateStore {
/** /**
* The render signal is aborted after React's `prerender` function is aborted * The render signal is aborted after React's `prerender` function is aborted
* (using a separate signal), which happens in two cases: * (using a separate signal), which happens in two cases:
...@@ -136,12 +146,6 @@ interface PrerenderStoreModernCommon extends CommonWorkUnitStore { ...@@ -136,12 +146,6 @@ interface PrerenderStoreModernCommon extends CommonWorkUnitStore {
*/ */
readonly allowEmptyStaticShell: boolean readonly allowEmptyStaticShell: boolean
// Collected revalidate times and tags for this document during the prerender.
revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.
expire: number // server expiration time
stale: number // client expiration time
tags: null | string[]
/** /**
* A mutable resume data cache for this prerender. * A mutable resume data cache for this prerender.
*/ */
...@@ -168,15 +172,12 @@ interface PrerenderStoreModernCommon extends CommonWorkUnitStore { ...@@ -168,15 +172,12 @@ interface PrerenderStoreModernCommon extends CommonWorkUnitStore {
readonly captureOwnerStack: undefined | (() => string | null) readonly captureOwnerStack: undefined | (() => string | null)
} }
export interface PrerenderStorePPR extends CommonWorkUnitStore { export interface PrerenderStorePPR
type: 'prerender-ppr' extends CommonWorkUnitStore,
RevalidateStore {
readonly type: 'prerender-ppr'
readonly rootParams: Params readonly rootParams: Params
readonly dynamicTracking: null | DynamicTrackingState readonly dynamicTracking: null | DynamicTrackingState
// Collected revalidate times and tags for this document during the prerender.
revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.
expire: number // server expiration time
stale: number // client expiration time
tags: null | string[]
/** /**
* The resume data cache for this prerender. * The resume data cache for this prerender.
...@@ -184,14 +185,11 @@ export interface PrerenderStorePPR extends CommonWorkUnitStore { ...@@ -184,14 +185,11 @@ export interface PrerenderStorePPR extends CommonWorkUnitStore {
prerenderResumeDataCache: PrerenderResumeDataCache prerenderResumeDataCache: PrerenderResumeDataCache
} }
export interface PrerenderStoreLegacy extends CommonWorkUnitStore { export interface PrerenderStoreLegacy
type: 'prerender-legacy' extends CommonWorkUnitStore,
RevalidateStore {
readonly type: 'prerender-legacy'
readonly rootParams: Params readonly rootParams: Params
// Collected revalidate times and tags for this document during the prerender.
revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.
expire: number // server expiration time
stale: number // client expiration time
tags: null | string[]
} }
export type PrerenderStore = export type PrerenderStore =
...@@ -213,24 +211,34 @@ export interface CommonCacheStore ...@@ -213,24 +211,34 @@ export interface CommonCacheStore
readonly draftMode: DraftModeProvider | undefined readonly draftMode: DraftModeProvider | undefined
} }
export interface UseCacheStore extends CommonCacheStore { export interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {
type: 'cache'
// Collected revalidate times and tags for this cache entry during the cache render.
revalidate: number // implicit revalidate time from inner caches / fetches
expire: number // server expiration time
stale: number // client expiration time
explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls
explicitExpire: undefined | number // server expiration time explicitExpire: undefined | number // server expiration time
explicitStale: undefined | number // client expiration time explicitStale: undefined | number // client expiration time
tags: null | string[]
readonly hmrRefreshHash: string | undefined readonly hmrRefreshHash: string | undefined
readonly isHmrRefresh: boolean readonly isHmrRefresh: boolean
readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined
readonly forceRevalidate: boolean readonly forceRevalidate: boolean
} }
export interface PublicUseCacheStore extends CommonUseCacheStore {
readonly type: 'cache'
}
export interface PrivateUseCacheStore extends CommonUseCacheStore {
readonly type: 'private-cache'
/**
* As opposed to the public cache store, the private cache store is allowed to
* access the request cookies.
*/
readonly cookies: ReadonlyRequestCookies
}
export type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore
export interface UnstableCacheStore extends CommonCacheStore { export interface UnstableCacheStore extends CommonCacheStore {
type: 'unstable-cache' readonly type: 'unstable-cache'
} }
/** /**
...@@ -270,6 +278,7 @@ export function getPrerenderResumeDataCache( ...@@ -270,6 +278,7 @@ export function getPrerenderResumeDataCache(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
return null return null
default: default:
...@@ -296,6 +305,7 @@ export function getRenderResumeDataCache( ...@@ -296,6 +305,7 @@ export function getRenderResumeDataCache(
// version of the cache as it can also be used for reading. // version of the cache as it can also be used for reading.
return workUnitStore.prerenderResumeDataCache return workUnitStore.prerenderResumeDataCache
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case 'prerender-legacy': case 'prerender-legacy':
return null return null
...@@ -311,6 +321,7 @@ export function getHmrRefreshHash( ...@@ -311,6 +321,7 @@ export function getHmrRefreshHash(
if (workStore.dev) { if (workStore.dev) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache':
case 'prerender': case 'prerender':
return workUnitStore.hmrRefreshHash return workUnitStore.hmrRefreshHash
case 'request': case 'request':
...@@ -338,6 +349,7 @@ export function getDraftModeProviderForCacheScope( ...@@ -338,6 +349,7 @@ export function getDraftModeProviderForCacheScope(
if (workStore.isDraftMode) { if (workStore.isDraftMode) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case 'request': case 'request':
return workUnitStore.draftMode return workUnitStore.draftMode
...@@ -365,6 +377,7 @@ export function getCacheSignal( ...@@ -365,6 +377,7 @@ export function getCacheSignal(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
return null return null
default: default:
......
...@@ -975,7 +975,13 @@ function assignDefaults( ...@@ -975,7 +975,13 @@ function assignDefaults(
const invalidHandlerItems: Array<{ key: string; reason: string }> = [] const invalidHandlerItems: Array<{ key: string; reason: string }> = []
for (const key of handlerKeys) { for (const key of handlerKeys) {
if (!allowedHandlerNameRegex.test(key)) { if (key === 'private') {
invalidHandlerItems.push({
key,
reason:
'The cache handler for "use cache: private" cannot be customized.',
})
} else if (!allowedHandlerNameRegex.test(key)) {
invalidHandlerItems.push({ invalidHandlerItems.push({
key, key,
reason: 'key must only use characters a-z and -', reason: 'key must only use characters a-z and -',
......
...@@ -17,8 +17,8 @@ import type { FetchMetric } from '../base-http' ...@@ -17,8 +17,8 @@ import type { FetchMetric } from '../base-http'
import { createDedupeFetch } from './dedupe-fetch' import { createDedupeFetch } from './dedupe-fetch'
import { import {
getCacheSignal, getCacheSignal,
type RevalidateStore,
type WorkUnitAsyncStorage, type WorkUnitAsyncStorage,
type WorkUnitStore,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
CachedRouteKind, CachedRouteKind,
...@@ -365,7 +365,7 @@ export function createPatchedFetcher( ...@@ -365,7 +365,7 @@ export function createPatchedFetcher(
`fetch ${input.toString()}` `fetch ${input.toString()}`
) )
let revalidateStore: Extract<WorkUnitStore, { tags: any }> | undefined let revalidateStore: RevalidateStore | undefined
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
...@@ -375,6 +375,7 @@ export function createPatchedFetcher( ...@@ -375,6 +375,7 @@ export function createPatchedFetcher(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
revalidateStore = workUnitStore revalidateStore = workUnitStore
break break
case 'request': case 'request':
...@@ -415,6 +416,7 @@ export function createPatchedFetcher( ...@@ -415,6 +416,7 @@ export function createPatchedFetcher(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -567,6 +569,7 @@ export function createPatchedFetcher( ...@@ -567,6 +569,7 @@ export function createPatchedFetcher(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
...@@ -677,6 +680,7 @@ export function createPatchedFetcher( ...@@ -677,6 +680,7 @@ export function createPatchedFetcher(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
...@@ -711,6 +715,7 @@ export function createPatchedFetcher( ...@@ -711,6 +715,7 @@ export function createPatchedFetcher(
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
isHmrRefresh = workUnitStore.isHmrRefresh ?? false isHmrRefresh = workUnitStore.isHmrRefresh ?? false
serverComponentsHmrCache = workUnitStore.serverComponentsHmrCache serverComponentsHmrCache = workUnitStore.serverComponentsHmrCache
break break
...@@ -847,6 +852,7 @@ export function createPatchedFetcher( ...@@ -847,6 +852,7 @@ export function createPatchedFetcher(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case undefined: case undefined:
return createCachedDynamicResponse( return createCachedDynamicResponse(
...@@ -917,6 +923,7 @@ export function createPatchedFetcher( ...@@ -917,6 +923,7 @@ export function createPatchedFetcher(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
...@@ -1018,6 +1025,7 @@ export function createPatchedFetcher( ...@@ -1018,6 +1025,7 @@ export function createPatchedFetcher(
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
...@@ -1050,6 +1058,7 @@ export function createPatchedFetcher( ...@@ -1050,6 +1058,7 @@ export function createPatchedFetcher(
) )
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case 'prerender-legacy': case 'prerender-legacy':
case 'prerender-ppr': case 'prerender-ppr':
......
...@@ -147,6 +147,7 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void { ...@@ -147,6 +147,7 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
case undefined: case undefined:
originalMethod.apply(this, args) originalMethod.apply(this, args)
......
...@@ -92,6 +92,7 @@ export function io(expression: string, type: ApiType) { ...@@ -92,6 +92,7 @@ export function io(expression: string, type: ApiType) {
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -43,10 +43,25 @@ export function connection(): Promise<void> { ...@@ -43,10 +43,25 @@ export function connection(): Promise<void> {
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache': {
throw new Error( const error = new Error(
`Route ${workStore.route} used "connection" inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used "connection" inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, connection)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'private-cache': {
// It might not be intuitive to throw for private caches as well, but
// we don't consider dynamic prefetches as "actual requests" (in the
// navigation sense), despite allowing them to read cookies.
const error = new Error(
`Route ${workStore.route} used "connection" inside "use cache: private". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
Error.captureStackTrace(error, connection)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache': case 'unstable-cache':
throw new Error( throw new Error(
`Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
......
...@@ -114,6 +114,8 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -114,6 +114,8 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
workStore, workStore,
workUnitStore workUnitStore
) )
case 'private-cache':
return makeUntrackedExoticCookies(workUnitStore.cookies)
case 'request': case 'request':
trackDynamicDataInDynamicRender(workUnitStore) trackDynamicDataInDynamicRender(workUnitStore)
...@@ -146,7 +148,6 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -146,7 +148,6 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
} else { } else {
return makeUntrackedExoticCookies(underlyingCookies) return makeUntrackedExoticCookies(underlyingCookies)
} }
break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
} }
...@@ -472,6 +473,7 @@ function syncIODev(route: string | undefined, expression: string) { ...@@ -472,6 +473,7 @@ function syncIODev(route: string | undefined, expression: string) {
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -59,6 +59,7 @@ export function draftMode(): Promise<DraftMode> { ...@@ -59,6 +59,7 @@ export function draftMode(): Promise<DraftMode> {
return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore) return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
// Inside of `"use cache"` or `unstable_cache`, draft mode is available if // Inside of `"use cache"` or `unstable_cache`, draft mode is available if
// the outmost work unit store is a request store, and if draft mode is // the outmost work unit store is a request store, and if draft mode is
...@@ -259,6 +260,7 @@ function syncIODev(route: string | undefined, expression: string) { ...@@ -259,6 +260,7 @@ function syncIODev(route: string | undefined, expression: string) {
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
...@@ -307,7 +309,8 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) { ...@@ -307,7 +309,8 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': { case 'cache':
case 'private-cache': {
const error = new Error( const error = new Error(
`Route ${workStore.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
......
...@@ -79,13 +79,22 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -79,13 +79,22 @@ export function headers(): Promise<ReadonlyHeaders> {
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache': {
const error = new Error( const error = new Error(
`Route ${workStore.route} used "headers" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used "headers" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
Error.captureStackTrace(error, headers) Error.captureStackTrace(error, headers)
workStore.invalidDynamicUsageError ??= error workStore.invalidDynamicUsageError ??= error
throw error throw error
}
case 'private-cache': {
const error = new Error(
`Route ${workStore.route} used "headers" inside "use cache: private". Accessing "headers" inside a private cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, headers)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache': case 'unstable-cache':
throw new Error( throw new Error(
`Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
...@@ -427,6 +436,7 @@ function syncIODev(route: string | undefined, expression: string) { ...@@ -427,6 +436,7 @@ function syncIODev(route: string | undefined, expression: string) {
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -68,9 +68,13 @@ export function createParamsFromClient( ...@@ -68,9 +68,13 @@ export function createParamsFromClient(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore) return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
throw new InvariantError(
'createParamsFromClient should not be called in cache contexts.'
)
case 'request':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -96,9 +100,13 @@ export function createServerParamsForRoute( ...@@ -96,9 +100,13 @@ export function createServerParamsForRoute(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore) return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
throw new InvariantError(
'createServerParamsForRoute should not be called in cache contexts.'
)
case 'request':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -119,9 +127,13 @@ export function createServerParamsForServerSegment( ...@@ -119,9 +127,13 @@ export function createServerParamsForServerSegment(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore) return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
throw new InvariantError(
'createServerParamsForServerSegment should not be called in cache contexts.'
)
case 'request':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -152,11 +164,15 @@ export function createPrerenderParamsForClientSegment( ...@@ -152,11 +164,15 @@ export function createPrerenderParamsForClientSegment(
} }
} }
break break
case 'cache':
case 'private-cache':
case 'unstable-cache':
throw new InvariantError(
'createPrerenderParamsForClientSegment should not be called in cache contexts.'
)
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache':
case 'unstable-cache':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -555,6 +571,7 @@ function syncIODev( ...@@ -555,6 +571,7 @@ function syncIODev(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -29,9 +29,13 @@ export function createServerPathnameForMetadata( ...@@ -29,9 +29,13 @@ export function createServerPathnameForMetadata(
workUnitStore workUnitStore
) )
} }
case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
throw new InvariantError(
'createServerPathnameForMetadata should not be called in cache contexts.'
)
case 'request':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
......
...@@ -39,8 +39,9 @@ export async function unstable_rootParams(): Promise<Params> { ...@@ -39,8 +39,9 @@ export async function unstable_rootParams(): Promise<Params> {
} }
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'unstable-cache': case 'cache':
case 'cache': { case 'private-cache':
case 'unstable-cache': {
throw new Error( throw new Error(
`Route ${workStore.route} used \`unstable_rootParams()\` inside \`"use cache"\` or \`unstable_cache\`. Support for this API inside cache scopes is planned for a future version of Next.js.` `Route ${workStore.route} used \`unstable_rootParams()\` inside \`"use cache"\` or \`unstable_cache\`. Support for this API inside cache scopes is planned for a future version of Next.js.`
) )
......
...@@ -72,9 +72,13 @@ export function createSearchParamsFromClient( ...@@ -72,9 +72,13 @@ export function createSearchParamsFromClient(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderSearchParams(workStore, workUnitStore) return createPrerenderSearchParams(workStore, workUnitStore)
case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
throw new InvariantError(
'createSearchParamsFromClient should not be called in cache contexts.'
)
case 'request':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -99,9 +103,13 @@ export function createServerSearchParamsForServerPage( ...@@ -99,9 +103,13 @@ export function createServerSearchParamsForServerPage(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createPrerenderSearchParams(workStore, workUnitStore) return createPrerenderSearchParams(workStore, workUnitStore)
case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
throw new InvariantError(
'createServerSearchParamsForServerPage should not be called in cache contexts.'
)
case 'request':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -127,11 +135,15 @@ export function createPrerenderSearchParamsForClientPage( ...@@ -127,11 +135,15 @@ export function createPrerenderSearchParamsForClientPage(
// We're prerendering in a mode that aborts (cacheComponents) and should stall // We're prerendering in a mode that aborts (cacheComponents) and should stall
// the promise to ensure the RSC side is considered dynamic // the promise to ensure the RSC side is considered dynamic
return makeHangingPromise(workUnitStore.renderSignal, '`searchParams`') return makeHangingPromise(workUnitStore.renderSignal, '`searchParams`')
case 'cache':
case 'private-cache':
case 'unstable-cache':
throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'
)
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache':
case 'unstable-cache':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -794,6 +806,7 @@ function syncIODev( ...@@ -794,6 +806,7 @@ function syncIODev(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
...@@ -1165,6 +1165,9 @@ function trackDynamic( ...@@ -1165,6 +1165,9 @@ function trackDynamic(
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache':
// TODO: Should we allow reading cookies and search params from the
// request for private caches in route handlers?
throw new Error( throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
......
...@@ -105,6 +105,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void { ...@@ -105,6 +105,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
'cacheLife() can only be called inside a "use cache" function.' 'cacheLife() can only be called inside a "use cache" function.'
) )
case 'cache': case 'cache':
case 'private-cache':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
......
...@@ -22,6 +22,7 @@ export function cacheTag(...tags: string[]): void { ...@@ -22,6 +22,7 @@ export function cacheTag(...tags: string[]): void {
'cacheTag() can only be called inside a "use cache" function.' 'cacheTag() can only be called inside a "use cache" function.'
) )
case 'cache': case 'cache':
case 'private-cache':
break break
default: default:
workUnitStore satisfies never workUnitStore satisfies never
......
// If the expire time is less than . export const DYNAMIC_EXPIRE = 300 // 5 minutes
export const DYNAMIC_EXPIRE = 300 export const DYNAMIC_PREFETCH_DYNAMIC_STALE = 30 // 30 seconds
...@@ -101,6 +101,7 @@ function revalidate(tags: string[], expression: string) { ...@@ -101,6 +101,7 @@ function revalidate(tags: string[], expression: string) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache':
throw new Error( throw new Error(
`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
) )
......
...@@ -161,6 +161,7 @@ export function unstable_cache<T extends Callback>( ...@@ -161,6 +161,7 @@ export function unstable_cache<T extends Callback>(
if (workUnitStore) { if (workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache':
case 'prerender': case 'prerender':
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
...@@ -386,6 +387,7 @@ function getFetchUrlPrefix( ...@@ -386,6 +387,7 @@ function getFetchUrlPrefix(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
return workStore.route return workStore.route
default: default:
......
...@@ -40,6 +40,7 @@ export function unstable_noStore() { ...@@ -40,6 +40,7 @@ export function unstable_noStore() {
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'cache': case 'cache':
case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
break break
default: default:
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export default function Page() {
return (
<>
<p>
This page uses `connection()` inside `'use cache: private'`, which
triggers an error at runtime.
</p>
<Suspense fallback={<p>Loading...</p>}>
<Private />
</Suspense>
</>
)
}
async function Private() {
'use cache: private'
// Calling connection() in a cache context is not allowed. We're try/catching
// here to ensure that, in dev mode, this error is shown even when it's caught
// in userland.
try {
await connection()
} catch {}
return <p id="private">Private</p>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { headers } from 'next/headers'
import { Suspense } from 'react'
export default function Page() {
return (
<>
<p>
This page uses `headers()` inside `'use cache: private'`, which triggers
an error at runtime.
</p>
<Suspense fallback={<p>Loading...</p>}>
<Private />
</Suspense>
</>
)
}
async function Private() {
'use cache: private'
// Reading headers in a cache context is not allowed. We're try/catching here
// to ensure that, in dev mode, this error is shown even when it's caught in
// userland.
try {
await headers()
} catch {}
return <p id="private">Private</p>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { unstable_cache } from 'next/cache'
export default function Page() {
return (
<>
<p>
This page nests `'use cache: private'` in `unstable_cache`, which
triggers an error.
</p>
<ComponentWithCachedData />
</>
)
}
async function ComponentWithCachedData() {
const data = await getCachedData()
return <p>{data}</p>
}
const getCachedData = unstable_cache(async () => {
'use cache: private'
return fetch('https://next-data-api-endpoint.vercel.app/api/random').then(
(res) => res.json()
)
})
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
export default async function Page() {
'use cache'
return (
<>
<p>
This page nests `'use cache: private'` in `'use cache'`, which triggers
an error.
</p>
<Private />
</>
)
}
async function Private() {
'use cache: private'
return <p>Private</p>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
export default function Page() {
return (
<>
<p>
This page uses `'use cache: private'` without wrapping it in a Suspense
boundary. In the context of prerenders, private caches are considered
dynamic, so they need to be wrapped in a Suspense boundary. Otherwise,
it triggers an error.
</p>
<Private />
</>
)
}
async function Private() {
'use cache: private'
return <p>Private</p>
}
File mode changed from 100644 to 100755
...@@ -9,19 +9,23 @@ export function getPrerenderOutput( ...@@ -9,19 +9,23 @@ export function getPrerenderOutput(
): string { ): string {
const lines: string[] = [] const lines: string[] = []
let foundPrerenderingLine = false let foundPrerenderingLine = false
let i = 0 let a = 0
let n = 0
const replaceNextDistStackFrame = () => const replaceNextDistStackFrame = () =>
`at ${abc[i++ % abc.length]} (<next-dist-dir>)` `at ${abc[a++ % abc.length]} (<next-dist-dir>)`
const replaceAnonymousStackFrame = (_m, name) => { const replaceAnonymousStackFrame = (_m, name) => {
const deterministicName = hostElementsUsedInFixtures.includes(name) const deterministicName = hostElementsUsedInFixtures.includes(name)
? name ? name
: abc[i++ % abc.length] : abc[a++ % abc.length]
return `at ${deterministicName} (<anonymous>)` return `at ${deterministicName} (<anonymous>)`
} }
const replaceMinifiedName = () => `at ${abc[a++ % abc.length]} (`
const replaceNumericModuleId = () => `at ${n++} (`
for (let line of cliOutput.split('\n')) { for (let line of cliOutput.split('\n')) {
if (line.includes('Collecting page data')) { if (line.includes('Collecting page data')) {
foundPrerenderingLine = true foundPrerenderingLine = true
...@@ -37,17 +41,25 @@ export function getPrerenderOutput( ...@@ -37,17 +41,25 @@ export function getPrerenderOutput(
!ignoredLines.some((ignoredLine) => line.includes(ignoredLine)) !ignoredLines.some((ignoredLine) => line.includes(ignoredLine))
) { ) {
if (isMinified) { if (isMinified) {
line = line line = line.replace(
.replace(/at \S+ \(.next[^)]+\)/, replaceNextDistStackFrame) /at (\S+) \(<anonymous>\)/,
.replace(/at (\S+) \(<anonymous>\)/, replaceAnonymousStackFrame) replaceAnonymousStackFrame
)
} else { } else {
line = line.replace( line = line.replace(
/at (\S+) \((webpack:\/\/)\/src[^)]+\)/, /at (\S+) \((webpack:\/\/\/)src[^)]+\)/,
`at $1 ($2<next-src>)` `at $1 ($2<next-src>)`
) )
} }
line = line line = line
.replace(/at \S+ \(.next[^)]+\)/, replaceNextDistStackFrame)
.replace(
// Single-letter lower-case names are likely minified.
/at [a-z] \((?!(<next-dist-dir>|<anonymous>))/,
replaceMinifiedName
)
.replace(/at \d+ \(/, replaceNumericModuleId)
.replace(/digest: '\d+'/, "digest: '<error-digest>'") .replace(/digest: '\d+'/, "digest: '<error-digest>'")
// Convert a module function sequence expression, e.g.: // Convert a module function sequence expression, e.g.:
// - (0 , __TURBOPACK__imported__module__1836__.cookies)(...) // - (0 , __TURBOPACK__imported__module__1836__.cookies)(...)
...@@ -55,6 +67,9 @@ export function getPrerenderOutput( ...@@ -55,6 +67,9 @@ export function getPrerenderOutput(
// - (0 , cookies.U)(...) // - (0 , cookies.U)(...)
// - (0 , e.U)(...) // - (0 , e.U)(...)
.replace(/\(0 , \w+\.(\w+)\)\(\.\.\.\)/, '<module-function>()') .replace(/\(0 , \w+\.(\w+)\)\(\.\.\.\)/, '<module-function>()')
// TODO(veil): Bundler protocols should not appear in stack frames.
.replace('webpack:///', 'bundler:///')
.replace('turbopack:///[project]/', 'bundler:///')
lines.push(line) lines.push(line)
} }
......
import { unstable_cacheLife } from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Private />
</Suspense>
)
}
async function Private() {
'use cache: private'
unstable_cacheLife({ stale: 420 })
const cookie = (await cookies()).get('test-cookie')
const { headers } = await fetch(
'https://next-data-api-endpoint.vercel.app/api/echo-headers',
{ headers: { 'x-test-cookie': cookie?.value ?? '' } }
).then((res) => res.json() as Promise<{ headers: Record<string, string> }>)
const cookieHeader = headers['x-test-cookie']
return (
<pre>
test-cookie: <span id="test-cookie">{cookieHeader}</span>
</pre>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { getSentinelValue } from './sentinel'
export default async function Page() {
return (
<>
<PageSentinel />
<Suspense fallback={<p>Loading...</p>}>
<Private />
</Suspense>
</>
)
}
async function PageSentinel() {
'use cache'
return (
<p>
page: <span id="page-sentinel">{getSentinelValue()}</span>
</p>
)
}
async function Private() {
'use cache: private'
return (
<p>
private: <span id="private-sentinel">{getSentinelValue()}</span>
</p>
)
}
export default function Loading() {
return <p>Loading...</p>
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string }>
}) {
'use cache: private'
const { q } = await searchParams
return (
<p>
Query: <span id="search-param">{q}</span>
</p>
)
}
const { PHASE_PRODUCTION_BUILD } = require('next/constants')
export function getSentinelValue() {
return process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD
? 'buildtime'
: 'runtime'
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
useCache: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
const pprEnabled =
process.env.__NEXT_EXPERIMENTAL_PPR === 'true' ||
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'
describe('use-cache-private', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
it('excludes private caches from prerenders', async () => {
const browser = await next.browser('/')
expect(await browser.elementById('page-sentinel').text()).toBe(
isNextDev || !pprEnabled ? 'runtime' : 'buildtime'
)
expect(await browser.elementById('private-sentinel').text()).toBe('runtime')
})
it('allows reading cookies in private caches', async () => {
const browser = await next.browser('/cookies')
expect(await browser.elementById('test-cookie').text()).toBe('')
await browser.addCookie({ name: 'test-cookie', value: 'foo' })
await browser.refresh()
expect(await browser.elementById('test-cookie').text()).toBe('foo')
})
it('allows reading search params in private caches', async () => {
const browser = await next.browser('/search-params?q=foo')
expect(await browser.elementById('search-param').text()).toBe('foo')
await browser.loadPage(new URL('/search-params?q=bar', next.url).href)
expect(await browser.elementById('search-param').text()).toBe('bar')
})
})
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