网页
综合
更新时间 2026-10-06 00:00:00
Caching
自动蜘蛛
nextjs.org
正文约 6000 字
This page covers caching with Cache Components, enabled by setting cacheComponents: true in your next.config.ts file. If you're not using Cache Components, see the Caching and Revalidating (Previous Model) guide.
Caching is a technique for storing the result of data fetching and other computations so that future requests for the same data can be served faster, without doing the work again.
New App Router apps created with the recommended create-next-app defaults already have Cache Components and Partial Prefetching enabled.
To enable it in an existing or manually created app, add the cacheComponents and partialPrefetching options to your Next config file:
Set partialPrefetching explicitly. Leaving it unset logs a warning, because the first release of Cache Components did not include Partial Prefetching. Set it to false only while migrating an app that adopted Cache Components before Partial Prefetching. Both features will be enabled everywhere in the next major release, and the options will be removed.
When Cache Components is enabled, GET Route Handlers follow the same prerendering model as pages. See Route Handlers with Cache Components for details.
The use cache directive caches the return value of async functions and components. You can apply it at two levels:
A cache directive gives a result a lifetime, which Next.js uses for time-based revalidation and rendering optimizations. For on-demand revalidation after a mutation, see Revalidating. See Prerendering for how cached results become part of the static shell and may be included in a prefetch.
We recommend pairing every cache directive with a cacheLife. Without one, the implicit default profile applies.
Arguments and any values captured from parent scopes automatically become part of the cache key, which means different inputs will produce separate cache entries. See cache output for what an entry holds, and serialization requirements and constraints for details on what can be cached and how arguments work.
To cache an asynchronous function that fetches data, add the use cache directive at the top of the function body:
Data-level caching is useful when the same data is used across multiple components, or when you want to cache the data independently from the UI.
To cache an entire component, page, or layout, add the use cache directive at the top of the component or page body:
If you add "use cache" at the top of a file, all exported functions in the file will be cached.
For components that fetch data from an asynchronous source such as an API, a database, or any other async operation, and require fresh data on every request, do not use "use cache".
Instead, wrap the component in <Suspense> and provide a fallback UI. The fallback ships with the prerendered shell while the async work runs at request time.
For example, <p>Loading posts...</p> is included in the static shell, and the posts stream in at request time.
Without a <Suspense> boundary around the uncached read, the dev overlay surfaces the blocking-route insight with this fix:
Each fix card links to a detailed walkthrough with patterns, code samples, and trade-offs. Click a card to dive in.
<Suspense> provides a fallback UI while async work completes, but it does not itself opt a component into dynamic rendering. If a component only performs synchronous work, it will complete during prerendering regardless of whether it is wrapped in <Suspense>.
Runtime APIs require information that is only available when a user makes a request. These include:
Components that access runtime APIs should be wrapped in <Suspense>:
A runtime API access without <Suspense> surfaces the same blocking-route insight in the dev overlay, with the same fix:
Runtime-dependent data can still be given a cache lifetime with "use cache: private", another variant that ships with Cache Components. It gives a lifetime to a function that reads cookies, headers, or searchParams directly, so it can be included in a prefetch.
The following section shows an alternative to use cache: private: extracting a runtime value and passing it to a shared cached function.
You can extract values from runtime APIs and pass them as arguments to cached functions:
At request time, <CachedContent /> executes if no matching cache entry is found, and stores the result for future requests with the same sessionId.
Because <CachedContent /> is gated behind request data, it isn't added to the prerendered static shell. At runtime it's cached in-memory by default, which doesn't persist across serverless requests, so it may re-evaluate on each request. Reach for 'use cache: remote' for durable, shared caching.
With this pattern, prefetching can prerender <CachedContent /> with the user's actual session during a client transition and have the result ready before the click. This works even when server-side entries rarely survive between requests, because the lifetime you assign is what lets the result join the prefetch, where the client treats it as fresh for its cacheLife stale window.
Here's a complete example showing static content, cached dynamic content, and streaming dynamic content working together on a single page:
During prerendering, the header (static) and blog posts (cached with use cache) become part of the static shell, along with the fallback UI for user preferences. The UI preferences stored in cookies stream in at request time.
Reading cookies() here doesn't opt-in the whole route into dynamic rendering, the way the previous rendering model did. The Suspense boundary provides fallback UI where the runtime access streams, while static and cached content still ship in the initial HTML.
Just as <Suspense> contains async access, an error boundary contains failures: wrap them around a subtree that might error during rendering. Use catchError for component-level boundaries, or the error.js file convention for route-level boundaries.
As you build, consider that inside generateMetadata and generateViewport, uncached fetches or runtime
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。