Error: cache() was called outside of a request during render (React Server Components)
React's server-side `cache()` memoizes a function's result for the lifetime of a single request — calling it (or reading its cached value) outside that request boundary, such as at module scope or after the request has already finished, throws. Only call the cached function from within components/functions that execute during that request's render.
What causes this error
Unlike a module-level memoization cache that lives for the process lifetime, React's cache() for Server Components is scoped to a single request/render — its whole purpose is deduplicating repeated calls to the same data-fetching function within one render pass, not caching across requests. `cacheSignal()` lets code detect when that lifetime has ended; calling into a cached function after that point, or from outside any request context at all, throws.
The Fix
import { cache } from 'react';
const getUser = cache(async (id: string) => {
return db.user.findUnique({ where: { id } });
});
// Correct — called during a request's render, from a Server Component
async function ProfilePage({ params }) {
const { id } = await params;
const user = await getUser(id); // deduplicated with any other getUser(id) calls this request
return <Profile user={user} />;
}
// Wrong — calling it at module scope, outside any request
const cachedUser = await getUser('123'); // throws — no active requestCommon causes / variations
- Calling a `cache()`-wrapped function at module top-level instead of inside a component/render function
- Awaiting a cached call inside a background job or a `setTimeout` that outlives the originating request
- Confusing per-request `cache()` with a persistent cross-request cache (use a real cache store, e.g. Redis, for that)
Related errors
See also: Only plain objects can be passed to Client Components, dynamic server usage cookies.
Comments
Loading comments...