Cache Components is an option, even though create-next-app recommends it and it's set to become the default behavior in version 17. Everything written before it, and much of what's being written today, works without it: projects on versions 13, 14 and 15, projects on 16 that haven't enabled it, and almost every article and answer you'll find when you search.
This lesson teaches you to read that code. You'll see how the previous model decides whether a route is static, which four caches are involved, what dynamic, revalidate, fetchCache, the fetch options and unstable_cache do, and why the same code behaves differently on 14 and on 15. Then we'll go through the migration step by step, with its codemods and a table of equivalents. Nothing in this lesson applies to AgendaViva: it's knowledge for the rest of your work.
- Which model you're looking at
Before touching a line, find out which model you're in. It's decided in the configuration, for the whole application:
| Sign | Model |
|---|---|
cacheComponents: true in next.config |
The one in this course |
| Next.js 16 without that option | Previous, with 15's defaults |
| Next.js 15 | Previous; fetch uncached by default |
| Next.js 13 or 14 | Previous; fetch cached by default |
experimental.ppr, experimental.dynamicIO, experimental.useCache |
Trial runs of what ended up as Cache Components |
pages/ folder, getStaticProps, getServerSideProps |
Pages Router: another model, not covered here |
In the code, the most reliable traces are export const dynamic, export const revalidate, fetch with next: {…} and unstable_cache. With Cache Components, the first two raise an error; the other two keep working, so their presence proves nothing on its own.
- It's decided per route
Without Cache Components there's no shell with holes. Each route is either static (generated at build time or on revalidation) or dynamic (rendered on every request), and a single detail in any component is enough to make the whole of it dynamic:
| What appears in the route | Effect |
|---|---|
cookies(), headers(), searchParams, connection() |
The whole route is dynamic |
fetch with cache: 'no-store' or revalidate: 0 |
The whole route is dynamic |
export const dynamic = 'force-dynamic' or revalidate = 0 |
Dynamic |
[slug] without generateStaticParams |
Dynamic |
| None of the above | Static, even if it queries a database |
The next build symbols were different too: ○ static, ● generated with generateStaticParams and ƒ dynamic. There's no ◐.
A <Suspense> in a dynamic route lets it stream in parts, but it doesn't separate the static from the dynamic: nothing is served ready-made, and every visit waits for the server to start responding. And reading cookies() in a layout to render a greeting turned the entire site dynamic, without a single warning. That's the problem the new model solved.
2.1. The last-row trap
The "none of the above" row is the model's most common source of bugs. This code, with an ORM, looks dynamic and isn't:
// Without Cache Components
export default async function VenuesPage() {
const venues = await db.select().from(venuesTable)
return <VenueList venues={venues} />
}A query with an ORM isn't a fetch and doesn't read the request, so Next.js sees nothing dynamic. It runs it at build time and serves that HTML until the next deployment. In development you don't notice, because there it renders on every visit. The symptom is unmistakable: "it works locally and in production the data doesn't change".
With a fetch without options, something similar happens on 15 and 16: the response isn't stored in the data cache, but if nothing else makes the route dynamic, the page is generated at build time and the result is frozen in the HTML. "Not cached by default" did not mean "on every request".
With Cache Components, the same code is an error that forces you to choose between streaming and caching. The inconvenience you felt in 01-04 is the price of making sure this can't happen.
- The four caches
The version 14 documentation described four mechanisms, and their names are still in use:
| Name | Stores | Where | Lasts |
|---|---|---|---|
| Request Memoization | Results of identical fetch calls |
Server | One render |
| Data Cache | Responses from fetch and unstable_cache |
Server | Across requests and across deployments |
| Full Route Cache | HTML and RSC Payload of static routes | Server | Across requests; cleared on deployment |
| Router Cache | RSC Payload of what was visited and prefetched | Browser | The session, or a set time |
flowchart TD
A["Navigation"] --> B{"Router Cache"}
B -- hit --> Z["Shown"]
B -- miss --> C{"Full Route Cache<br/>(static routes only)"}
C -- hit --> Z
C -- miss --> D["Rendered"]
D --> E{"Request Memoization"}
E -- miss --> F{"Data Cache"}
F -- miss --> G["API or database"]
Two relationships between them explain almost everything that's surprising:
- Invalidating the Data Cache invalidates the Full Route Cache, because the page depends on the data. Not the other way around: a dynamic page can use cached data.
- None of the server caches clears anyone else's Router Cache. Only that of whoever runs a Server Action that revalidates.
How they map to what you know:
| Before | Now |
|---|---|
| Request Memoization | The same, for fetch; React.cache for everything else |
| Data Cache | 'use cache' entries, with the difference that they do not survive a deployment |
| Full Route Cache | Stored shells and pages, partial or complete |
| Router Cache | The client cache, with stale per piece of content |
- Data
4.1. The fetch options
await fetch(url) // Depends on the version
await fetch(url, { cache: 'force-cache' }) // Stored
await fetch(url, { cache: 'no-store' }) // Never stored
await fetch(url, { next: { revalidate: 3600 } }) // Stored for an hour
await fetch(url, { next: { tags: ['events'] } }) // With a tag
await fetch(url, { next: { revalidate: 3600, tags: ['events'] } })| Next.js 13 and 14 | Next.js 15 and 16 | |
|---|---|---|
fetch without options |
Stored | Not stored (though the route may be static) |
GET in a Route Handler |
Stored if it doesn't read the request | Not stored |
| Pages in the Router Cache | 30 s for dynamic ones, 5 min for static ones | Not reused when navigating, except for back and forward |
params, cookies(), headers() |
Synchronous | Asynchronous |
This change in defaults is why one article says the opposite of another. Always check the date and the version. More details that come up when reading code:
revalidate: falsemeans "forever";0, "never stored".{ revalidate: 3600, cache: 'no-store' }is contradictory: both are ignored, with a warning in development.- If several
fetchcalls in the same route have different times, the route is revalidated with the lowest. - Only 200 responses are stored.
4.2. unstable_cache
For anything that isn't fetch, a function that wraps another one:
import { unstable_cache } from 'next/cache'
export const getVenue = unstable_cache(
async (slug: string) => queryVenue(slug),
['venue'], // Additional key parts
{ tags: ['venues'], revalidate: 3600 },
)The key is made up of the arguments, the function's source text and the second parameter. That parameter exists because captured variables don't count, unlike with 'use cache':
// Classic bug: district isn't in the key, so every district shares the entry
function getGuide(district: string) {
return unstable_cache(async () => queryGuide(district), ['guide'])()
}
// Fixed
function getGuideFixed(district: string) {
return unstable_cache(async () => queryGuide(district), ['guide', district])()
}The first one is a serious, silent bug: as soon as the data depends on a person, it's an information leak. When you review old code, look for it.
Despite the prefix, it keeps working with Cache Components, and the documentation recommends it in one specific case: data that doesn't come from fetch and must survive deployments. 'use cache' can't do that.
- Segment configuration
These are constants exported from page, layout or route. These are the meanings you need to recognize:
export const dynamic = 'auto' // 'force-dynamic' | 'error' | 'force-static'
export const revalidate = 3600 // false | 0 | seconds
export const fetchCache = 'auto' // and six other values
export const dynamicParams = true // false: 404 for anything not generated
export const runtime = 'nodejs' // 'edge', deprecated| Export | What it does |
|---|---|
dynamic = 'force-dynamic' |
Rendered on every request, and its fetch calls aren't stored |
dynamic = 'force-static' |
Always generated, and cookies(), headers() and useSearchParams() return empty values |
dynamic = 'error' |
Generated; if something prevents it, it fails |
revalidate = n |
The route's default time. It doesn't override each fetch's own |
fetchCache |
Changes or restricts the option of every fetch in the route |
dynamicParams = false |
Only the URLs from generateStaticParams exist |
Three details that waste time:
- The lowest wins. In a route with several layouts and the page, the lowest
revalidateapplies to all of it. A root layout withrevalidate = 60affects the entire site. - The value is analyzed without running it.
revalidate = 3600works;revalidate = 60 * 60doesn't. force-staticdoesn't warn you. The page doesn't fail when reading a cookie: it's told there isn't one. It's easy to deploy a private area this way that thinks it's empty.
Alongside them you'll see unstable_noStore(), or noStore(), inside functions: it marked whoever called it as dynamic. And experimental.staleTimes in the configuration, for the Router Cache.
5.1. Reading an old file
// app/events/[slug]/page.tsx — Next.js 15, without Cache Components
import { unstable_cache } from 'next/cache'
import { notFound } from 'next/navigation'
export const revalidate = 3600
export const dynamicParams = true
const getEvent = unstable_cache(
async (slug: string) => queryEvent(slug),
['event'],
{ tags: ['events'], revalidate: 600 },
)
export async function generateStaticParams() {
return []
}
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const event = await getEvent(slug)
if (!event) notFound()
const response = await fetch(`https://api.example.com/weather?day=${event.day}`)
const weather = await response.json()
return <Details event={event} weather={weather} />
}Interpreting it:
- It's a static route with ISR:
[]postpones each page until its first visit, anddynamicParams = trueallows them to be generated. - The page is regenerated every 600 seconds, not every 3600: the lowest wins.
- The
fetchhas no options. On 15 it doesn't go into the Data Cache, but its result is frozen in the HTML until regeneration. Whoever wrote it may have believed it fetched the weather on every visit. - The first visit waits for the complete result, and that's why
notFound()does give a real 404: nothing has been sent yet. - With
revalidateTag('events'), the single-argument form that was usual back then, both the data and the pages are invalidated.
- Migrating step by step
Cache Components requires Next.js 16. If the project is older, there are two migrations: upgrading the version and, later, switching models. Mixing them makes it impossible to tell what broke what.
6.1. Upgrading to 16
It updates Next.js and React and offers to apply the transformations. The ones you'll see most:
| Codemod | What it changes |
|---|---|
next-async-request-api |
params, searchParams, cookies()… become awaited. Where it can't tell, it leaves a comment that blocks the build until you resolve it |
middleware-to-proxy |
middleware.ts becomes proxy.ts |
next-lint-to-eslint-cli |
next lint goes away |
remove-unstable-prefix |
unstable_cacheTag and the like, without the prefix |
remove-experimental-ppr |
Removes experimental_ppr from segments |
At this point the application works with the previous model. Check the revalidateTag calls: the second argument is required without Cache Components too. Deploy and stabilize.
6.2. Enabling the option without converting everything
When you set cacheComponents: true, segments with dynamic, revalidate or fetchCache raise errors, and so do routes that block. Doing it all at once in a large project is unworkable; the official guide proposes turning off validation everywhere and turning it back on route by route:
It adds export const instant = false, with a comment, to every page, layout and default that doesn't declare it, except Client Components. Check the number of modified files: with the wrong path (./app in a project with src/) it doesn't fail, it says it processed zero. The full order:
- Enable
cacheComponentsand, if possible,partialPrefetching. Leaving the latter unset produces a warning. - Remove the segment configurations, replacing them according to the table in section 7. Also
runtime(including'nodejs') anddynamicParams. - Apply the codemod so the rest builds.
- Fix the clock and randomness.
instant = falsedoesn't silence them:new Date(),Math.random()orcrypto.randomUUID()while prerendering are still errors. It's the only work that can't be postponed. - Review
generateStaticParams: it mustn't return[]. - Deploy. The site works, blocking where it used to block.
- Convert one route: remove its
instant = false, deal with the warnings (stream or cache), check it with the Navigation Inspector. And repeat.
Start with the routes with lots of traffic and shared data, which is where the gains are. Private areas, last or never: a dashboard that blocks can stay blocking.
There's also an official skill for coding agents, next-cache-components-adoption, that guides this same process.
6.3. The previous file, migrated
// lib/data/events.ts
import { cacheLife, cacheTag } from 'next/cache'
export async function getEvent(slug: string) {
'use cache'
cacheLife({ stale: 300, revalidate: 600, expire: 86_400 })
cacheTag('events')
return queryEvent(slug)
}
// lib/data/weather.ts
export async function getWeather(day: string) {
'use cache'
cacheLife('hours')
const response = await fetch(`https://api.example.com/weather?day=${day}`)
return response.json()
}// app/events/[slug]/page.tsx
export async function generateStaticParams() {
const slugs = await listSlugs(20)
return slugs.map((slug) => ({ slug }))
}
export default function Page({ params }: PageProps<'/events/[slug]'>) {
return (
<Suspense fallback={<EventDetailsSkeleton />}>
<Content params={params} />
</Suspense>
)
}
async function Content({ params }: Pick<PageProps<'/events/[slug]'>, 'params'>) {
const { slug } = await params
const event = await getEvent(slug)
if (!event) notFound()
return <Details event={event} weather={await getWeather(event.day)} />
}The two exports disappear, unstable_cache becomes a directive and the weather finally has a written lifetime. There's also a change in behavior that must be accepted knowingly: the first visit to an event that wasn't included no longer waits, it receives a fallback, and a nonexistent event responds with a 200 and noindex instead of a 404 (05-05).
- Equivalents
| Previous model | With Cache Components |
|---|---|
dynamic = 'force-dynamic' |
Remove it. Whatever isn't cached already runs at request time, under <Suspense> |
dynamic = 'force-static' |
Remove it and use 'use cache' with cacheLife. If the requirement stays, ensureStatic = 'navigation' |
dynamic = 'error' |
Remove it; ensureStatic = 'navigation' if you want the guarantee |
revalidate = n |
'use cache' and cacheLife where the data is read |
revalidate = 0 |
Remove it |
fetchCache = 'force-cache' and similar |
'use cache' on each read that should be stored |
fetchCache = 'force-no-store' and similar |
Remove it, along with the cache options it overrode |
fetch(url, { cache: 'force-cache' }) |
fetch inside a function with 'use cache' |
next: { revalidate, tags } |
cacheLife and cacheTag |
cache: 'no-store' |
Remove it |
unstable_cache |
It can stay; if migrated, 'use cache'. The key list is no longer needed |
unstable_noStore() |
Remove it; io() or connection() if the code must wait for the request |
React.cache |
It stays, with its own scope in each cached function |
revalidateTag(t) |
updateTag(t) in actions, revalidateTag(t, 'max') elsewhere |
revalidatePath |
The same |
generateStaticParams returning [] |
At least one value |
dynamicParams = false |
Doesn't exist: notFound() in the page |
runtime = 'edge' |
Remove it: Node.js is required |
experimental_ppr |
Remove it |
GET with force-static |
Helper function with 'use cache' called by the GET |
The first two rows sum up the change in mindset: before, you declared the route's mode; now you handle each piece of data and the mode follows.
- What isn't equivalent
A mechanical migration leaves differences the table doesn't show:
| Difference | Consequence | What to do |
|---|---|---|
The Data Cache and unstable_cache survive deployments; 'use cache' doesn't |
A spike in queries after deploying | Enough capacity, or keep unstable_cache for the most expensive data |
'use cache' stores in memory per instance |
On serverless platforms, fewer runtime hits | 'use cache: remote' where it pays off |
force-static gave empty cookies |
Now the real ones are read | Check that no personal content shows up |
| Pages are hidden instead of unmounted | State that used to reset now persists: open dropdowns, a form's messages | Reset explicitly |
| 404 codes and redirects after the shell | 200 | Decide in proxy.ts if needed |
GET handlers abandon prerendering by throwing an exception |
A broad try/catch catches it and logs it as an error |
Narrow the try |
| Building runs the cached queries | The database is needed | 05-02 and 05-05 |
usePathname and useParams can suspend |
The build fails on dynamic routes | <Suspense> around the component |
The third row deserves a warning. If a force-static page showed the "Sign in" menu because the cookie came out empty, after migrating it'll read the real session. That's usually what was wanted, but if that component is also marked with 'use cache', the error from 05-02 is the only thing preventing a session from being shared.
Is it worth migrating? The option will be the default behavior in the next major version, so the question is when. A project in maintenance mode can wait; one that's growing accumulates, with every route, code that will have to be converted.
Common Mistakes and Tips
- Applying advice without checking the version.
fetchbehaves the opposite way on 14 and on 15. - Believing an ORM query makes the route dynamic in the previous model.
- Interpreting "not cached" as "on every request".
- Leaving captured variables out of the
unstable_cachekey. - Upgrading the version and switching models at the same time.
- Translating
force-dynamicasinstant = false. One turned off prerendering; the other, a validation. - Leaving
instant = falseall over the project and calling the migration done. - Putting
'use cache'on whole pages to imitaterevalidate: everything inherits the same lifetime and nothing personal fits. - Using the
experimentalprefix from a tutorial for something that's already stable.
Exercises
Exercise 1: diagnosing
In a project on Next.js 16 without Cache Components, /news uses await prisma.article.findMany() and exports nothing. In development the new articles show up; in production, they don't. The team tries, separately, these three fixes. Explain what each one does and which you'd choose: (a) export const dynamic = 'force-dynamic'; (b) export const revalidate = 300; (c) cache: 'no-store' on the header's fetch.
Solution
The route is static: it was generated at build time, and nothing regenerates it.
- (a) The query runs on every visit. It works, and the whole page always waits.
- (b) The page is regenerated at most every five minutes, in the background. For news, it's the best of the three.
- (c) It also "works": a single
no-storemakes the whole route dynamic, and the query with it. It's a side effect; if someone caches the header tomorrow, the news freezes again.
The ideal would be (b) with an invalidation on publishing: unstable_cache with a tag and revalidateTag. With Cache Components, the original code wouldn't have built.
Exercise 2: migrating a page
Migrate this page to Cache Components keeping the intent: the list can be half an hour behind, the greeting is personal. Say what improves.
export const dynamic = 'force-dynamic'
export default async function HomePage() {
const name = (await cookies()).get('name')?.value
const response = await fetch('https://api.example.com/featured', {
next: { revalidate: 1800, tags: ['featured'] },
})
const featured: FeaturedItem[] = await response.json()
return (
<>
<p>{name ? `Hi, ${name}` : 'Hi'}</p>
<FeaturedList featured={featured} />
</>
)
}Solution
import { Suspense } from 'react'
import { cacheLife, cacheTag } from 'next/cache'
import { cookies } from 'next/headers'
async function getFeatured(): Promise<FeaturedItem[]> {
'use cache'
cacheLife({ stale: 300, revalidate: 1800, expire: 86_400 })
cacheTag('featured')
const response = await fetch('https://api.example.com/featured')
if (!response.ok) throw new Error(`The API responded with ${response.status}`)
return response.json()
}
async function Greeting() {
const name = (await cookies()).get('name')?.value
return <p>{name ? `Hi, ${name}` : 'Hi'}</p>
}
export default async function HomePage() {
return (
<>
<Suspense fallback={<p>Hi</p>}>
<Greeting />
</Suspense>
<FeaturedList featured={await getFeatured()} />
</>
)
}Before, the whole page waited for the request because of a greeting. Now the list is in the shell and only the name arrives afterwards; the fallback, "Hi", takes up the same space. What's more, the response is checked: a 500 would no longer be stored as if it were a list.
Exercise 3: planning
You inherit an online store on Next.js 14 with 120 routes, middleware.ts, revalidate = 60 in the root layout, 30 uses of unstable_cache and a private dashboard. There's a weekly deployment and the database is stretched thin. Write the plan in stages, with the criterion for moving from one to the next and the risks of each.
Solution
| Stage | Work | Main risk | Move on when |
|---|---|---|---|
| 1 | Upgrade to 15 with the codemod: async APIs | fetch stops being stored: the database and APIs get more load |
Metrics are stable; the important fetch calls have explicit force-cache or revalidate |
| 2 | Upgrade to 16: proxy.ts, ESLint, second argument of revalidateTag |
Images, parallel routes and other changes in the version guide | Everything green and deployed |
| 3 | Enable cacheComponents; remove configurations; instant = false codemod; fix clock and randomness |
The root revalidate = 60 disappears: whatever depended on it moves to the request |
It builds and performs as before |
| 4 | Convert catalog and product pages, with generateStaticParams and tags |
Building against the database; 404s that become 200s | The shells contain product and price where appropriate |
| 5 | unstable_cache: migrate the cheap ones, keep the expensive ones |
Query spike after each weekly deployment | The database can handle it |
| 6 | Dashboard | Little gain | It can stay with instant = false |
In stage 3, before deleting the root revalidate, it's worth listing which static routes depended on it and caching their reads in the same change. Each stage is a reversible deployment; if the database struggles, 'use cache: remote' or keeping unstable_cache are the ways out.
Conclusion
The previous model decides per route: it's static unless something makes it dynamic, and an ORM query doesn't count as something. Acting on that decision are four caches, fetch options whose default changed in 15, unstable_cache and the segment exports. To migrate, you first upgrade the version, then enable the option with validation switched off and, finally, convert route by route. The equivalents are almost direct; what you need to watch is what stops persisting, the status codes and the state that no longer resets.
That wraps up module 5. AgendaViva serves its shared content from the shell, knows how long each piece of data lasts and has written down how to report each change. All it's missing is for something to change: so far nobody can write anything to it. Module 6 deals with mutations and starts with Server Actions, where the first action will save the preferred district that you had to write by hand in the console in 04-05.
