Unverified Commit 8283b126 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Support accessing root params in `"use cache"` functions (#91191)

Root params (e.g. `import { lang } from 'next/root-params'`) can now be read inside `"use cache"` functions. The read root param values are automatically included in the cache key so that different root param combinations produce separate cache entries.

Since which root params a cache function reads is only known after execution, the cache key is reconciled post-generation. When root params are read, a two-key scheme is used: the full entry is stored under a specific key (coarse key + root param suffix), and a lightweight redirect entry is stored under the coarse key. The redirect entry's tags encode the root param names using the pattern `_N_RP_<rootParamName>` (e.g. `_N_RP_lang`), following the convention of existing internal tags like `_N_T_<pathname>` (e.g. `_N_T_/dashboard`) for implicit route tags. This allows a cold server to resolve the specific key on the first request after restart. An in-memory map (`knownRootParamsByFunctionId`) provides a fast path for subsequent invocations. When no root params are read, the full entry is stored directly under the coarse key with no redirect involved.

The in-memory map grows monotonically — if a function conditionally reads different root params across invocations, the set accumulates all observed param names. The redirect entry's tags are built from this combined set, ensuring cold servers always resolve the most complete specific key.

The two-key scheme only applies to the cache handler. The Resume Data Cache (RDC) always uses the coarse key because each page gets its own isolated RDC instance, so root params are fixed within a single RDC and no disambiguation is needed. When an RDC entry is found during resume, it seeds `knownRootParamsByFunctionId` so that subsequent cache handler lookups can use the specific key directly.

Reading root params inside `unstable_cache` still throws. Reading root params inside `"use cache"` nested within `unstable_cache` throws with a specific error message explaining the limitation.

Alternatives considered: extending the `CacheEntry` interface (would be a breaking change for custom cache handlers), encoding root param metadata in the stream via a wrapper object, or sentinel byte, or Flightception (runtime overhead of stream manipulation on every cache read), and deferring `cacheHandler.set` until after generation (breaks the cache handler's pending-set deduplication for concurrent requests).
parent 76d7dc1e
......@@ -1137,5 +1137,7 @@
"1136": "Page \"%s\" cannot use both \\`export const unstable_dynamicStaleTime\\` and \\`export const unstable_instant\\`.",
"1137": "\"%s\" cannot use \\`export const unstable_dynamicStaleTime\\`. This config is only supported in page files, not layouts.",
"1138": "`unstable_retry()` can only be used in the App Router. Use `reset()` in the Pages Router.",
"1139": "`unstable_catchError` can only be used in Client Components."
"1139": "`unstable_catchError` can only be used in Client Components.",
"1140": "Route %s used \\`import('next/root-params').%s()\\` inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.",
"1141": "Route %s used \\`import('next/root-params').%s()\\` inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead."
}
......@@ -35,6 +35,7 @@ export const NEXT_CACHE_TAG_MAX_ITEMS = 128
export const NEXT_CACHE_TAG_MAX_LENGTH = 256
export const NEXT_CACHE_SOFT_TAG_MAX_LENGTH = 1024
export const NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_'
export const NEXT_CACHE_ROOT_PARAM_TAG_ID = '_N_RP_'
// in seconds
export const CACHE_ONE_YEAR_SECONDS = 31536000
......
......@@ -44,6 +44,7 @@ describe('getDynamicHTMLPostponedState', () => {
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
readRootParamNames: undefined,
})
)
......
......@@ -345,6 +345,19 @@ export interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {
export interface PublicUseCacheStore extends CommonUseCacheStore {
readonly type: 'cache'
/**
* The root params for the current route. `undefined` when nested inside
* `unstable_cache`, which doesn't carry root params. Currently, `"use cache"`
* inside `unstable_cache` is allowed, so this case must be handled. The error
* message in `getRootParam` assumes this is the only scenario where
* `rootParams` is `undefined`.
*/
readonly rootParams: Params | undefined
/**
* Tracks which root param names were read during this cache invocation.
*/
readonly readRootParamNames: Set<string>
}
export interface PrivateUseCacheStore extends CommonUseCacheStore {
......@@ -354,9 +367,8 @@ export interface PrivateUseCacheStore extends CommonUseCacheStore {
readonly cookies: ReadonlyRequestCookies
/**
* Private caches don't currently need to track root params in the cache key
* because they're not persisted anywhere, so we can allow root params access
* (unlike public caches)
* Private caches don't currently need to track read root params for the cache
* key because they're not persisted anywhere.
*/
readonly rootParams: Params
}
......@@ -365,6 +377,12 @@ export type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore
export interface UnstableCacheStore extends CommonCacheStore {
readonly type: 'unstable-cache'
/**
* Always `undefined` for `unstable_cache` — root params are not available in
* this context. If a `"use cache"` function nested inside `unstable_cache`
* tries to access root params, it will encounter `undefined` here and throw.
*/
readonly rootParams: undefined
}
/**
......
......@@ -58,12 +58,20 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
}
switch (workUnitStore.type) {
case 'unstable-cache':
case 'unstable-cache': {
throw new Error(
`Route ${workStore.route} used ${apiName} inside \`unstable_cache\`. This is not supported. Use \`"use cache"\` instead.`
)
}
case 'cache': {
if (!workUnitStore.rootParams) {
throw new Error(
`Route ${workStore.route} used ${apiName} 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 ${apiName} inside \`"use cache"\` nested within \`unstable_cache\`. Root params are not available in this context.`
)
}
workUnitStore.readRootParamNames.add(paramName)
return Promise.resolve(workUnitStore.rootParams[paramName])
}
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': {
......
......@@ -44,6 +44,7 @@ export interface UseCacheCacheStoreSerialized {
}
hasExplicitRevalidate: boolean | undefined
hasExplicitExpire: boolean | undefined
readRootParamNames: string[] | undefined
}
/**
......@@ -64,7 +65,7 @@ export function parseUseCacheCacheStore(
for (const [
key,
{ entry, hasExplicitRevalidate, hasExplicitExpire },
{ entry, hasExplicitRevalidate, hasExplicitExpire, readRootParamNames },
] of entries) {
store.set(
key,
......@@ -88,6 +89,9 @@ export function parseUseCacheCacheStore(
},
hasExplicitRevalidate,
hasExplicitExpire,
readRootParamNames: readRootParamNames
? new Set(readRootParamNames)
: undefined,
})
)
}
......@@ -107,7 +111,13 @@ export async function serializeUseCacheCacheStore(
return Promise.all(
Array.from(entries).map(([key, value]) => {
return value
.then(async ({ entry, hasExplicitRevalidate, hasExplicitExpire }) => {
.then(
async ({
entry,
hasExplicitRevalidate,
hasExplicitExpire,
readRootParamNames,
}) => {
if (
isCacheComponentsEnabled &&
(entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE)
......@@ -143,9 +153,13 @@ export async function serializeUseCacheCacheStore(
},
hasExplicitRevalidate,
hasExplicitExpire,
readRootParamNames: readRootParamNames
? [...readRootParamNames]
: undefined,
},
] satisfies [string, UseCacheCacheStoreSerialized]
})
}
)
.catch(() => {
// Any failed cache writes should be ignored as to not discard the
// entire cache.
......
......@@ -25,6 +25,7 @@ function createMockedCache() {
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
readRootParamNames: undefined,
})
)
......@@ -42,6 +43,7 @@ function createMockedCache() {
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
readRootParamNames: undefined,
})
)
......@@ -59,6 +61,7 @@ function createMockedCache() {
},
hasExplicitRevalidate: true,
hasExplicitExpire: true,
readRootParamNames: undefined,
})
)
......
......@@ -55,6 +55,8 @@ import { decryptActionBoundArgs } from '../app-render/encryption'
import { InvariantError } from '../../shared/lib/invariant-error'
import { createReactServerErrorHandler } from '../app-render/create-error-handler'
import { DYNAMIC_EXPIRE, RUNTIME_PREFETCH_DYNAMIC_STALE } from './constants'
import { NEXT_CACHE_ROOT_PARAM_TAG_ID } from '../../lib/constants'
import type { CacheHandler } from '../lib/cache-handlers/types'
import { getCacheHandler } from './handlers'
import { UseCacheTimeoutError } from './use-cache-errors'
import {
......@@ -67,6 +69,7 @@ import {
type SearchParams,
} from '../request/search-params'
import type { Params } from '../request/params'
import type { PrerenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import { createLazyResult, isResolvedLazyResult } from '../lib/lazy-result'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
import type { CacheLife } from './cache-life'
......@@ -151,6 +154,131 @@ const nestedCacheShortExpireErrorMessage =
`dynamic (with short \`expire\`). Read more: ` +
`https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife`
// Tracks which root params each cache function has historically read. Used to
// compute the specific cache key upfront on subsequent invocations. In-memory
// only — after server restart, the coarse-key redirect entry in the cache
// handler provides fallback.
const knownRootParamsByFunctionId = new Map<string, Set<string>>()
function addKnownRootParamNames(
id: string,
names: ReadonlySet<string>
): Set<string> {
const existing = knownRootParamsByFunctionId.get(id)
if (existing) {
for (const name of names) {
existing.add(name)
}
return existing
}
const created = new Set(names)
knownRootParamsByFunctionId.set(id, created)
return created
}
function computeRootParamsCacheKeySuffix(
rootParams: Params,
paramNames: ReadonlySet<string>
): string {
if (paramNames.size === 0) {
return ''
}
return JSON.stringify(
[...paramNames]
.sort()
.map((paramName) => [paramName, rootParams[paramName]])
)
}
function saveToResumeDataCache(
prerenderResumeDataCache: PrerenderResumeDataCache | null,
serializedCacheKey: string,
pendingCacheResult: Promise<CollectedCacheResult>
): Promise<CollectedCacheResult> {
if (!prerenderResumeDataCache) {
return pendingCacheResult
}
const split = clonePendingCacheResult(pendingCacheResult)
const savedCacheResult = getNthCacheResult(split, 0)
const rdcResult = getNthCacheResult(split, 1)
// The RDC is per-page and root params are fixed within a page, so we always
// use the coarse key (without root param suffix). Unlike the cache handler,
// the RDC doesn't need root-param-specific keys for isolation.
prerenderResumeDataCache.cache.set(serializedCacheKey, rdcResult)
return savedCacheResult
}
function saveToCacheHandler(
cacheHandler: CacheHandler,
workStore: WorkStore,
id: string,
serializedCacheKey: string,
savedCacheResult: Promise<CollectedCacheResult>,
rootParams: Params | undefined
): void {
const pendingCoarseEntry = savedCacheResult.then((collectedResult) => {
const { entry: fullEntry, readRootParamNames } = collectedResult
// Use the combined set (union of all historically observed reads) for both
// the specific key and the redirect entry's tags. The read path computes
// cacheHandlerKey from this same union (knownRootParamsByFunctionId), so
// the write path must use the identical set to land on the same specific
// key. If we used only the current invocation's reads, a function that
// conditionally reads different root params across invocations would
// scatter entries across different specific keys, making previous entries
// unreachable from the read path's union-based lookup.
const rootParamNames = readRootParamNames
? addKnownRootParamNames(id, readRootParamNames)
: knownRootParamsByFunctionId.get(id)
if (rootParamNames && rootParamNames.size > 0 && rootParams) {
const specificKey =
serializedCacheKey +
computeRootParamsCacheKeySuffix(rootParams, rootParamNames)
const specificSetPromise = cacheHandler.set(
specificKey,
Promise.resolve(fullEntry)
)
workStore.pendingRevalidateWrites ??= []
workStore.pendingRevalidateWrites.push(specificSetPromise)
// Return a redirect entry for the coarse key. On a cold server (empty
// knownRootParamsByFunctionId), this entry's tags tell us which root
// params to include in the specific key for the follow-up lookup.
const rootParamTags = [...rootParamNames].map(
(paramName) => NEXT_CACHE_ROOT_PARAM_TAG_ID + paramName
)
return {
value: new ReadableStream({
start(controller) {
// Single byte so the entry has non-zero size in LRU caches.
controller.enqueue(new Uint8Array([0]))
controller.close()
},
}),
tags: [...fullEntry.tags, ...rootParamTags],
stale: fullEntry.stale,
timestamp: fullEntry.timestamp,
expire: fullEntry.expire,
revalidate: fullEntry.revalidate,
} satisfies CacheEntry
}
return fullEntry
})
const promise = cacheHandler.set(serializedCacheKey, pendingCoarseEntry)
workStore.pendingRevalidateWrites ??= []
workStore.pendingRevalidateWrites.push(promise)
}
function generateCacheEntry(
workStore: WorkStore,
cacheContext: CacheContext,
......@@ -274,6 +402,8 @@ function createUseCacheStore(
workStore,
outerWorkUnitStore
),
rootParams: outerWorkUnitStore.rootParams,
readRootParamNames: new Set<string>(),
}
}
}
......@@ -363,9 +493,10 @@ function propagateCacheStaleTimeToRequestStore(
}
}
function propagateCacheLifeAndTags(
function propagateCacheEntryMetadata(
cacheContext: CacheContext,
entry: CacheEntry
entry: CacheEntry,
readRootParamNames: ReadonlySet<string> | undefined
): void {
if (cacheContext.kind === 'private') {
switch (cacheContext.outerWorkUnitStore.type) {
......@@ -390,6 +521,12 @@ function propagateCacheLifeAndTags(
} else {
switch (cacheContext.outerWorkUnitStore.type) {
case 'cache':
if (readRootParamNames) {
for (const paramName of readRootParamNames) {
cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName)
}
}
// fallthrough
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
......@@ -433,6 +570,13 @@ export interface CollectedCacheResult {
* - `undefined`: unknown (e.g. pre-existing entry from a cache handler)
*/
hasExplicitExpire: boolean | undefined
/**
* The root param names that were read during cache entry generation.
* Used to compute the specific cache key after generation completes.
* `undefined` for pre-existing entries from cache handlers where we
* don't have this information.
*/
readRootParamNames: ReadonlySet<string> | undefined
}
async function collectResult(
......@@ -543,7 +687,13 @@ async function collectResult(
case 'unstable-cache':
case 'prerender-legacy':
case 'prerender-ppr': {
propagateCacheLifeAndTags(cacheContext, entry)
propagateCacheEntryMetadata(
cacheContext,
entry,
innerCacheStore.type === 'cache'
? innerCacheStore.readRootParamNames
: undefined
)
break
}
case 'generate-static-params':
......@@ -563,6 +713,10 @@ async function collectResult(
entry,
hasExplicitRevalidate: innerCacheStore.explicitRevalidate !== undefined,
hasExplicitExpire: innerCacheStore.explicitExpire !== undefined,
readRootParamNames:
innerCacheStore.type === 'cache'
? innerCacheStore.readRootParamNames
: undefined,
}
}
......@@ -834,11 +988,13 @@ function cloneCacheResult(
entry: entryA,
hasExplicitRevalidate: result.hasExplicitRevalidate,
hasExplicitExpire: result.hasExplicitExpire,
readRootParamNames: result.readRootParamNames,
},
{
entry: entryB,
hasExplicitRevalidate: result.hasExplicitRevalidate,
hasExplicitExpire: result.hasExplicitExpire,
readRootParamNames: result.readRootParamNames,
},
]
}
......@@ -1309,6 +1465,17 @@ export async function cache(
encodedCacheKeyParts
: await encodeFormData(encodedCacheKeyParts)
// If we already know which root params this function reads, include them in
// the cache handler key for a direct hit (skipping the redirect entry).
// rootParams is undefined when nested inside unstable_cache.
const rootParams = workUnitStore.rootParams
const knownRootParamNames = knownRootParamsByFunctionId.get(id)
let cacheHandlerKey =
knownRootParamNames && rootParams
? serializedCacheKey +
computeRootParamsCacheKeySuffix(rootParams, knownRootParamNames)
: serializedCacheKey
let stream: undefined | ReadableStream = undefined
// Get an immutable and mutable versions of the resume data cache.
......@@ -1323,16 +1490,16 @@ export async function cache(
if (cacheSignal) {
cacheSignal.beginRead()
}
const cachedResult = renderResumeDataCache.cache.get(serializedCacheKey)
if (cachedResult !== undefined) {
let existingResult: CollectedCacheResult | undefined = await cachedResult
const rdcEntry = renderResumeDataCache.cache.get(serializedCacheKey)
if (rdcEntry !== undefined) {
let rdcResult: CollectedCacheResult | undefined = await rdcEntry
// Check if the RDC entry should be discarded due to recently revalidated tags.
// When a server action calls updateTag(), the re-render should see fresh data
// instead of stale RDC data.
if (existingResult !== undefined) {
// Check if the RDC entry should be discarded due to recently revalidated
// tags. When a server action calls updateTag(), the re-render should see
// fresh data instead of stale RDC data.
if (rdcResult !== undefined) {
if (
existingResult.entry.tags.some((tag) =>
rdcResult.entry.tags.some((tag) =>
isRecentlyRevalidatedTag(tag, workStore)
) ||
implicitTags.some((tag) => isRecentlyRevalidatedTag(tag, workStore))
......@@ -1341,14 +1508,14 @@ export async function cache(
'discarding RDC entry due to recently revalidated tags',
serializedCacheKey
)
existingResult = undefined
rdcResult = undefined
}
}
if (existingResult !== undefined) {
if (rdcResult !== undefined) {
if (
existingResult.entry.revalidate === 0 ||
existingResult.entry.expire < DYNAMIC_EXPIRE
rdcResult.entry.revalidate === 0 ||
rdcResult.entry.expire < DYNAMIC_EXPIRE
) {
switch (workUnitStore.type) {
case 'prerender':
......@@ -1358,8 +1525,8 @@ export async function cache(
// generating static pages for such data. It's better to leave
// a dynamic hole that can be filled in during the resume with
// a potentially cached entry.
if (existingResult.entry.revalidate === 0) {
if (existingResult.hasExplicitRevalidate === false) {
if (rdcResult.entry.revalidate === 0) {
if (rdcResult.hasExplicitRevalidate === false) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheZeroRevalidateErrorMessage),
workStore
......@@ -1371,7 +1538,7 @@ export async function cache(
'from static shell due to revalidate: 0'
)
} else {
if (existingResult.hasExplicitExpire === false) {
if (rdcResult.hasExplicitExpire === false) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheShortExpireErrorMessage),
workStore
......@@ -1381,7 +1548,7 @@ export async function cache(
'omitting entry',
serializedCacheKey,
'from static shell due to short expire value:',
existingResult.entry.expire
rdcResult.entry.expire
)
}
if (cacheSignal) {
......@@ -1407,8 +1574,8 @@ export async function cache(
case 'request': {
if (process.env.NODE_ENV === 'development') {
if (
existingResult.entry.revalidate === 0 &&
existingResult.hasExplicitRevalidate === false
rdcResult.entry.revalidate === 0 &&
rdcResult.hasExplicitRevalidate === false
) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheZeroRevalidateErrorMessage),
......@@ -1416,8 +1583,8 @@ export async function cache(
)
}
if (
existingResult.entry.expire < DYNAMIC_EXPIRE &&
existingResult.hasExplicitExpire === false
rdcResult.entry.expire < DYNAMIC_EXPIRE &&
rdcResult.hasExplicitExpire === false
) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheShortExpireErrorMessage),
......@@ -1454,7 +1621,7 @@ export async function cache(
}
}
if (existingResult.entry.stale < RUNTIME_PREFETCH_DYNAMIC_STALE) {
if (rdcResult.entry.stale < RUNTIME_PREFETCH_DYNAMIC_STALE) {
switch (workUnitStore.type) {
case 'prerender-runtime':
// In a runtime prerender, if the cache entry will become
......@@ -1465,7 +1632,7 @@ export async function cache(
'omitting entry',
serializedCacheKey,
'from runtime shell due to short stale value:',
existingResult.entry.stale
rdcResult.entry.stale
)
if (cacheSignal) {
cacheSignal.endRead()
......@@ -1505,20 +1672,31 @@ export async function cache(
}
}
if (existingResult !== undefined) {
if (rdcResult !== undefined) {
debug?.('Resume Data Cache entry found', serializedCacheKey)
if (prerenderResumeDataCache) {
prerenderResumeDataCache.cache.set(serializedCacheKey, cachedResult)
prerenderResumeDataCache.cache.set(serializedCacheKey, rdcEntry)
}
if (
rdcResult.readRootParamNames &&
rdcResult.readRootParamNames.size > 0
) {
addKnownRootParamNames(id, rdcResult.readRootParamNames)
}
// We want to make sure we only propagate cache life & tags if the
// entry was *not* omitted from the prerender. So we only do this
// after the above early returns.
propagateCacheLifeAndTags(cacheContext, existingResult.entry)
propagateCacheEntryMetadata(
cacheContext,
rdcResult.entry,
rdcResult.readRootParamNames
)
const [streamA, streamB] = existingResult.entry.value.tee()
existingResult.entry.value = streamB
const [streamA, streamB] = rdcResult.entry.value.tee()
rdcResult.entry.value = streamB
if (cacheSignal) {
// When we have a cacheSignal we need to block on reading the cache
......@@ -1599,7 +1777,26 @@ export async function cache(
// We ignore existing cache entries when force revalidating.
if (cacheHandler && !shouldForceRevalidate(workStore, workUnitStore)) {
entry = await cacheHandler.get(serializedCacheKey, implicitTags)
entry = await cacheHandler.get(cacheHandlerKey, implicitTags)
// Check if this is a redirect entry (coarse key → specific key). Redirect
// entries have private tags encoding the root param names (one tag per
// param name, prefixed with _N_RP_).
if (entry && rootParams) {
const paramNames = new Set<string>()
for (const tag of entry.tags) {
if (tag.startsWith(NEXT_CACHE_ROOT_PARAM_TAG_ID)) {
paramNames.add(tag.slice(NEXT_CACHE_ROOT_PARAM_TAG_ID.length))
}
}
if (paramNames.size > 0) {
addKnownRootParamNames(id, paramNames)
cacheHandlerKey =
serializedCacheKey +
computeRootParamsCacheKeySuffix(rootParams, paramNames)
entry = await cacheHandler.get(cacheHandlerKey, implicitTags)
}
}
}
if (entry) {
......@@ -1634,7 +1831,7 @@ export async function cache(
implicitTagsExpiration
)
) {
debug?.('discarding expired entry', serializedCacheKey)
debug?.('discarding expired entry', cacheHandlerKey)
entry = undefined
}
}
......@@ -1655,13 +1852,13 @@ export async function cache(
if (entry.revalidate === 0) {
debug?.(
'omitting entry',
serializedCacheKey,
cacheHandlerKey,
'from static shell due to revalidate: 0'
)
} else {
debug?.(
'omitting entry',
serializedCacheKey,
cacheHandlerKey,
'from static shell due to short expire value:',
entry.expire
)
......@@ -1723,14 +1920,14 @@ export async function cache(
if (entry) {
if (currentTime > entry.timestamp + entry.expire * 1000) {
debug?.('entry is expired', serializedCacheKey)
debug?.('entry is expired', cacheHandlerKey)
}
if (
workStore.isStaticGeneration &&
currentTime > entry.timestamp + entry.revalidate * 1000
) {
debug?.('static generation, entry is stale', serializedCacheKey)
debug?.('static generation, entry is stale', cacheHandlerKey)
}
}
......@@ -1751,28 +1948,21 @@ export async function cache(
// When draft mode is enabled, we must not save the cache entry.
if (!workStore.isDraftMode) {
let savedCacheResult
if (prerenderResumeDataCache) {
// Create a clone that goes into the cache scope memory cache.
const split = clonePendingCacheResult(pendingCacheResult)
savedCacheResult = getNthCacheResult(split, 0)
prerenderResumeDataCache.cache.set(
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
serializedCacheKey,
getNthCacheResult(split, 1)
pendingCacheResult
)
} else {
savedCacheResult = pendingCacheResult
}
if (cacheHandler) {
const promise = cacheHandler.set(
saveToCacheHandler(
cacheHandler,
workStore,
id,
serializedCacheKey,
savedCacheResult.then((r) => r.entry)
savedCacheResult,
rootParams
)
workStore.pendingRevalidateWrites ??= []
workStore.pendingRevalidateWrites.push(promise)
}
}
......@@ -1786,13 +1976,17 @@ export async function cache(
)
}
propagateCacheLifeAndTags(cacheContext, entry)
propagateCacheEntryMetadata(
cacheContext,
entry,
knownRootParamsByFunctionId.get(id)
)
// We want to return this stream, even if it's stale.
stream = entry.value
// If we have a cache scope, we need to clone the entry and set it on
// the inner cache scope.
// If we have a resume data cache, we need to clone the entry and add it
// to the resume data cache.
if (prerenderResumeDataCache) {
const [entryLeft, entryRight] = cloneCacheEntry(entry)
if (cacheSignal) {
......@@ -1801,6 +1995,8 @@ export async function cache(
stream = entryLeft.value
}
// The RDC is per-page and root params are fixed within a page, so we
// always use the coarse key (without root param suffix).
prerenderResumeDataCache.cache.set(
serializedCacheKey,
Promise.resolve({
......@@ -1813,6 +2009,7 @@ export async function cache(
// set this to undefined here.
hasExplicitRevalidate: undefined,
hasExplicitExpire: undefined,
readRootParamNames: knownRootParamNames,
})
)
} else {
......@@ -1844,27 +2041,22 @@ export async function cache(
if (result.type === 'cached') {
const { stream: ignoredStream, pendingCacheResult } = result
let savedCacheResult: Promise<CollectedCacheResult>
if (prerenderResumeDataCache) {
const split = clonePendingCacheResult(pendingCacheResult)
savedCacheResult = getNthCacheResult(split, 0)
prerenderResumeDataCache.cache.set(
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
serializedCacheKey,
getNthCacheResult(split, 1)
pendingCacheResult
)
} else {
savedCacheResult = pendingCacheResult
}
if (cacheHandler) {
const promise = cacheHandler.set(
saveToCacheHandler(
cacheHandler,
workStore,
id,
serializedCacheKey,
savedCacheResult.then((r) => r.entry)
savedCacheResult,
rootParams
)
workStore.pendingRevalidateWrites ??= []
workStore.pendingRevalidateWrites.push(promise)
}
await ignoredStream.cancel()
......
......@@ -148,6 +148,7 @@ export function unstable_cache<T extends Callback>(
workUnitStore &&
workStore &&
getDraftModeProviderForCacheScope(workStore, workUnitStore),
rootParams: undefined,
}
if (workStore) {
......
import { lang, locale } from 'next/root-params'
export default async function Page() {
const rootParams = await getCachedParams()
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
const result = await getCachedData()
return (
<p>
<span id="param">
{rootParams.lang} {rootParams.locale}
{result.lang} {result.locale}
</span>{' '}
<span id="random">{data}</span>
<span id="random">{result.random}</span>
</p>
)
}
async function getCachedParams() {
async function getCachedData() {
'use cache'
return { lang: await lang(), locale: await locale() }
const random = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return { lang: await lang(), locale: await locale(), random }
}
import { lang } from 'next/root-params'
import { cacheTag, updateTag } from 'next/cache'
import { connection } from 'next/server'
import { Suspense } from 'react'
let flagValue = false
async function getFlag() {
'use cache: remote'
cacheTag('flag-tag')
return flagValue
}
async function conditionalOnAnotherCache() {
'use cache: remote'
const random = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
const flag = await getFlag()
if (flag) {
return { lang: await lang(), random }
}
return { lang: null, random }
}
async function Runtime() {
await connection()
const result = await conditionalOnAnotherCache()
return (
<div>
<p id="lang-value">{String(result.lang)}</p>
<p id="random">{result.random}</p>
<form>
<button
id="enable-flag"
formAction={async () => {
'use server'
flagValue = true
updateTag('flag-tag')
}}
>
Enable flag
</button>
<button
id="disable-flag"
formAction={async () => {
'use server'
flagValue = false
updateTag('flag-tag')
}}
>
Disable flag
</button>
</form>
</div>
)
}
export default async function Page() {
return (
<Suspense fallback="Loading...">
<Runtime />
</Suspense>
)
}
import { lang, countryCode } from 'next/root-params'
import { connection } from 'next/server'
import { Suspense } from 'react'
async function conditionalOnRootParam() {
'use cache: remote'
const random = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
const currentLang = await lang()
if (currentLang === 'en') {
return { lang: currentLang, countryCode: await countryCode(), random }
}
return { lang: currentLang, countryCode: null, random }
}
async function Runtime() {
await connection()
const result = await conditionalOnRootParam()
return (
<div>
<p id="lang-value">{String(result.lang)}</p>
<p id="country-code-value">{String(result.countryCode)}</p>
<p id="random">{result.random}</p>
</div>
)
}
export default async function Page() {
return (
<Suspense fallback="Loading...">
<Runtime />
</Suspense>
)
}
......@@ -9,8 +9,9 @@ export default function Root({ children }: { children: ReactNode }) {
}
export function generateStaticParams() {
// the param values are not accessed in tests,
// we just need a value here to avoid errors in PPR/cacheComponents
// where we need to provide at least one set of values for root params
return [{ lang: 'foo', locale: 'bar' }]
return [
{ lang: 'en', countryCode: 'us' },
{ lang: 'en', countryCode: 'gb' },
{ lang: 'fr', countryCode: 'ca' },
]
}
import { lang } from 'next/root-params'
import { connection } from 'next/server'
import { Suspense } from 'react'
async function maybeReadsRootParam(readLang: boolean) {
'use cache: remote'
const random = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
if (readLang) {
return { lang: await lang(), random }
}
return { lang: null, random }
}
async function Runtime() {
await connection()
// The `true` call must come first so that `saveToCacheHandler` adds `lang`
// to `knownRootParamsByFunctionId` before the `false` call's lookup runs.
const withLang = await maybeReadsRootParam(true)
const withoutLang = await maybeReadsRootParam(false)
return (
<div>
<p id="with-lang-random">{withLang.random}</p>
<p id="with-lang-value">{String(withLang.lang)}</p>
<p id="without-lang-random">{withoutLang.random}</p>
<p id="without-lang-value">{String(withoutLang.lang)}</p>
</div>
)
}
export default async function Page() {
return (
<Suspense fallback="Loading...">
<Runtime />
</Suspense>
)
}
import { lang, countryCode } from 'next/root-params'
import { unstable_cache } from 'next/cache'
import { connection } from 'next/server'
import { Suspense } from 'react'
export default async function Page() {
return (
<Suspense fallback="Loading...">
<Runtime />
</Suspense>
)
}
async function Runtime() {
await connection()
const getParams = unstable_cache(getCachedParams)
const rootParams = await getParams()
return (
<p id="param">
{rootParams.lang} {rootParams.countryCode}
</p>
)
}
async function getCachedParams() {
'use cache'
return { lang: await lang(), countryCode: await countryCode() }
}
import { Suspense } from 'react'
import { lang, locale } from 'next/root-params'
import { lang, countryCode } from 'next/root-params'
import { connection } from 'next/server'
import { unstable_cache } from 'next/cache'
......@@ -22,7 +22,7 @@ async function Runtime() {
return (
<p>
<span id="param">
{rootParams.lang} {rootParams.locale}
{rootParams.lang} {rootParams.countryCode}
</span>{' '}
<span id="random">{data}</span>
</p>
......@@ -30,5 +30,5 @@ async function Runtime() {
}
const getCachedParams = unstable_cache(async function uncachedGetParams() {
return { lang: await lang(), locale: await locale() }
return { lang: await lang(), countryCode: await countryCode() }
})
import { lang, countryCode } from 'next/root-params'
import { connection } from 'next/server'
import { Suspense } from 'react'
async function getCachedData() {
'use cache'
const random = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return { lang: await lang(), countryCode: await countryCode(), random }
}
export default async function Page() {
const result = await getCachedData()
return (
<>
<p>
<span id="param">
{result.lang} {result.countryCode}
</span>{' '}
<span id="random">{result.random}</span>
</p>
<Suspense fallback={<p id="fallback">Loading...</p>}>
<Dynamic />
</Suspense>
</>
)
}
async function Dynamic() {
await connection()
return <p id="dynamic">dynamic</p>
}
import { lang, locale } from 'next/root-params'
import { lang, countryCode } from 'next/root-params'
import { connection } from 'next/server'
import { Suspense } from 'react'
......@@ -13,22 +13,24 @@ export default async function Page() {
async function Runtime() {
await connection()
const rootParams = await getCachedParams()
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
const result = await getCachedData()
return (
<p>
<span id="param">
{rootParams.lang} {rootParams.locale}
{result.lang} {result.countryCode}
</span>{' '}
<span id="random">{data}</span>
<span id="random">{result.random}</span>
</p>
)
}
async function getCachedParams() {
'use cache'
return { lang: await lang(), locale: await locale() }
async function getCachedData() {
'use cache: remote'
const random = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return { lang: await lang(), countryCode: await countryCode(), random }
}
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
import { waitForNoRedbox } from 'next-test-utils'
import { assertNoConsoleErrors, retry, waitForNoRedbox } from 'next-test-utils'
describe('app-root-param-getters - cache - at runtime', () => {
const { next, isNextDev, skipped } = nextTestSetup({
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: join(__dirname, 'fixtures', 'use-cache-runtime'),
// this test asserts on build failure logs, which aren't currently observable in `next.cliOutput`.
skipDeployment: true,
})
if (skipped) return
if (isNextDev) {
it('should error when using root params within a "use cache" - dev', async () => {
it('should allow using root params within a "use cache" - dev', async () => {
const browser = await next.browser('/en/us/use-cache')
await waitForNoRedbox(browser)
expect(await browser.elementById('param').text()).toBe('en us')
})
it('should error when using root params within `unstable_cache` - dev', async () => {
const browser = await next.browser('/en/us/unstable_cache')
await expect(browser).toDisplayRedbox(`
{
"code": "E1012",
"description": "Route /[lang]/[locale]/use-cache used \`import('next/root-params').lang()\` inside \`"use cache"\` or \`unstable_cache\`. Support for this API inside cache scopes is planned for a future version of Next.js.",
"environmentLabel": "Cache",
"code": "E1141",
"description": "Route /[lang]/[countryCode]/unstable_cache used \`import('next/root-params').lang()\` inside \`unstable_cache\`. This is not supported. Use \`"use cache"\` instead.",
"environmentLabel": "Server",
"label": "Runtime Error",
"source": "app/[lang]/[locale]/use-cache/page.tsx (33:28) @ getCachedParams
> 33 | return { lang: await lang(), locale: await locale() }
"source": "app/[lang]/[countryCode]/unstable_cache/page.tsx (33:28) @ uncachedGetParams
> 33 | return { lang: await lang(), countryCode: await countryCode() }
| ^",
"stack": [
"getCachedParams app/[lang]/[locale]/use-cache/page.tsx (33:28)",
"uncachedGetParams app/[lang]/[countryCode]/unstable_cache/page.tsx (33:28)",
"Runtime app/[lang]/[countryCode]/unstable_cache/page.tsx (17:22)",
],
}
`)
})
it('should error when using root params within `unstable_cache` - dev', async () => {
const browser = await next.browser('/en/us/unstable_cache')
it('should error when using root params in "use cache" nested inside unstable_cache - dev', async () => {
const browser = await next.browser('/en/us/nested-in-unstable_cache')
await expect(browser).toDisplayRedbox(`
{
"code": "E1012",
"description": "Route /[lang]/[locale]/unstable_cache used \`import('next/root-params').lang()\` inside \`"use cache"\` or \`unstable_cache\`. Support for this API inside cache scopes is planned for a future version of Next.js.",
"environmentLabel": "Server",
"code": "E1140",
"description": "Route /[lang]/[countryCode]/nested-in-unstable_cache used \`import('next/root-params').lang()\` inside \`"use cache"\` nested within \`unstable_cache\`. Root params are not available in this context.",
"environmentLabel": "Cache",
"label": "Runtime Error",
"source": "app/[lang]/[locale]/unstable_cache/page.tsx (33:28) @ uncachedGetParams
> 33 | return { lang: await lang(), locale: await locale() }
"source": "app/[lang]/[countryCode]/nested-in-unstable_cache/page.tsx (29:28) @ getCachedParams
> 29 | return { lang: await lang(), countryCode: await countryCode() }
| ^",
"stack": [
"uncachedGetParams app/[lang]/[locale]/unstable_cache/page.tsx (33:28)",
"Runtime app/[lang]/[locale]/unstable_cache/page.tsx (17:22)",
"getCachedParams app/[lang]/[countryCode]/nested-in-unstable_cache/page.tsx (29:28)",
],
}
`)
})
} else {
it('should error when using root params within a "use cache" - start', async () => {
await next.render$('/en/us/use-cache')
expect(next.cliOutput).toInclude(
'Error: Route /[lang]/[locale]/use-cache used `import(\'next/root-params\').lang()` inside `"use cache"` or `unstable_cache`'
it('should allow using root params within a "use cache" - start', async () => {
const browser = await next.browser('/en/us/use-cache')
expect(await browser.elementById('param').text()).toBe('en us')
})
it('should create separate cache entries for different root params', async () => {
const browser = await next.browser('/en/us/use-cache')
expect(await browser.elementById('param').text()).toBe('en us')
const enRandom = await browser.elementById('random').text()
await browser.loadPage(next.url + '/fr/ca/use-cache')
expect(await browser.elementById('param').text()).toBe('fr ca')
const frRandom = await browser.elementById('random').text()
// Different root params must produce different cache entries.
expect(enRandom).not.toBe(frRandom)
// Each entry must be individually cached (same random on revisit).
await browser.loadPage(next.url + '/en/us/use-cache')
expect(await browser.elementById('random').text()).toBe(enRandom)
await browser.loadPage(next.url + '/fr/ca/use-cache')
expect(await browser.elementById('random').text()).toBe(frRandom)
})
it('should resume with the same cached data that was prerendered', async () => {
const browser = await next.browser('/en/us/use-cache-resume', {
pushErrorAsConsoleLog: true,
})
expect(await browser.elementById('random').text()).toBeTruthy()
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('dynamic')
})
// If the Resume Data Cache lookup missed during the resume (e.g. due
// to a key mismatch caused by root params), the "use cache" function
// would re-execute and produce a different random value than the one
// in the prerendered shell, causing a hydration error.
await assertNoConsoleErrors(browser)
})
it('should handle conditional root param reads based on arguments', async () => {
const browser = await next.browser('/en/us/maybe-reads-root-param')
expect(await browser.elementById('with-lang-value').text()).toBe('en')
expect(await browser.elementById('without-lang-value').text()).toBe(
'null'
)
const enWithRandom = await browser.elementById('with-lang-random').text()
const enWithoutRandom = await browser
.elementById('without-lang-random')
.text()
await browser.loadPage(next.url + '/fr/ca/maybe-reads-root-param')
expect(await browser.elementById('with-lang-value').text()).toBe('fr')
expect(await browser.elementById('without-lang-value').text()).toBe(
'null'
)
const frWithRandom = await browser.elementById('with-lang-random').text()
const frWithoutRandom = await browser
.elementById('without-lang-random')
.text()
// Different root params produce different cache entries.
expect(frWithRandom).not.toBe(enWithRandom)
// The without-lang call doesn't read lang, but after
// knownRootParamsByFunctionId grows, the key includes lang too, so
// different root params still produce different entries.
expect(frWithoutRandom).not.toBe(enWithoutRandom)
// Revisit to confirm cache hits.
await browser.loadPage(next.url + '/en/us/maybe-reads-root-param')
expect(await browser.elementById('with-lang-random').text()).toBe(
enWithRandom
)
expect(await browser.elementById('without-lang-random').text()).toBe(
enWithoutRandom
)
await browser.loadPage(next.url + '/fr/ca/maybe-reads-root-param')
expect(await browser.elementById('with-lang-random').text()).toBe(
frWithRandom
)
expect(await browser.elementById('without-lang-random').text()).toBe(
frWithoutRandom
)
})
it('should handle root param reads introduced after revalidation', async () => {
const browser = await next.browser('/en/us/conditional-on-another-cache')
// Reset the flag in case a previous test attempt left it enabled.
if ((await browser.elementById('lang-value').text()) !== 'null') {
await browser.elementById('disable-flag').click()
await retry(async () => {
expect(await browser.elementById('lang-value').text()).toBe('null')
})
}
// Before the flag is enabled, lang is not read on any route.
await browser.loadPage(next.url + '/fr/ca/conditional-on-another-cache')
expect(await browser.elementById('lang-value').text()).toBe('null')
// Enable the flag and revalidate (staying on the fr/ca page).
await browser.elementById('enable-flag').click()
await retry(async () => {
expect(await browser.elementById('lang-value').text()).toBe('fr')
})
// Wait for the cache to settle by verifying the random value is
// stable across two consecutive loads.
let frRandom: string = ''
await retry(async () => {
await browser.loadPage(next.url + '/fr/ca/conditional-on-another-cache')
frRandom = await browser.elementById('random').text()
await browser.loadPage(next.url + '/fr/ca/conditional-on-another-cache')
expect(await browser.elementById('random').text()).toBe(frRandom)
})
// Different root params must now produce different entries because
// lang is being read.
await browser.loadPage(next.url + '/en/us/conditional-on-another-cache')
expect(await browser.elementById('lang-value').text()).toBe('en')
const enRandom = await browser.elementById('random').text()
expect(enRandom).not.toBe(frRandom)
// Revisit fr/ca to confirm cache hit.
await browser.loadPage(next.url + '/fr/ca/conditional-on-another-cache')
expect(await browser.elementById('random').text()).toBe(frRandom)
})
it('should handle root param reads conditional on another root param value', async () => {
// Visit en/us first — reads both lang and countryCode.
const browser = await next.browser('/en/us/conditional-on-root-param')
expect(await browser.elementById('lang-value').text()).toBe('en')
expect(await browser.elementById('country-code-value').text()).toBe('us')
const enUsRandom = await browser.elementById('random').text()
// Visit en/gb — also reads both. Must produce a different entry because
// countryCode differs.
await browser.loadPage(next.url + '/en/gb/conditional-on-root-param')
expect(await browser.elementById('lang-value').text()).toBe('en')
expect(await browser.elementById('country-code-value').text()).toBe('gb')
const enGbRandom = await browser.elementById('random').text()
expect(enGbRandom).not.toBe(enUsRandom)
// Visit fr/ca — only reads lang (not countryCode), but
// knownRootParamsByFunctionId already includes countryCode from the en
// visits. The key is more specific than needed, which is safe.
await browser.loadPage(next.url + '/fr/ca/conditional-on-root-param')
expect(await browser.elementById('lang-value').text()).toBe('fr')
expect(await browser.elementById('country-code-value').text()).toBe(
'null'
)
const frCaRandom = await browser.elementById('random').text()
expect(frCaRandom).not.toBe(enUsRandom)
expect(frCaRandom).not.toBe(enGbRandom)
// Revisit all three to confirm cache hits.
await browser.loadPage(next.url + '/en/us/conditional-on-root-param')
expect(await browser.elementById('random').text()).toBe(enUsRandom)
await browser.loadPage(next.url + '/en/gb/conditional-on-root-param')
expect(await browser.elementById('random').text()).toBe(enGbRandom)
await browser.loadPage(next.url + '/fr/ca/conditional-on-root-param')
expect(await browser.elementById('random').text()).toBe(frCaRandom)
})
if (!isNextDeploy) {
it('should error when using root params within `unstable_cache` - start', async () => {
await next.render$('/en/us/unstable_cache')
expect(next.cliOutput).toInclude(
'Error: Route /[lang]/[locale]/unstable_cache used `import(\'next/root-params\').lang()` inside `"use cache"` or `unstable_cache`'
"Error: Route /[lang]/[countryCode]/unstable_cache used `import('next/root-params').lang()` inside `unstable_cache`"
)
})
it('should error when using root params in "use cache" nested inside unstable_cache - start', async () => {
await next.render$('/en/us/nested-in-unstable_cache')
expect(next.cliOutput).toInclude(
'Error: Route /[lang]/[countryCode]/nested-in-unstable_cache used `import(\'next/root-params\').lang()` inside `"use cache"` nested within `unstable_cache`. Root params are not available in this context.'
)
})
}
}
})
describe('app-root-param-getters - private cache', () => {
......@@ -88,22 +270,18 @@ describe('app-root-param-getters - private cache', () => {
describe('app-root-param-getters - cache - at build', () => {
const { next, isNextDev } = nextTestSetup({
files: join(__dirname, 'fixtures', 'use-cache-build'),
skipStart: true,
})
if (isNextDev) {
// we omit these tests in dev because they are duplicates semantically to the runtime fixture tested above
it('noop in dev', () => {})
} else {
it('should error when building a project that uses root params within `"use cache"`', async () => {
try {
await next.start()
} catch {
// we expect the build to fail
}
expect(next.cliOutput).toInclude(
'Error: Route /[lang]/[locale]/use-cache used `import(\'next/root-params\').lang()` inside `"use cache"` or `unstable_cache`'
)
it('should allow using root params within a "use cache" at build time', async () => {
const browser = await next.browser('/en/us/use-cache')
expect(await browser.elementById('param').text()).toBe('en us')
await browser.loadPage(next.url + '/es/es/use-cache')
expect(await browser.elementById('param').text()).toBe('es es')
})
}
})
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