Unverified Commit e9180eae authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

errors: shorten "use cache" messages and unify them into one factory (#94300)

### What?

Centralizes related <code>"use cache"</code> scope errors and rewrites
them as shorter, actionable messages with consistent <code>Learn
more:</code> links. It also updates the reachable revalidation errors
for rendering and <code>generateStaticParams</code>.

### Why?

The previous messages were long, inconsistent, and sometimes missing
documentation links. Some new cache-specific revalidation messages were
also hidden by an earlier render-phase error. The new messages name the
constraint, give the immediate fix, and link to the relevant
documentation.

### How?

Adds centralized error factories and dedicated error pages for request
data, cache configuration, private-cache composition, and revalidation.
When an active App Router route is available, the messages include it.
The error pages use consistent terminology and complete examples. The
<code>unstable_cache()</code> reference now documents the
request-dependent operations that these errors reject.

### Before and after

Route-based examples use <code>/products</code>. Bracketed values are
alternatives in matching order. For example, <code>[E1482, E1486,
E1489]</code> maps to <code>[headers(), cookies(), request.url]</code>.
Each runtime error contains one alternative, but the table groups
messages with the same template.

#### Messages that include the route

| Cases | Before | After |
| --- | --- | --- |
| E1480 · <code>searchParams</code> in <code>"use cache"</code> | Route
/products used <code>searchParams</code> inside "use cache". Accessing
dynamic request data inside a cache scope is not supported. If you need
some search params inside a cached function await
<code>searchParams</code> outside of the cached function and pass only
the required search params as arguments to the cached function. See more
info here: https://nextjs.org/docs/messages/next-request-in-use-cache |
Route "/products": <code>searchParams</code> can't be read inside
<code>"use cache"</code>. Await it outside the cached function and pass
what you need as an argument.<br><br>Learn more:
https://nextjs.org/docs/messages/next-request-in-use-cache |
| [E1482, E1486, E1489] · [<code>headers()</code>,
<code>cookies()</code>, <code>request.url</code>] in <code>"use
cache"</code> | Route /products used [<code>headers()</code>,
<code>cookies()</code>, <code>request.url</code>] inside "use cache".
Accessing Dynamic data sources inside a cache scope is not supported. If
you need this data inside a cached function use [<code>headers()</code>,
<code>cookies()</code>, <code>request.url</code>] 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 "/products": [<code>headers()</code>, <code>cookies()</code>,
<code>request.url</code>] can't be read inside <code>"use cache"</code>.
Read it outside the cached function and pass what you need as an
argument.<br><br>Learn more:
https://nextjs.org/docs/messages/next-request-in-use-cache |
| [E1481, E1485, E1492] · [<code>cookies()</code>,
<code>request.url</code>, <code>headers()</code>] in
<code>unstable_cache()</code> | Route /products used
[<code>cookies()</code>, <code>request.url</code>,
<code>headers()</code>] inside a function cached with
<code>unstable_cache()</code>. Accessing Dynamic data sources inside a
cache scope is not supported. If you need this data inside a cached
function use [<code>cookies()</code>, <code>request.url</code>,
<code>headers()</code>] 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 "/products": [<code>cookies()</code>, <code>request.url</code>,
<code>headers()</code>] can't be read inside
<code>unstable_cache()</code>. Read it outside the cached function and
pass what you need as an argument.<br><br>Learn more:
https://nextjs.org/docs/app/api-reference/functions/unstable_cache |
| [E1484, E1491] · <code>draftMode().enable()</code> in
[<code>unstable_cache()</code>, <code>"use cache"</code>] | Route
/products used "draftMode().enable()" inside [a function cached with
<code>unstable_cache()</code>, "use cache"]. The enabled status of
<code>draftMode()</code> can be read in caches but you must not enable
or disable <code>draftMode()</code> inside a cache. See more info here:
[https://nextjs.org/docs/app/api-reference/functions/unstable_cache,
https://nextjs.org/docs/messages/next-request-in-use-cache] | Route
"/products": <code>draftMode().enable()</code> can't be called inside
[<code>unstable_cache()</code>, <code>"use cache"</code>]. Draft mode
can be read inside a cached function, but enabling or disabling it must
happen outside.<br><br>Learn more:
[https://nextjs.org/docs/app/api-reference/functions/unstable_cache,
https://nextjs.org/docs/messages/next-request-in-use-cache] |
| [E1488, E1499] · <code>connection()</code> in
[<code>unstable_cache()</code>, <code>"use cache"</code>] | Route
/products used <code>connection()</code> inside [a function cached with
<code>unstable_cache()</code>, "use cache"]. The
<code>connection()</code> 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,
https://nextjs.org/docs/messages/next-request-in-use-cache] | Route
"/products": <code>connection()</code> can't be called inside
[<code>unstable_cache()</code>, <code>"use cache"</code>] because cached
functions may run during prerendering, without an incoming request. Call
it outside the cached function.<br><br>Learn more:
[https://nextjs.org/docs/app/api-reference/functions/unstable_cache,
https://nextjs.org/docs/messages/next-request-in-use-cache] |
| E1494 · <code>connection()</code> in <code>"use cache: private"</code>
| Route /products used <code>connection()</code> inside "use cache:
private". The <code>connection()</code> 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 | Route
"/products": <code>connection()</code> can't be called inside <code>"use
cache: private"</code> because private cached functions may run during
prefetching, without a navigation request. Call it outside the cached
function.<br><br>Learn more:
https://nextjs.org/docs/app/api-reference/directives/use-cache-private |
| [E1483, E1495] · <code>revalidateTag("products")</code> in [<code>"use
cache"</code>, <code>unstable_cache()</code>] | Route /products used
"revalidateTag products" inside [a "use cache", a function cached with
"unstable_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 "/products": <code>revalidateTag("products")</code> can't be
called during render, inside a cached function, or inside
<code>generateStaticParams</code>. Call it from a Server Action or Route
Handler instead.<br><br>Learn more:
https://nextjs.org/docs/messages/revalidate-in-use-cache |
| During render | Route /products used "revalidateTag products" during
render 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 "/products": <code>revalidateTag("products")</code> can't be
called during render, inside a cached function, or inside
<code>generateStaticParams</code>. Call it from a Server Action or Route
Handler instead.<br><br>Learn more:
https://nextjs.org/docs/messages/revalidate-in-use-cache |
| Inside <code>generateStaticParams</code> | Route /products used
"revalidateTag products" inside <code>generateStaticParams</code> 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 "/products": <code>revalidateTag("products")</code> can't be
called inside <code>generateStaticParams</code>. Call it from a Server
Action or Route Handler instead.<br><br>Learn more:
https://nextjs.org/docs/messages/revalidate-in-use-cache |

#### Other messages

| Cases | Before | After |
| --- | --- | --- |
| [E1477, E1490] · Nested cache with [short <code>expire</code>,
<code>revalidate: 0</code>] | A "use cache" with [short
<code>expire</code> (under 5 minutes), zero <code>revalidate</code>] is
nested inside another "use cache" that has no explicit
<code>cacheLife</code>, which is not allowed during prerendering. Add
<code>cacheLife()</code> to the outer "use cache" to choose whether it
should be prerendered [with longer <code>expire</code>, with non-zero
<code>revalidate</code>] or remain dynamic [with short
<code>expire</code>, with zero <code>revalidate</code>]. Read more:
https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife
| Route <code>"/products"</code>: A nested <code>"use cache"</code> with
[a short <code>expire</code> (under 5 minutes), <code>revalidate:
0</code>] is inside an outer <code>"use cache"</code> that has no
<code>cacheLife()</code>. Add <code>cacheLife()</code> to the outer one
to choose whether to prerender it [with a longer <code>expire</code>,
with a non-zero <code>revalidate</code>] or keep it dynamic [with a
short <code>expire</code>, with <code>revalidate:
0</code>].<br><br>Learn more:
https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife
|
| E1478 · External promise | Filling a "use cache" entry appears to be
stuck on shared state from the outer render scope. The same function
completed when run in isolation, which usually means a module-scoped
value (for example a top-level Map used to dedupe fetches) is joining a
promise created outside the cache. "use cache" already dedupes calls
with the same arguments within a request and across requests on the same
server instance, so the surrounding dedupe layer is both unnecessary and
the likely cause. Remove it and rely on "use cache" alone for
deduping.<br><br><em>No documentation link.</em> | Route
<code>"/products"</code>: A <code>"use cache"</code> function is
awaiting a promise created outside it. The same call completed when run
in isolation, so a module-scoped value (often a top-level
<code>Map</code> used to dedupe fetches) is most likely blocking it.
<code>"use cache"</code> already dedupes calls with the same arguments.
Remove the surrounding dedupe layer.<br><br>Learn more:
https://nextjs.org/docs/messages/next-request-in-use-cache |
| [E1479, E1498] · [<code>cacheTag()</code>, <code>cacheLife()</code>]
outside a cached function | [<code>cacheTag()</code>,
<code>cacheLife()</code>] can only be called inside a "use cache"
function.<br><br><em>No documentation link.</em> | Route
<code>"/products"</code>: [<code>cacheTag()</code>,
<code>cacheLife()</code>] can only be called inside a <code>"use
cache"</code> or <code>"use cache: private"</code>
function.<br><br>Learn more:
[https://nextjs.org/docs/messages/cache-tag-outside-use-cache,
https://nextjs.org/docs/messages/cache-life-outside-use-cache]<br><br>Outside
an App Router route, the same message is shown without the route prefix.
|
| E1487 · Prerender timeout | Filling a cache during prerender timed
out, likely because request-specific arguments such as params,
searchParams, cookies() or dynamic data were used inside "use
cache".<br><br><em>No documentation link.</em> | Route
<code>"/products"</code>: A <code>"use cache"</code> function took too
long during prerendering. The most common cause is passing unresolved
request-specific arguments, such as <code>params</code> or
<code>searchParams</code>, into the cached function. Resolve the data
before calling the function and pass only the values you
need.<br><br>Learn more:
https://nextjs.org/docs/messages/next-request-in-use-cache |
| E1493 · Private cache inside a public cache | "use cache: private"
must not be used within "use cache". It can only be nested inside of
another "use cache: private".<br><br><em>No documentation link.</em> |
Route <code>"/products"</code>: <code>"use cache: private"</code> can't
be nested inside <code>"use cache"</code> because a shared cached
function can't depend on private request data. Nest it only inside
another <code>"use cache: private"</code>.<br><br>Learn more:
https://nextjs.org/docs/messages/use-cache-private-composition |
| E1496 · Private cache without a request | "use cache: private" cannot
be used outside of a request context.<br><br><em>No documentation
link.</em> | Route <code>"/products"</code>: <code>"use cache:
private"</code> needs an active request, so it can't be used during
<code>generateStaticParams</code> or other build-time contexts. Move it
to a request-time component or function.<br><br>Learn more:
https://nextjs.org/docs/messages/use-cache-private-composition |
| E1497 · Private cache inside <code>unstable_cache()</code> | "use
cache: private" must not be used within
<code>unstable_cache()</code>.<br><br><em>No documentation link.</em> |
Route <code>"/products"</code>: <code>"use cache: private"</code> can't
be used inside <code>unstable_cache()</code> because
<code>unstable_cache()</code> uses a shared cache that can't contain
private request data. Call the private cached function outside
<code>unstable_cache()</code>.<br><br>Learn more:
https://nextjs.org/docs/messages/use-cache-private-composition |

### Runtime verification

- Exercised the 13 route-based message IDs through minimal dev-runtime
reproductions. Twelve reached the new factories from userland, with
byte-identical output across three requests each.
- The `request.url` error for `"use cache"` Route Handlers is currently
limited to the prerender path. A dynamic request captured by a cached
closure can bypass that tracking; this is existing framework behavior to
follow up separately.
- Passing the `searchParams` promise into a nested cached function can
still surface the earlier synchronous dynamic-API error before this
factory. The new message is verified when the cache scope reads its own
`searchParams` value.
- A follow-up preview verification triggered 17 of the 19 rewritten
messages from userland with byte-identical output. The timeout-driven
external-promise and prerender-timeout messages were verified in source
and through their focused test coverage.

### Verification

- <code>CI=1 pnpm build-all</code>
- <code>pnpm --filter=next types</code>
- <code>pnpm --filter=next build</code>
- <code>HEADLESS=true pnpm test-dev-turbo
test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts</code>
- <code>HEADLESS=true pnpm test-start-turbo
test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts</code>
- <code>NEXT_SKIP_ISOLATE=1 HEADLESS=true pnpm test-dev-webpack
test/e2e/app-dir/cache-components-errors/use-cache.test.ts -t 'cacheLife
with (expire &lt; 5 minutes|revalidate: 0)'</code> (6 tests and 6
snapshots passed)
- <code>pnpm test-dev
test/e2e/app-dir/cache-components-errors/use-cache.test.ts --projects
jest.config.*</code> (42 tests and 42 snapshots passed across Turbopack
and webpack)
- <code>pnpm test-dev
test/e2e/app-dir/use-cache-hanging/use-cache-hanging.test.ts --projects
jest.config.*</code> (10 tests and 8 snapshots passed across Turbopack
and webpack)
- <code>pnpm test-dev
test/e2e/app-dir/use-cache-configured-timeout/use-cache-configured-timeout.test.ts
--projects jest.config.*</code> (4 tests and 2 snapshots passed across
Turbopack and webpack)
- Prettier, ESLint, and Alex on the changed source, tests, and error
pages

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarClaude Opus 4.8 (1M context) <noreply@anthropic.com>
parent d434afa8
......@@ -26,9 +26,22 @@ export default async function Component({ userID }) {
> **Good to know**:
>
> - Accessing uncached data sources such as `headers` or `cookies` 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 uncached data in as an argument.
> - Accessing request data such as `headers` or `cookies` inside a cache scope is not supported. Read the data outside the cached function and pass the values you need as arguments.
> - This API uses Next.js' built-in cache to persist the result across requests and deployments. See [Caching and Revalidating](/docs/app/getting-started/caching).
## Unsupported operations
The function passed to `unstable_cache` cannot depend on the incoming request. Read values from `cookies()` or `headers()` before calling the cached function, then pass those values as arguments so they become part of the cache key.
The cached function also cannot:
- Call `connection()`, which requires an incoming request
- Enable or disable draft mode
- Call `revalidateTag()`, `updateTag()`, or `revalidatePath()` during cache execution
- Call a function that uses the `use cache: private` directive
Perform request-dependent work before calling the cached function. Perform mutations and revalidation afterward from a Server Action or Route Handler.
## Parameters
```jsx
......
---
title: Cannot call `cacheLife()` outside `use cache`
---
## Why This Error Occurred
The `cacheLife()` function configures the `stale`, `revalidate`, and `expire` times for a cache entry. Call it from a function or component that uses the `use cache` or `use cache: private` directive. When you call `cacheLife()` outside a cached function, there is no cache entry to configure.
```jsx filename="app/page.js" highlight={4}
import { cacheLife } from 'next/cache'
export default async function Page() {
cacheLife('hours') // No cache entry to configure
return <p>...</p>
}
```
## Possible Ways to Fix It
Move `cacheLife()` inside the cached function whose lifetime you want to set.
```jsx filename="app/page.js" highlight={5}
import { cacheLife } from 'next/cache'
async function getProducts() {
'use cache'
cacheLife('hours') // Configures this cache entry
return db.products.findMany()
}
export default async function Page() {
const products = await getProducts()
return <p>...</p>
}
```
If you don't intend to cache the function or component, remove the `cacheLife()` call.
## Useful Links
- [`cacheLife()` function](/docs/app/api-reference/functions/cacheLife)
- [`cacheTag()` function](/docs/app/api-reference/functions/cacheTag)
- [`use cache` directive](/docs/app/api-reference/directives/use-cache)
- [`use cache: private` directive](/docs/app/api-reference/directives/use-cache-private)
---
title: Cannot call `cacheTag()` outside `use cache`
---
## Why This Error Occurred
The `cacheTag()` function attaches one or more tags to a cache entry so you can later revalidate it with `revalidateTag()`. Call it from a function or component that uses the `use cache` or `use cache: private` directive. When you call `cacheTag()` outside a cached function, there is no cache entry to tag.
```jsx filename="app/page.js" highlight={4}
import { cacheTag } from 'next/cache'
export default async function Page() {
cacheTag('products') // No cache entry to tag
return <p>...</p>
}
```
## Possible Ways to Fix It
Move `cacheTag()` inside the cached function whose entry you want to tag.
```jsx filename="app/page.js" highlight={5}
import { cacheTag } from 'next/cache'
async function getProducts() {
'use cache'
cacheTag('products') // Tags this cache entry
return db.products.findMany()
}
export default async function Page() {
const products = await getProducts()
return <p>...</p>
}
```
If you don't intend to cache the function or component, remove the `cacheTag()` call. To revalidate the tag later, call [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) from a Server Action or Route Handler.
## Useful Links
- [`cacheTag()` function](/docs/app/api-reference/functions/cacheTag)
- [`cacheLife()` function](/docs/app/api-reference/functions/cacheLife)
- [`use cache` directive](/docs/app/api-reference/directives/use-cache)
- [`use cache: private` directive](/docs/app/api-reference/directives/use-cache-private)
- [`revalidateTag()` function](/docs/app/api-reference/functions/revalidateTag)
---
title: Cannot access `cookies()` or `headers()` in `"use cache"`
title: Cannot access request data in `use cache`
---
## Why This Error Occurred
A function is trying to read from the current incoming request inside the scope of a function annotated with `"use cache"`. This is not supported because it would make the cache invalidated by every request which is probably not what you intended.
A cached function tried to access the incoming request. APIs such as `cookies()`, `headers()`, `searchParams`, and `connection()` depend on the request and cannot be called inside a function that uses the `use cache` directive. This error can also occur when you pass unresolved request data into a cached function during prerendering. You can read draft mode inside a cached function, but enable or disable it outside.
A cached function can also stall if it awaits a promise stored outside the function, such as one kept in a module-scoped `Map` for deduplication.
## Possible Ways to Fix It
Instead of calling this inside the `"use cache"` function, move it outside the function and pass the value in as an argument. The specific value will now be part of the cache key through its arguments.
Read and resolve request data outside the cached function, then pass only the values you need as arguments. Call `connection()` and enable or disable draft mode outside the cached function as well.
If a module-scoped cache or deduplication layer stores promises, remove it. The `use cache` directive already deduplicates calls with the same arguments within a render pass and across requests for as long as the cache entry lasts.
Before:
```jsx filename="app/page.js" highlight={5}
import { cookies } from 'next/headers'
async function getExampleData() {
"use cache"
async function getGreeting() {
'use cache'
const isLoggedIn = (await cookies()).has('token')
...
return isLoggedIn ? 'Welcome back' : 'Welcome'
}
export default async function Page() {
const data = await getExampleData()
return ...
const greeting = await getGreeting()
return <p>{greeting}</p>
}
```
After:
```jsx filename="app/page.js" highlight={9}
```jsx filename="app/page.js" highlight={9,10}
import { cookies } from 'next/headers'
async function getExampleData(isLoggedIn) {
"use cache"
...
async function getGreeting(isLoggedIn) {
'use cache'
return isLoggedIn ? 'Welcome back' : 'Welcome'
}
export default async function Page() {
const isLoggedIn = (await cookies()).has('token')
const data = await getExampleData(isLoggedIn)
return ...
const greeting = await getGreeting(isLoggedIn)
return <p>{greeting}</p>
}
```
......@@ -48,4 +52,6 @@ export default async function Page() {
- [`headers()` function](/docs/app/api-reference/functions/headers)
- [`cookies()` function](/docs/app/api-reference/functions/cookies)
- [`connection()` function](/docs/app/api-reference/functions/connection)
- [`draftMode()` function](/docs/app/api-reference/functions/draft-mode)
- [`use cache` directive](/docs/app/api-reference/directives/use-cache)
---
title: Cannot revalidate during render, inside a cached function, or in `generateStaticParams`
---
## Why This Error Occurred
The `revalidateTag()` and `revalidatePath()` functions invalidate cached data. To keep cache state consistent, call them from a Server Action or Route Handler. Next.js throws this error when you call either function during rendering, from a cached function, or from `generateStaticParams`.
```jsx filename="app/products/page.js" highlight={5}
import { revalidateTag } from 'next/cache'
export default async function Page() {
const products = await db.products.findMany()
revalidateTag('products', 'max') // Cannot revalidate during render
return <p>{products.length} products</p>
}
```
## Possible Ways to Fix It
Call `revalidateTag()` or `revalidatePath()` from the Server Action or Route Handler itself. Do not call either function during rendering or from a function that uses the `use cache` directive or `unstable_cache()`.
```jsx filename="app/actions.js" highlight={6}
'use server'
import { revalidateTag } from 'next/cache'
export async function saveProduct(data) {
await db.products.create(data)
revalidateTag('products', 'max') // Runs outside any cached function
}
```
To tag the cache entry that this revalidates, call [`cacheTag()`](/docs/app/api-reference/functions/cacheTag) inside the function that uses the `use cache` directive to read the data.
## Useful Links
- [`revalidateTag()` function](/docs/app/api-reference/functions/revalidateTag)
- [`revalidatePath()` function](/docs/app/api-reference/functions/revalidatePath)
- [Revalidating data](/docs/app/getting-started/revalidating)
- [`use cache` directive](/docs/app/api-reference/directives/use-cache)
---
title: 'Invalid `use cache: private` composition'
---
## Why This Error Occurred
The `use cache: private` directive lets a cached function access request-specific data. Next.js stores its results only in the browser's memory. Private cached functions cannot run inside shared caches or without an active request. This error occurs when a private cached function is:
- **Nested inside a public `use cache` directive.** A shared cached function can reuse its result across users, so it cannot contain a private cached function. Nest a private cached function only inside another private cached function.
- **Used inside `unstable_cache()`.** `unstable_cache()` is a shared cache and has the same restriction.
- **Used without an active request.** A private cached function depends on the current request, so it cannot run during build-time contexts such as `generateStaticParams`.
```jsx filename="app/page.js" highlight={2,7}
async function PrivateSegment() {
'use cache: private'
return <p>Private</p>
}
export default async function Page() {
'use cache' // A public cache cannot contain a private one
return <PrivateSegment />
}
```
## Possible Ways to Fix It
Nest a private cached function only inside another private cached function. You can also call it directly from a component or function that runs during a request. Do not place it inside a public cached function, `unstable_cache()`, or a build-time context.
```jsx filename="app/page.js" highlight={7}
async function PrivateSegment() {
'use cache: private'
return <p>Private</p>
}
export default async function Page() {
// No surrounding "use cache". The private segment runs per request.
return <PrivateSegment />
}
```
If the data is the same for every user, use the `use cache` directive so Next.js can prerender and reuse the result. If you need per-user data, read it during the request instead of in `generateStaticParams`.
## Useful Links
- [`use cache: private` directive](/docs/app/api-reference/directives/use-cache-private)
- [`use cache` directive](/docs/app/api-reference/directives/use-cache)
......@@ -16,6 +16,11 @@ import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { RenderStage } from '../app-render/staged-rendering'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
createConnectionInPublicUseCacheError,
createConnectionInPrivateUseCacheError,
createConnectionInUnstableCacheError,
} from '../use-cache/use-cache-messages'
/**
* This function allows you to indicate that you require an actual user Request before continuing.
......@@ -49,9 +54,7 @@ export function connection(): Promise<void> {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache': {
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`
)
const error = createConnectionInPublicUseCacheError(workStore.route)
Error.captureStackTrace(error, connection)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
......@@ -61,18 +64,14 @@ export function connection(): Promise<void> {
// It might not be intuitive to throw for private caches as well, but
// we don't consider runtime 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`
)
const error = createConnectionInPrivateUseCacheError(workStore.route)
Error.captureStackTrace(error, connection)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache':
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`
)
throw createConnectionInUnstableCacheError(workStore.route)
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`connection()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
......
......@@ -28,6 +28,10 @@ import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-b
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
createCookiesInUseCacheError,
createCookiesInUnstableCacheError,
} from '../use-cache/use-cache-messages'
export function cookies(): Promise<ReadonlyRequestCookies> {
const callingExpression = 'cookies'
......@@ -57,17 +61,13 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache':
const error = new Error(
`Route ${workStore.route} used \`cookies()\` inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`cookies()\` 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`
)
const error = createCookiesInUseCacheError(workStore.route)
Error.captureStackTrace(error, cookies)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
case 'unstable-cache':
throw new Error(
`Route ${workStore.route} used \`cookies()\` 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 \`cookies()\` 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`
)
throw createCookiesInUnstableCacheError(workStore.route)
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`cookies()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
......
......@@ -18,6 +18,10 @@ import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-b
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { DynamicServerError } from '../../client/components/hooks-server-context'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
createDraftModeMutationInUseCacheError,
createDraftModeMutationInUnstableCacheError,
} from '../use-cache/use-cache-messages'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
applyOwnerStack,
......@@ -210,8 +214,9 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
switch (workUnitStore.type) {
case 'cache':
case 'private-cache': {
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`
const error = createDraftModeMutationInUseCacheError(
workStore.route,
expression
)
Error.captureStackTrace(error, constructorOpt)
applyOwnerStack(error)
......@@ -219,8 +224,9 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
throw error
}
case 'unstable-cache':
throw new Error(
`Route ${workStore.route} used "${expression}" inside a function cached with \`unstable_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/app/api-reference/functions/unstable_cache`
throw createDraftModeMutationInUnstableCacheError(
workStore.route,
expression
)
case 'prerender':
......
......@@ -26,6 +26,10 @@ import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-b
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
createHeadersInUseCacheError,
createHeadersInUnstableCacheError,
} from '../use-cache/use-cache-messages'
/**
* This function allows you to read the HTTP incoming request headers in
......@@ -58,18 +62,14 @@ export function headers(): Promise<ReadonlyHeaders> {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache': {
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`
)
const error = createHeadersInUseCacheError(workStore.route)
Error.captureStackTrace(error, headers)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache':
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`
)
throw createHeadersInUnstableCacheError(workStore.route)
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`headers()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
......
......@@ -2,6 +2,7 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import { actionAsyncStorage } from '../app-render/action-async-storage.external'
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external'
import { createSearchParamsInUseCacheError } from '../use-cache/use-cache-messages'
import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
export function throwWithStaticGenerationBailoutErrorWithDynamicError(
......@@ -17,9 +18,7 @@ export function throwForSearchParamsAccessInUseCache(
workStore: WorkStore,
constructorOpt: Function
): never {
const error = new Error(
`Route ${workStore.route} used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
const error = createSearchParamsInUseCacheError(workStore.route)
Error.captureStackTrace(error, constructorOpt)
workStore.invalidDynamicUsageError ??= error
......
......@@ -92,6 +92,10 @@ import { trackPendingModules } from '../../app-render/module-loading/track-modul
import { InvariantError } from '../../../shared/lib/invariant-error'
import { LazyModule } from '../../lib/lazy-module'
import { createPrerenderResumeDataCache } from '../../resume-data-cache/resume-data-cache'
import {
createRouteHandlerRequestInUseCacheError,
createRouteHandlerRequestInUnstableCacheError,
} from '../../use-cache/use-cache-messages'
export class WrappedNextRouterError {
constructor(
......@@ -1462,12 +1466,11 @@ function trackDynamic(
case 'private-cache':
// TODO: Should we allow reading cookies and search params from the
// request for private caches in route handlers?
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`
)
throw createRouteHandlerRequestInUseCacheError(store.route, expression)
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" 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 "${expression}" 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`
throw createRouteHandlerRequestInUnstableCacheError(
store.route,
expression
)
case 'prerender':
const error = new Error(
......
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { createCacheLifeOutsideUseCacheError } from './use-cache-messages'
import { validateAndNormalizeCacheLifeProfile } from './cache-life-profile'
import type { CacheLife } from './cache-life-profile'
......@@ -42,8 +43,8 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
case 'unstable-cache':
case 'generate-static-params':
case undefined:
throw new Error(
'`cacheLife()` can only be called inside a "use cache" function.'
throw createCacheLifeOutsideUseCacheError(
workAsyncStorage.getStore()?.route
)
case 'cache':
case 'private-cache':
......
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { validateTags } from '../lib/patch-fetch'
import { createCacheTagOutsideUseCacheError } from './use-cache-messages'
export function cacheTag(...tags: string[]): void {
if (!process.env.__NEXT_USE_CACHE) {
......@@ -20,8 +22,8 @@ export function cacheTag(...tags: string[]): void {
case 'unstable-cache':
case 'generate-static-params':
case undefined:
throw new Error(
'`cacheTag()` can only be called inside a "use cache" function.'
throw createCacheTagOutsideUseCacheError(
workAsyncStorage.getStore()?.route
)
case 'cache':
case 'private-cache':
......
export class UseCacheTimeoutError extends Error {
constructor() {
constructor(route: string) {
super(
'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".'
`Route "${route}": ` +
`A \`"use cache"\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \`params\` or \`searchParams\`, into the cached function. Resolve the data before calling the function and pass only the values you need.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
}
}
export class UseCacheDeadlockError extends Error {
constructor() {
constructor(route: string) {
super(
'Filling a "use cache" entry appears to be stuck on shared state from the outer render scope. The same function completed when run in isolation, which usually means a module-scoped value (for example a top-level Map used to dedupe fetches) is joining a promise created outside the cache. "use cache" already dedupes calls with the same arguments — within a request and across requests on the same server instance — so the surrounding dedupe layer is both unnecessary and the likely cause. Remove it and rely on "use cache" alone for deduping.'
`Route "${route}": ` +
`A \`"use cache"\` function is awaiting a promise created outside it. The same call completed when run in isolation, so a module-scoped value (often a top-level \`Map\` used to dedupe fetches) is most likely blocking it. \`"use cache"\` already dedupes calls with the same arguments. Remove the surrounding dedupe layer.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
}
}
......
/**
* Centralized error factories for cached function and revalidation misuse.
* State the scope and constraint, explain non-obvious boundaries, give the
* immediate fix, then link to the relevant docs.
*/
const NEXT_REQUEST_IN_USE_CACHE =
'https://nextjs.org/docs/messages/next-request-in-use-cache'
const UNSTABLE_CACHE_API_DOCS =
'https://nextjs.org/docs/app/api-reference/functions/unstable_cache'
const USE_CACHE_PRIVATE_API_DOCS =
'https://nextjs.org/docs/app/api-reference/directives/use-cache-private'
const CACHE_TAG_OUTSIDE_USE_CACHE =
'https://nextjs.org/docs/messages/cache-tag-outside-use-cache'
const CACHE_LIFE_OUTSIDE_USE_CACHE =
'https://nextjs.org/docs/messages/cache-life-outside-use-cache'
const USE_CACHE_PRIVATE_COMPOSITION =
'https://nextjs.org/docs/messages/use-cache-private-composition'
const REVALIDATE_IN_USE_CACHE =
'https://nextjs.org/docs/messages/revalidate-in-use-cache'
const NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE =
'https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife'
// Request data accessed in caches
export function createCookiesInUseCacheError(route: string): Error {
return new Error(
`Route "${route}": \`cookies()\` can't be read inside \`"use cache"\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`
)
}
export function createCookiesInUnstableCacheError(route: string): Error {
return new Error(
`Route "${route}": \`cookies()\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`
)
}
export function createHeadersInUseCacheError(route: string): Error {
return new Error(
`Route "${route}": \`headers()\` can't be read inside \`"use cache"\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`
)
}
export function createHeadersInUnstableCacheError(route: string): Error {
return new Error(
`Route "${route}": \`headers()\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`
)
}
export function createSearchParamsInUseCacheError(route: string): Error {
return new Error(
`Route "${route}": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`
)
}
export function createConnectionInPublicUseCacheError(route: string): Error {
return new Error(
`Route "${route}": \`connection()\` can't be called inside \`"use cache"\` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`
)
}
export function createConnectionInPrivateUseCacheError(route: string): Error {
return new Error(
`Route "${route}": \`connection()\` can't be called inside \`"use cache: private"\` because private cached functions may run during prefetching, without a navigation request. Call it outside the cached function.\nLearn more: ${USE_CACHE_PRIVATE_API_DOCS}`
)
}
export function createConnectionInUnstableCacheError(route: string): Error {
return new Error(
`Route "${route}": \`connection()\` can't be called inside \`unstable_cache()\` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`
)
}
export function createRouteHandlerRequestInUseCacheError(
route: string,
expression: string
): Error {
return new Error(
`Route "${route}": \`${expression}\` can't be read inside \`"use cache"\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`
)
}
export function createRouteHandlerRequestInUnstableCacheError(
route: string,
expression: string
): Error {
return new Error(
`Route "${route}": \`${expression}\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`
)
}
// Mutations inside caches and render
/**
* Used when `draftMode().enable()` or `.disable()` is called inside
* `"use cache"` or `"use cache: private"`. Reading `draftMode()` is fine
* inside a cached function, but toggling it is not.
*/
export function createDraftModeMutationInUseCacheError(
route: string,
expression: string
): Error {
return new Error(
`Route "${route}": \`${expression}\` can't be called inside \`"use cache"\`. Draft mode can be read inside a cached function, but enabling or disabling it must happen outside.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`
)
}
export function createDraftModeMutationInUnstableCacheError(
route: string,
expression: string
): Error {
return new Error(
`Route "${route}": \`${expression}\` can't be called inside \`unstable_cache()\`. Draft mode can be read inside a cached function, but enabling or disabling it must happen outside.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`
)
}
export function createRevalidateDuringRenderError(
route: string,
expression: string
): Error {
return new Error(
`Route "${route}": \`${expression}\` can't be called during render, inside a cached function, or inside \`generateStaticParams\`. Call it from a Server Action or Route Handler instead.\nLearn more: ${REVALIDATE_IN_USE_CACHE}`
)
}
// Cache configuration and nesting
function routePrefix(route: string | undefined): string {
return route === undefined ? '' : `Route "${route}": `
}
export function createCacheTagOutsideUseCacheError(
route: string | undefined
): Error {
return new Error(
`${routePrefix(route)}\`cacheTag()\` can only be called inside a \`"use cache"\` or \`"use cache: private"\` function.\nLearn more: ${CACHE_TAG_OUTSIDE_USE_CACHE}`
)
}
export function createCacheLifeOutsideUseCacheError(
route: string | undefined
): Error {
return new Error(
`${routePrefix(route)}\`cacheLife()\` can only be called inside a \`"use cache"\` or \`"use cache: private"\` function.\nLearn more: ${CACHE_LIFE_OUTSIDE_USE_CACHE}`
)
}
export function createNestedCacheZeroRevalidateError(
route: string,
cause: Error | undefined
): Error {
return new Error(
`Route "${route}": A nested \`"use cache"\` with \`revalidate: 0\` is inside an outer \`"use cache"\` that has no \`cacheLife()\`. Add \`cacheLife()\` to the outer one to choose whether to prerender it with a non-zero \`revalidate\` or keep it dynamic with \`revalidate: 0\`.\nLearn more: ${NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE}`,
{ cause }
)
}
export function createNestedCacheShortExpireError(
route: string,
cause: Error | undefined
): Error {
return new Error(
`Route "${route}": A nested \`"use cache"\` with a short \`expire\` (under 5 minutes) is inside an outer \`"use cache"\` that has no \`cacheLife()\`. Add \`cacheLife()\` to the outer one to choose whether to prerender it with a longer \`expire\` or keep it dynamic with a short \`expire\`.\nLearn more: ${NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE}`,
{ cause }
)
}
// Private cache composition and request context
export function createUseCachePrivateInsidePublicUseCacheError(
route: string
): Error {
return new Error(
`Route "${route}": \`"use cache: private"\` can't be nested inside \`"use cache"\` because a shared cached function can't depend on private request data. Nest it only inside another \`"use cache: private"\`.\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`
)
}
export function createUseCachePrivateInsideUnstableCacheError(
route: string
): Error {
return new Error(
`Route "${route}": \`"use cache: private"\` can't be used inside \`unstable_cache()\` because \`unstable_cache()\` uses a shared cache that can't contain private request data. Call the private cached function outside \`unstable_cache()\`.\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`
)
}
export function createUseCachePrivateOutsideRequestContextError(
route: string
): Error {
return new Error(
`Route "${route}": \`"use cache: private"\` needs an active request, so it can't be used during \`generateStaticParams\` or other build-time contexts. Move it to a request-time component or function.\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`
)
}
......@@ -94,6 +94,13 @@ import {
UseCacheDeadlockError,
UseCacheTimeoutError,
} from './use-cache-errors'
import {
createNestedCacheShortExpireError,
createNestedCacheZeroRevalidateError,
createUseCachePrivateInsidePublicUseCacheError,
createUseCachePrivateInsideUnstableCacheError,
createUseCachePrivateOutsideRequestContextError,
} from './use-cache-messages'
import {
createHangingInputAbortSignal,
throwToInterruptStaticGeneration,
......@@ -360,22 +367,6 @@ const findSourceMapURL =
.findSourceMapURLDEV
: undefined
const nestedCacheZeroRevalidateErrorMessage =
`A "use cache" with zero \`revalidate\` is nested inside another "use cache" ` +
`that has no explicit \`cacheLife\`, which is not allowed during ` +
`prerendering. Add \`cacheLife()\` to the outer "use cache" to choose ` +
`whether it should be prerendered (with non-zero \`revalidate\`) or remain ` +
`dynamic (with zero \`revalidate\`). Read more: ` +
`https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife`
const nestedCacheShortExpireErrorMessage =
`A "use cache" with short \`expire\` (under 5 minutes) is nested inside ` +
`another "use cache" that has no explicit \`cacheLife\`, which is not ` +
`allowed during prerendering. Add \`cacheLife()\` to the outer "use cache" ` +
`to choose whether it should be prerendered (with longer \`expire\`) or remain ` +
`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
......@@ -1826,7 +1817,7 @@ export async function cache(
}
}
const timeoutError = new UseCacheTimeoutError()
const timeoutError = new UseCacheTimeoutError(workStore.route)
Error.captureStackTrace(timeoutError, cache)
applyOwnerStack(timeoutError)
......@@ -1838,7 +1829,7 @@ export async function cache(
// gate lets the error class drop out of the production runtime bundle.
let deadlockError: UseCacheDeadlockError | undefined
if (process.env.__NEXT_DEV_SERVER) {
deadlockError = new UseCacheDeadlockError()
deadlockError = new UseCacheDeadlockError(workStore.route)
Error.captureStackTrace(deadlockError, cache)
applyOwnerStack(deadlockError)
}
......@@ -1885,18 +1876,12 @@ export async function cache(
)
case 'unstable-cache': {
throw wrapAsInvalidDynamicUsageError(
new Error(
// TODO: Add a link to an error documentation page when we have one.
`${expression} must not be used within \`unstable_cache()\`.`
)
createUseCachePrivateInsideUnstableCacheError(workStore.route)
)
}
case 'cache': {
throw wrapAsInvalidDynamicUsageError(
new Error(
// TODO: Add a link to an error documentation page when we have one.
`${expression} must not be used within "use cache". It can only be nested inside of another ${expression}.`
)
createUseCachePrivateInsidePublicUseCacheError(workStore.route)
)
}
case 'request':
......@@ -1913,10 +1898,7 @@ export async function cache(
break
case 'generate-static-params':
throw wrapAsInvalidDynamicUsageError(
new Error(
// TODO: Add a link to an error documentation page when we have one.
`${expression} cannot be used outside of a request context.`
)
createUseCachePrivateOutsideRequestContextError(workStore.route)
)
default:
workUnitStore satisfies never
......@@ -2415,9 +2397,10 @@ export async function cache(
shouldReportNestedCacheError
) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheZeroRevalidateErrorMessage, {
cause: rdcResult.dynamicNestedCacheError,
})
createNestedCacheZeroRevalidateError(
workStore.route,
rdcResult.dynamicNestedCacheError
)
)
}
debug?.(
......@@ -2432,9 +2415,10 @@ export async function cache(
shouldReportNestedCacheError
) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheShortExpireErrorMessage, {
cause: rdcResult.dynamicNestedCacheError,
})
createNestedCacheShortExpireError(
workStore.route,
rdcResult.dynamicNestedCacheError
)
)
}
debug?.(
......@@ -2481,9 +2465,10 @@ export async function cache(
shouldReportNestedCacheError
) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheZeroRevalidateErrorMessage, {
cause: rdcResult.dynamicNestedCacheError,
})
createNestedCacheZeroRevalidateError(
workStore.route,
rdcResult.dynamicNestedCacheError
)
)
}
if (
......@@ -2492,9 +2477,10 @@ export async function cache(
shouldReportNestedCacheError
) {
throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheShortExpireErrorMessage, {
cause: rdcResult.dynamicNestedCacheError,
})
createNestedCacheShortExpireError(
workStore.route,
rdcResult.dynamicNestedCacheError
)
)
}
// A short-lived entry is a dynamic hole, excluded from the
......
......@@ -14,6 +14,7 @@ import {
} from '../../../shared/lib/action-revalidation-kind'
import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'
import { encodeHeaderSafe } from '../../lib/encode-header-safe'
import { createRevalidateDuringRenderError } from '../../use-cache/use-cache-messages'
import { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'
type CacheLifeConfig = {
......@@ -37,7 +38,11 @@ export function revalidateTag(tag: string, profile: string | CacheLifeConfig) {
} else if (typeof profile === 'object') {
profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })
}
return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)
return revalidate(
[encodeHeaderSafe(tag)],
`revalidateTag(${JSON.stringify(tag)})`,
profile
)
}
/**
......@@ -59,7 +64,11 @@ export function updateTag(tag: string) {
)
}
// updateTag uses immediate expiration (no profile) without deprecation warning
return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)
return revalidate(
[encodeHeaderSafe(tag)],
`updateTag(${JSON.stringify(tag)})`,
undefined
)
}
/**
......@@ -119,7 +128,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)
}
return revalidate(tags, `revalidatePath ${originalPath}`)
return revalidate(tags, `revalidatePath(${JSON.stringify(originalPath)})`)
}
function revalidate(
......@@ -137,25 +146,15 @@ function revalidate(
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
if (workUnitStore.phase === 'render') {
throw new Error(
`Route ${store.route} used "${expression}" during render 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`
)
throw createRevalidateDuringRenderError(store.route, expression)
}
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
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`
)
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_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`
)
case 'generate-static-params':
throw new Error(
`Route ${store.route} used "${expression}" inside \`generateStaticParams\` 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`
)
throw createRevalidateDuringRenderError(store.route, expression)
case 'prerender':
case 'prerender-runtime':
// cacheComponents Prerender
......
......@@ -307,7 +307,8 @@ describe('dynamic-data inside cache scope', () => {
try {
await expect(browser).toDisplayRedbox(`
{
"description": "Route /cookies used \`cookies()\` 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 \`cookies()\` 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",
"description": "Route "/cookies": \`cookies()\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"environmentLabel": "Server",
"label": "Runtime Error",
"source": "app/cookies/page.js (4:40) @ ${isTurbopack ? '<anonymous>' : 'eval'}
......@@ -327,7 +328,8 @@ describe('dynamic-data inside cache scope', () => {
try {
await expect(browser).toDisplayRedbox(`
{
"description": "Route /connection 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",
"description": "Route "/connection": \`connection()\` can't be called inside \`unstable_cache()\` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.
Learn more: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"environmentLabel": "Server",
"label": "Runtime Error",
"source": "app/connection/page.js (4:54) @ ${isTurbopack ? '<anonymous>' : 'eval'}
......@@ -347,7 +349,8 @@ describe('dynamic-data inside cache scope', () => {
try {
await expect(browser).toDisplayRedbox(`
{
"description": "Route /headers 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",
"description": "Route "/headers": \`headers()\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"environmentLabel": "Server",
"label": "Runtime Error",
"source": "app/headers/page.js (4:40) @ ${isTurbopack ? '<anonymous>' : 'eval'}
......@@ -371,13 +374,13 @@ describe('dynamic-data inside cache scope', () => {
// We expect this to fail
}
expect(next.cliOutput).toMatch(
'Error: Route /cookies used `cookies()` inside a function cached with `unstable_cache()`.'
'Error: Route "/cookies": `cookies()` can\'t be read inside `unstable_cache()`. Read it outside the cached function and pass what you need as an argument.'
)
expect(next.cliOutput).toMatch(
'Error: Route /connection used `connection()` inside a function cached with `unstable_cache()`.'
'Error: Route "/connection": `connection()` can\'t be called inside `unstable_cache()` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.'
)
expect(next.cliOutput).toMatch(
'Error: Route /headers used `headers()` inside a function cached with `unstable_cache()`.'
'Error: Route "/headers": `headers()` can\'t be read inside `unstable_cache()`. Read it outside the cached function and pass what you need as an argument.'
)
})
}
......
......@@ -30,7 +30,7 @@ describe('revalidateTag-rsc', () => {
if (isNextDev) {
await waitForRedbox(browser)
await expect(getRedboxHeader(browser)).resolves.toContain(
'Route /revalidate_via_page used "revalidateTag data"'
'Route "/revalidate_via_page": `revalidateTag("data")` can\'t be called during render, inside a cached function, or inside `generateStaticParams`.'
)
} else {
await retry(async () => {
......@@ -41,7 +41,7 @@ describe('revalidateTag-rsc', () => {
}
expect(next.cliOutput).toContain(
'Route /revalidate_via_page used "revalidateTag data"'
'Route "/revalidate_via_page": `revalidateTag("data")` can\'t be called during render, inside a cached function, or inside `generateStaticParams`. Call it from a Server Action or Route Handler instead.\nLearn more: https://nextjs.org/docs/messages/revalidate-in-use-cache'
)
})
}
......
import { nextTestSetup } from 'e2e-utils'
import stripAnsi from 'strip-ansi'
const expectedTimeoutErrorMessage =
'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".'
const timeoutErrorMessage =
'A `"use cache"` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as `params` or `searchParams`, into the cached function. Resolve the data before calling the function and pass only the values you need.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache'
function expectedTimeoutErrorMessage(route: string) {
return `Route "${route}": ${timeoutErrorMessage}`
}
describe('use-cache-configured-timeout', () => {
const { next, isNextDev, skipped } = nextTestSetup({
......@@ -27,7 +31,7 @@ describe('use-cache-configured-timeout', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).not.toContain(expectedTimeoutErrorMessage)
expect(cliOutput).not.toContain(timeoutErrorMessage)
})
})
......@@ -38,7 +42,8 @@ describe('use-cache-configured-timeout', () => {
await expect(browser).toDisplayRedbox(`
{
"description": "Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".",
"description": "Route "/above-dev-timeout": A \`"use cache"\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \`params\` or \`searchParams\`, into the cached function. Resolve the data before calling the function and pass only the values you need.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Cache",
"label": "Runtime Error",
"source": "app/above-dev-timeout/page.tsx (4:1) @ getCachedData
......@@ -54,7 +59,9 @@ describe('use-cache-configured-timeout', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).toContain(expectedTimeoutErrorMessage)
expect(cliOutput).toContain(
expectedTimeoutErrorMessage('/above-dev-timeout')
)
})
})
} else {
......@@ -66,7 +73,7 @@ describe('use-cache-configured-timeout', () => {
// expected
}
expect(next.cliOutput).toContain(expectedTimeoutErrorMessage)
expect(next.cliOutput).toContain(timeoutErrorMessage)
expect(next.cliOutput).toContain(
'Error occurred prerendering page "/below-dev-timeout"'
)
......
......@@ -10,8 +10,12 @@ import {
} from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const expectedTimeoutErrorMessage =
'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".'
const timeoutErrorMessage =
'A `"use cache"` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as `params` or `searchParams`, into the cached function. Resolve the data before calling the function and pass only the values you need.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache'
function expectedTimeoutErrorMessage(route: string) {
return `Route "${route}": ${timeoutErrorMessage}`
}
describe('use-cache-hanging-inputs', () => {
const { next, isNextDev, skipped } = nextTestSetup({
......@@ -42,7 +46,9 @@ describe('use-cache-hanging-inputs', () => {
const errorSource = await getRedboxSource(browser)
expect(errorCount).toBe(1)
expect(errorDescription).toBe(expectedTimeoutErrorMessage)
expect(errorDescription).toBe(
expectedTimeoutErrorMessage('/uncached-promise')
)
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
......@@ -58,7 +64,8 @@ describe('use-cache-hanging-inputs', () => {
13 | return ("
`)
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
expect(cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage('/uncached-promise')}
at Foo (app/uncached-promise/page.tsx:10:13)`)
}, 180_000)
})
......@@ -80,7 +87,9 @@ describe('use-cache-hanging-inputs', () => {
const errorSource = await getRedboxSource(browser)
expect(errorCount).toBe(1)
expect(errorDescription).toBe(expectedTimeoutErrorMessage)
expect(errorDescription).toBe(
expectedTimeoutErrorMessage('/uncached-promise-nested')
)
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
......@@ -96,7 +105,8 @@ describe('use-cache-hanging-inputs', () => {
19 | return getCachedData(promise)"
`)
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
expect(cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage('/uncached-promise-nested')}
at indirection (app/uncached-promise-nested/page.tsx:16:1)
at Page (app/uncached-promise-nested/page.tsx:23:22)`)
}, 180_000)
......@@ -122,7 +132,9 @@ describe('use-cache-hanging-inputs', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(errorDescription).toBe(expectedTimeoutErrorMessage)
expect(errorDescription).toBe(
expectedTimeoutErrorMessage('/bound-args')
)
expect(errorSource).toMatchInlineSnapshot(`
"app/bound-args/page.tsx (13:15) @ Foo
......@@ -136,7 +148,8 @@ describe('use-cache-hanging-inputs', () => {
16 | return ("
`)
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
expect(cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage('/bound-args')}
at Foo (app/bound-args/page.tsx:13:15)`)
}, 180_000)
})
......@@ -167,7 +180,7 @@ describe('use-cache-hanging-inputs', () => {
expect(cliOutput).toInclude('Error: kaputt!')
expect(cliOutput).toIncludeRepeated(
escapeStringRegexp(expectedTimeoutErrorMessage),
escapeStringRegexp(timeoutErrorMessage),
4
)
......
......@@ -2,8 +2,12 @@ import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const expectedTimeoutErrorMessage =
'Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".'
const timeoutErrorMessage =
'A `"use cache"` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as `params` or `searchParams`, into the cached function. Resolve the data before calling the function and pass only the values you need.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache'
function expectedTimeoutErrorMessage(route: string) {
return `Route "${route}": ${timeoutErrorMessage}`
}
describe('use-cache-hanging', () => {
const { next, isNextDev, skipped, isTurbopack } = nextTestSetup({
......@@ -24,7 +28,8 @@ describe('use-cache-hanging', () => {
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".",
"description": "Route "/static": A \`"use cache"\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \`params\` or \`searchParams\`, into the cached function. Resolve the data before calling the function and pass only the values you need.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/static/page.tsx (1:1) @ getCachedData
......@@ -40,7 +45,8 @@ describe('use-cache-hanging', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
expect(cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage('/static')}
at getCachedData (app/static/page.tsx:1:1)`)
})
})
......@@ -52,7 +58,8 @@ describe('use-cache-hanging', () => {
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".",
"description": "Route "/runtime": A \`"use cache"\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \`params\` or \`searchParams\`, into the cached function. Resolve the data before calling the function and pass only the values you need.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/runtime/page.tsx (4:1) @ getCachedData
......@@ -68,7 +75,8 @@ describe('use-cache-hanging', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
expect(cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage('/runtime')}
at getCachedData (app/runtime/page.tsx:4:1)`)
})
})
......@@ -83,13 +91,15 @@ describe('use-cache-hanging', () => {
await retry(() => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
expect(cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage('/static')}
at getCachedData (app/static/page.tsx:1:1)`)
}, 20_000)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".",
"description": "Route "/static": A \`"use cache"\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \`params\` or \`searchParams\`, into the cached function. Resolve the data before calling the function and pass only the values you need.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/static/page.tsx (1:1) @ getCachedData
......@@ -115,13 +125,15 @@ describe('use-cache-hanging', () => {
await retry(() => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).toContain(`Error: ${expectedTimeoutErrorMessage}
expect(cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage('/runtime')}
at getCachedData (app/runtime/page.tsx:4:1)`)
}, 20_000)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache".",
"description": "Route "/runtime": A \`"use cache"\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \`params\` or \`searchParams\`, into the cached function. Resolve the data before calling the function and pass only the values you need.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/runtime/page.tsx (4:1) @ getCachedData
......@@ -148,7 +160,7 @@ describe('use-cache-hanging', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).not.toContain(expectedTimeoutErrorMessage)
expect(cliOutput).not.toContain(timeoutErrorMessage)
})
})
} else {
......@@ -162,11 +174,13 @@ describe('use-cache-hanging', () => {
if (isTurbopack) {
expect(next.cliOutput)
.toContain(`Error: ${expectedTimeoutErrorMessage}
.toContain(`Error: ${expectedTimeoutErrorMessage('/static')}
at <unknown> (app/static/page.tsx:1:1)`)
} else {
// Webpack production builds don't have source maps by default.
expect(next.cliOutput).toContain(expectedTimeoutErrorMessage)
expect(next.cliOutput).toContain(
expectedTimeoutErrorMessage('/static')
)
}
})
})
......
......@@ -3,7 +3,7 @@ import { assertNoConsoleErrors, waitForNoRedbox } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const getExpectedErrorMessage = (route: string) =>
`Route ${route} used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
`Route "${route}": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache`
describe('use-cache-search-params', () => {
const { next, isNextDev, skipped } = nextTestSetup({
......@@ -30,7 +30,8 @@ describe('use-cache-search-params', () => {
await expect(browser).toDisplayRedbox(`
{
"description": "Route /search-params-used used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"description": "Route "/search-params-used": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Cache",
"label": "Runtime Error",
"source": "app/search-params-used/page.tsx (8:17) @ Page
......@@ -60,7 +61,8 @@ describe('use-cache-search-params', () => {
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route /search-params-caught used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"description": "Route "/search-params-caught": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/search-params-caught/page.tsx (11:5) @ Page
......@@ -88,7 +90,8 @@ describe('use-cache-search-params', () => {
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route /search-params-caught used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"description": "Route "/search-params-caught": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/search-params-caught/page.tsx (11:5) @ Page
......@@ -126,7 +129,8 @@ describe('use-cache-search-params', () => {
await expect(browser).toDisplayRedbox(`
{
"description": "Route /search-params-used-generate-metadata used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"description": "Route "/search-params-used-generate-metadata": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Cache",
"label": "Runtime Error",
"source": "app/search-params-used-generate-metadata/page.tsx (9:17) @ generateMetadata
......@@ -146,7 +150,8 @@ describe('use-cache-search-params', () => {
await expect(browser).toDisplayRedbox(`
{
"description": "Route /search-params-used-generate-viewport used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"description": "Route "/search-params-used-generate-viewport": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": "Cache",
"label": "Runtime Error",
"source": "app/search-params-used-generate-viewport/page.tsx (9:17) @ generateViewport
......
......@@ -1064,7 +1064,7 @@ describe('use-cache', () => {
const expectedErrorMessage = disableJavaScript
? 'Failed to load resource: the server responded with a status of 500 (Internal Server Error)'
: isNextDev
? 'Route /draft-mode/[mode] used `cookies()` inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use `cookies()` 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 "/draft-mode/[mode]": `cookies()` can\'t be read inside `"use cache"`. Read it outside the cached function and pass what you need as an argument.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache'
: GENERIC_RSC_ERROR
expect(logs).toMatchObject(
......
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