Managing API Caching and Data Fetching in Next.js
A mental model for Next.js caching layers and a repeatable pattern for fetching, caching and revalidating API data.
- next.js
- caching
- data-fetching
- api
On this page · 15 sections
Caching in Next.js used to be implicit: whether a fetch was cached depended on defaults, route segment options and which APIs you happened to call. That made it powerful and also hard to reason about. With Cache Components, the model is explicit. Nothing is cached unless you say so, everything else is either prerendered into a static shell or streamed at request time, and every cached result has a lifetime and optional tags for invalidation.
This guide builds a mental model for the new approach and a repeatable pattern for fetching, caching and revalidating API data. It targets the App Router with cacheComponents: true.
The problem: stale data, over-fetching and surprise dynamic pages
Teams usually hit the same three problems:
- Stale pages. A page shows old data and nobody knows which cache holds it.
- Over-fetching. The same API is called on every request because nothing is cached.
- Pages that silently became dynamic. Reading
cookies()or an uncached fetch high in the tree forces a whole route to render per request.
Cache Components addresses all three by making the boundaries visible: static shell, cached content and streamed content.
Enable Cache Components
// next.config.tsimport type { NextConfig } from "next";const nextConfig: NextConfig = { cacheComponents: true, partialPrefetching: true,};export default nextConfig;New projects created with the current create-next-app defaults already have both options on. Setting partialPrefetching explicitly avoids a warning.
The mental model: three kinds of content
Every piece of UI in a route falls into one of three groups:
| Kind | What it is | How it renders |
|---|---|---|
| Static | Pure computation and markup | Prerendered at build time into the static shell |
| Cached | Async work wrapped in use cache | Computed once, reused until its lifetime ends, can be part of the shell |
| Streamed | Request-time data (cookies, uncached fetches) | Rendered per request behind a <Suspense> boundary |
Decide which group each component belongs to and the code almost writes itself.
Cache data with use cache
Add the directive to an async function and give it a lifetime with cacheLife:
// lib/posts.tsimport { cacheLife, cacheTag } from "next/cache";export interface Post { id: string; title: string; excerpt: string;}export async function getPosts(): Promise<Post[]> { "use cache"; cacheLife("hours"); cacheTag("posts"); const res = await fetch("https://api.example.com/posts"); if (!res.ok) throw new Error(`Posts API failed: ${res.status}`); return res.json();}Three things to notice:
cacheLife("hours")uses a built-in profile. Pair everyuse cachewith an explicit lifetime instead of relying on the implicit default profile. Profiles such asseconds,minutes,hours,days,weeksandmaxcover most needs, and you can define your own in the Next config.cacheTag("posts")attaches a label so you can invalidate this entry on demand.- Arguments are part of the key. A function like
getPost(id)produces one cache entry peridautomatically.
Cache a component
You can also cache UI. This is useful when the rendered output is expensive or when the same markup is reused across many requests:
// app/blog/blog-posts.tsximport { cacheLife, cacheTag } from "next/cache";import { getPosts } from "@/lib/posts";export async function BlogPosts() { "use cache"; cacheLife("hours"); cacheTag("posts"); const posts = await getPosts(); return ( <ul> {posts.map((p) => ( <li key={p.id}> <h3>{p.title}</h3> <p>{p.excerpt}</p> </li> ))} </ul> );}Stream request-time data behind Suspense
Data that depends on the request, or that must be fresh on every request, should not be cached. Put it in its own component and wrap that component in <Suspense>:
// app/blog/page.tsximport { cookies } from "next/headers";import { Suspense } from "react";import { BlogPosts } from "./blog-posts";async function UserPreferences() { const theme = (await cookies()).get("theme")?.value ?? "light"; return <aside>Your theme: {theme}</aside>;}export default function BlogPage() { return ( <> <h1>Our blog</h1> {/* cached: part of the static shell */} <BlogPosts /> {/* runtime: streams in per request */} <Suspense fallback={<p>Loading preferences…</p>}> <UserPreferences /> </Suspense> </> );}The heading and the cached posts are served instantly from the shell, and only the preferences component waits for the request. Reading cookies() no longer turns the whole route dynamic.
If you forget the boundary, the dev overlay reports a blocking route and points at the component to wrap in Suspense. Treat that message as a design hint, not noise.
Pass runtime values into cached functions
Sometimes cached data depends on the current user. Read the runtime value in an uncached parent and hand it to a cached function as an argument; the argument becomes part of the cache key:
import { cookies } from "next/headers";import { Suspense } from "react";export default function ProfilePage() { return ( <Suspense fallback={<p>Loading…</p>}> <ProfileContent /> </Suspense> );}async function ProfileContent() { const sessionId = (await cookies()).get("session")?.value; if (!sessionId) return <p>Please sign in.</p>; return <CachedProfile sessionId={sessionId} />;}async function CachedProfile({ sessionId }: { sessionId: string }) { "use cache"; cacheLife("minutes"); const profile = await fetchProfile(sessionId); // keyed by sessionId return <h2>{profile.name}</h2>;}Because this entry is gated behind request data, it is not part of the static shell and is cached in memory by default, which does not persist between serverless invocations. Treat it as an optimization, not a guarantee, and reach for the remote or private cache variants when you need different durability or isolation.
Revalidate after a mutation
Time-based lifetimes are only half the story. After a user changes data, invalidate by tag.
updateTag expires the entry immediately so the user sees their own change. It can only be called from a Server Action:
// app/blog/actions.ts"use server";import { updateTag } from "next/cache";import { redirect } from "next/navigation";export async function createPost(formData: FormData) { const title = String(formData.get("title") ?? "").trim(); if (!title) throw new Error("Title is required"); await db.posts.insert({ title }); updateTag("posts"); // read-your-own-writes redirect("/blog");}revalidateTag uses stale-while-revalidate semantics: stale content is served immediately while fresh content is fetched in the background. It works in Server Actions and Route Handlers, which makes it the right tool for webhooks:
// app/api/revalidate/route.tsimport { revalidateTag } from "next/cache";import { NextResponse } from "next/server";export async function POST(request: Request) { const secret = request.headers.get("x-webhook-secret"); if (secret !== process.env.REVALIDATE_SECRET) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } revalidateTag("posts", "max"); return NextResponse.json({ revalidated: true });}A good CMS setup combines a long lifetime (cacheLife("max")) with tags and a webhook. Content stays cached until the CMS announces a change, so you avoid pointless time-based revalidation.
Prefer tags over revalidatePath when you can. Tags are precise, while paths can invalidate more than you intended.
Common mistakes
- Using
use cachewithout a lifetime. You get the implicit default profile, which may not match your intent. - Caching per-user data in a shared entry. If user-specific data is read inside a cached scope without being part of the key, it can be served to the wrong person. Always pass identifying values as arguments, or use the private variant.
- Calling
cookies()orheaders()insideuse cache. Runtime APIs belong outside the cached scope. Read them in a parent and pass the value down. - Using
Date.now(),Math.random()ornew Date()while prerendering. These are non-deterministic. Move them behind Suspense or compute them inside a cached scope when a frozen value is acceptable. - No Suspense boundary around request-time reads. This is the most common source of blocking-route errors.
- Invalidating by path when a tag would do. It over-invalidates and hides which data is actually stale.
A repeatable pattern for API data
- Write a small data function per resource in
lib/withuse cache, an explicitcacheLifeand acacheTag. - Validate the response shape and throw on non-OK responses so errors reach an error boundary instead of being cached.
- Render those functions from Server Components. Put request-time reads in separate components inside
<Suspense>. - After mutations, call
updateTag(read-your-own-writes) orrevalidateTag(background refresh). - Document, next to each data function, which strategy applies: static, cached with a lifetime, or streamed.
Client-side caching is a different layer
Server caching does not replace client caching. If a component needs live-updating data in the browser (polling, optimistic updates, infinite scroll), use a client library such as TanStack Query for that data, and keep server-cached data for initial, shareable content. Avoid fetching the same resource through both layers without a reason, since you then have two caches to invalidate.
Testing and verification
- Run
next buildand read the route output: static shell routes and partially prerendered routes are marked differently, and blocking-route errors fail the build. - In development, use the overlay insights to find uncached reads that are not wrapped in Suspense.
- Verify invalidation by changing data, calling the Server Action or webhook, and reloading. With
updateTagthe change should appear immediately; withrevalidateTagit may appear on the next request. - Add a test around your data functions that asserts they throw on non-OK API responses, so bad responses never get cached.
Production considerations
Cache storage differs between environments. In-memory caches do not survive across serverless invocations or multiple instances, so if you self-host more than one instance, plan for a shared cache handler. Set cacheLife thoughtfully for content that changes often, and monitor your API's request volume after launch to confirm that caching is actually reducing load.
Best practices
- Make caching explicit and local to the data it describes.
- Pair every
use cachewithcacheLifeand, when you will invalidate it,cacheTag. - Keep request-specific reads outside cached scopes.
- Wrap runtime reads in Suspense with meaningful fallbacks.
- Prefer tag-based invalidation and secure any webhook that triggers it.
Conclusion
Cache Components trade implicit magic for explicit contracts. You decide what is static, what is cached and for how long, and what streams, and the framework enforces it with clear errors instead of silent behavior. Start with one data function and one Suspense boundary, confirm the behavior in a production build, and then apply the same pattern route by route.
Frequently asked questions
+What does the use cache directive actually cache?
It caches the return value of an async function or component. The function's arguments and any values it captures from parent scopes become part of the cache key, so different inputs produce separate cache entries.
+How is Cache Components different from the old Next.js caching model?
In the previous model, fetch calls and route segments were cached or dynamic by default depending on configuration. With Cache Components you opt in explicitly with use cache, everything else is either prerendered or streamed behind Suspense, and you describe lifetimes with cacheLife.
+When should I use revalidateTag and when updateTag?
Use revalidateTag for stale-while-revalidate behavior where a slightly delayed update is fine, such as blog posts or catalogs. Use updateTag inside a Server Action when the user must immediately see their own change (read-your-own-writes).
+Why do I get a blocking-route or Suspense error when I read cookies()?
Runtime APIs such as cookies, headers, params and searchParams depend on the incoming request, so they cannot be part of the prerendered shell. Wrap the component that reads them in a Suspense boundary so the rest of the page can still be prerendered.
+Can I cache data that depends on the current user?
Yes, but be deliberate. Read the user value in an uncached component, pass it as an argument to the cached function so it becomes part of the cache key, or use the private cache variant for data that must never be shared between users.
+Why does Date.now() or Math.random() break my cached page?
Non-deterministic values change on every call, so they cannot be frozen into a prerendered result. Move them into a component that streams at request time, or compute them inside a cached scope when a stable value is acceptable.
+Does TanStack Query or SWR conflict with Next.js caching?
They cache in different places. Next.js caches on the server (and in prefetched payloads), while TanStack Query caches in the browser. Keep one source of truth per resource and avoid fetching the same data both ways unless you hydrate the client cache from the server.