Skip to content

Make cache()'s server request scope more obvious#8310

Open
thomasboyt wants to merge 1 commit intoreactjs:mainfrom
thomasboyt:patch-1
Open

Make cache()'s server request scope more obvious#8310
thomasboyt wants to merge 1 commit intoreactjs:mainfrom
thomasboyt:patch-1

Conversation

@thomasboyt
Copy link

@thomasboyt thomasboyt commented Feb 18, 2026

I'm adopting Next's App Router in a new project, and was surprised by how non-obvious the documentation for cache() is about how it works.

As far as I'm aware - please correct me if I'm wrong on this, because it's rather important! - cache() is a server-request-scoped cache. A cache is unique to a single server request and will not share values with other server requests being handled at the same time.

This is important to its use in a framework like Next.js, where you might have a function like:

import { cookies } from 'next/headers';

const getCurrentUser = cache(async () => {
  const result = await getCurrentUserFromAuthToken(cookies.get('auth-token'));
  return result;
});

Even though getCurrentUser() has no arguments passed in, it still should return the correct user for each request's current context, and not incorrectly share a user object between different server requests.

As far as I'm concerned, this is the single most important aspect of cache(), and I don't understand why this is buried under the caveats section. It's not a caveat; it is intentional, desired behavior! It is the key to how you use it!

So in this PR I want to lift this detail up to the first sentence. I would also like to add a second sentence like:

cache lets you cache the result of a data fetch or computation for the span of a server request. You can use it to avoid re-fetching data when multiple React Server Components are rendered during a single server request.

Because currently, the motivation is buried down in "Usage." However, I think there's a preference to only have a single sentence in the "intro" of each docs page, so I held off - maybe it could be a separate paragraph above the TOC?

@github-actions
Copy link

Size changes

Details

📦 Next.js Bundle Analysis for react-dev

This analysis was generated by the Next.js Bundle Analysis action. 🤖

This PR introduced no changes to the JavaScript bundle! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments