Caching
App Router Getting Started Caching 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.
Enabling Cache Components 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: TypeScript next.config.ts import type { NextConfig } from 'next' const nextConfig : NextConfig = { cacheComponents : true , partialPrefetching : true , } export default nextConfig 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. Good to know When Cache Components is enabled, GET Route Handlers follow the same prerendering model as pages.
See Route Handlers with Cache Components for details. Usage The use cache directive caches the return value of async functions and components. You can apply it at two levels: Data-level : Cache a function that fetches or computes data (e.g., getProducts() , getUser(id) ) UI-level : Cache an entire component or page (e.g., async function BlogPosts() ) 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 . Good to know 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. Data-level caching To cache an asynchronous function that fetches data, add the use cache directive at the top of the function body: app/lib/data.ts import { cacheLife } from 'next/cache' export async function getUsers () { 'use cache' cacheLife ( 'hours' ) return db .query ( 'SELECT * FROM users' ) } 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.
UI-level caching To cache an entire component, page, or layout, add the use cache directive at the top of the component or page body: app/page.tsx import { cacheLife } from 'next/cache' export default async function Page () { 'use cache' cacheLife ( 'hours' ) const users = await db .query ( 'SELECT * FROM users' ) return ( < ul > { users .map ((user) => ( < li key = { user .id}>{ user .name}</ li > ))} </ ul > ) } If you add " use cache " at the top of a file, all exported functions in the file will be cached.
Streaming uncached data 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. page.tsx import { Suspense } from 'react' async function LatestPosts () { const data = await fetch ( 'https://api.example.com/posts' ) const posts = await data .json () return ( < ul > { posts .map ((post) => ( < li key = { post .id}>{ post .title}</ li > ))} </ ul > ) } export default function Page () { return ( <> < h1 >My Blog</ h1 > < Suspense fallback = {< p >Loading posts...</ p >}> < LatestPosts /> </ Suspense > </> ) } 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: Stream Wrap in or move into Suspense <Suspense fallback={…}> <DataChild /> </Suspense> Good to know 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> . Working with runtime APIs Runtime APIs require information that is only available when a user makes a request. These include: cookies - User's cookie data headers - Request headers searchParams - URL query parameters params - Dynamic route parameters. Use generateStaticParams to prerender specific values at build time, or ISR with Cache Components to serve an App Shell while unknown params resolve in the background.
Components that access runtime APIs should be wrapped in <Suspense> : page.tsx import { cookies } from 'next/headers' import { Suspense } from 'react' async function UserGreeting () { const cookieStore = await cookies () const theme = cookieStore .get ( 'theme' )?.value || 'light' return < p >Your theme: {theme}</ p > } export default function Page () { return ( <> < h1 >Dashboard</ h1 > < Suspense fallback = {< p >Loading...</ p >}> < UserGreeting /> </ Suspense > </> ) } A runtime API access without <Suspense> surfaces the same blocking-route insight in the dev overlay, with the same fix: Stream Wrap in or move into Suspense <Suspense fallback={…}> <DataChild /> </Suspense> 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. Passing runtime values to cached functions You can extract values from runtime APIs and pass them as arguments to cached functions: app/profile/page.tsx import { cookies } from 'next/headers' import { Suspense } from 'react' export default function Page () { return ( < Suspense fallback = {< div >Loading...</ div >}> < ProfileContent /> </ Suspense > ) } // Component (not cached) reads runtime data async function ProfileContent () { const session = ( await cookies ()) .get ( 'session' )?.value return < CachedContent sessionId = {session} /> } // Cached component receives extracted value as a prop async function CachedContent ({ sessionId } : { sessionId : string }) { 'use cache' // sessionId becomes part of the cache key const data = await fetchUserData (sessionId) return < div >{data}</ div > } At request time, <CachedContent /> executes if no matching cache entry is found, and stores the result for future requests with the same sessionId .
Good to know 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 j
The rest of this page is on the live site.