Lesson 11 of 27Full-stack
Data Fetching and Caching
Fetch data in Server Components, avoid waterfalls, and cache it with `use cache`, cacheLife and cache tags.
In the React course's Data Fetching you loaded data in the browser and handled loading and race conditions by hand. Here the fetch moves to the server, and the new question is caching. Most performance bugs in Next.js apps are data bugs: a waterfall of awaits that makes every page slow, or a cache that serves yesterday's prices. Next.js 16 makes caching explicit: nothing is cached unless you say so, and the build tells you when a page is blocked on uncached data. Learn the handful of APIs here and you control exactly what is fresh, what is fast, and when it refreshes.
Fetching in Server Components
A Server Component can be async, so fetching data is just await:
import { db } from "@/db";
export default async function BlogPage() {
const res = await fetch("https://api.example.com/featured");
const featured: { id: string; title: string }[] = await res.json();
const posts = await db.query.posts.findMany({ orderBy: (p, { desc }) => desc(p.publishedAt) });
return (
<>
<h2>Featured</h2>
<ul>{featured.map((f) => <li key={f.id}>{f.title}</li>)}</ul>
<h2>Latest</h2>
<ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>
</>
);
}Any async source works: fetch, an ORM like Drizzle or Prisma, a file read. Two defaults to remember: fetch is not cached by default, and an await blocks everything after it in that component.
Waterfalls and how to avoid them
Two independent awaits in a row run one after the other. Start them together instead:
Press Run (⌘ Enter) to see what happens.Sequential fetching is right only when the second request needs the first one's result (fetch the artist, then their playlists by artist.id). Even then, wrap the dependent part in <Suspense> so the first result can show while the second loads.
Request memoization
In a component tree, the layout, the page and generateMetadata might all need the current user. You do not have to fetch once and drill props. Within a single render pass (one request), identical fetch calls are memoized: the request runs once and every caller shares the result.
For non-fetch data, such as an ORM query, wrap the function in React.cache:
import { cache } from "react";
import { db } from "@/db";
export const getUser = cache(async (id: string) => {
return db.query.users.findFirst({ where: (u, { eq }) => eq(u.id, id) });
});Memoization is per request only. The next visitor's request starts empty. It removes duplicate work inside one render; it is not a cache across users. Here is the idea in plain TypeScript:
Press Run (⌘ Enter) to see what happens.What does this print?
let calls = 0;
const seen = new Map<string, number>();
const get = (k: string) => { if (!seen.has(k)) { calls++; seen.set(k, k.length); } return seen.get(k); };
get("a"); get("bb"); get("a"); get("bb"); get("ccc");
console.log(calls);Static or dynamic: runtime data
Some data only exists when a real request arrives. Next.js calls these runtime APIs:
cookies()andheaders()fromnext/headers- the
searchParamsprop params, unless the value was listed bygenerateStaticParamsat build timeconnection()fromnext/server, which explicitly says "wait for a request" (use it beforeMath.random()orDate.now()when you want a new value per request)
With Cache Components on (cacheComponents: true, the default for new apps), a component that uses runtime data or uncached I/O must sit inside a <Suspense> boundary, or next build fails and names the route. That rule guarantees every page still has a prerendered static shell.
import { Suspense } from "react";
import { cookies } from "next/headers";
async function Greeting() {
const name = (await cookies()).get("name")?.value ?? "there";
return <p>Welcome back, {name}</p>;
}
export default function DashboardPage() {
return (
<>
<h1>Dashboard</h1> {/* static: in the shell */}
<Suspense fallback={<p>Loading...</p>}>
<Greeting /> {/* runtime: streams in per request */}
</Suspense>
</>
);
}<Suspense> does not make anything dynamic by itself. It only marks where a fallback can go while request-time work finishes.
await fetch(url) at the top level with no use cache and no Suspense. What happens at next build?Caching with "use cache"
When data is the same for everyone and can be a little stale, cache it. Add the "use cache" directive at the top of an async function or component:
import { cacheLife, cacheTag } from "next/cache";
import { db } from "@/db";
export async function getProducts(category: string) {
"use cache";
cacheLife("hours"); // how long it stays fresh
cacheTag("products"); // a label for on-demand invalidation
return db.query.products.findMany({ where: (p, { eq }) => eq(p.category, category) });
}How it works:
- Cache key. The build ID, the function's identity, and its arguments (plus any variables it captures from outer scopes) make up the key.
getProducts("mugs")andgetProducts("grinders")are separate entries. - Serialisable inputs and outputs. Arguments and return values must be serialisable (no class instances or plain functions). Returning JSX is fine, so you can cache whole components.
- No runtime APIs inside. A cached function cannot call
cookies()orheaders(). Read them outside and pass the value in as an argument, which then becomes part of the key. - Where it lands. At build time, cached output becomes part of the static shell. At runtime the default store is in memory on each server instance (ephemeral on serverless).
"use cache: remote"uses a shared store such as Redis, and"use cache: private"caches per user in the browser.
Put "use cache" at the top of a file to cache every export, or inside a component to cache its rendered UI.
cacheLife: how long is fresh?
cacheLife sets three timers. stale: how long the browser reuses the result without asking the server. revalidate: after this, the next request gets the cached value and triggers a background refresh. expire: after this with no traffic, the next request waits for fresh data.
| Profile | stale | revalidate | expire |
|---|---|---|---|
default | 5m | 15m | never |
seconds | 30s | 1s | 1m |
minutes | 5m | 1m | 1h |
hours | 5m | 1h | 1d |
days | 5m | 1d | 1w |
weeks | 5m | 1w | 30d |
max | 5m | 30d | 1y |
You can also pass an object: cacheLife({ stale: 60, revalidate: 300, expire: 3600 }). Very short lifetimes (the seconds profile, or expire under 5 minutes) are left out of the static shell and resolved per request instead.
Press Run (⌘ Enter) to see what happens.Where the cached copies live
The prerendered static shell (static markup plus use cache output from build time) comes straight from the CDN.
Revalidating on demand
Time-based freshness is a guess. Usually you know exactly when data changed: someone saved a product. Tag the cached data with cacheTag, then invalidate the tag after the change.
"use server";
import { revalidatePath, revalidateTag, updateTag } from "next/cache";
export async function saveProduct(formData: FormData) {
// ...check permissions, write to the database...
updateTag("products"); // the admin sees their own change on the next render
}
// in a webhook Route Handler from your CMS:
// revalidateTag("products", "max"); // serve stale, refresh in the background
// a whole page, when you do not know the tags:
// revalidatePath("/shop");| API | Where you can call it | Behaviour |
|---|---|---|
updateTag(tag) | Server Actions only | Expires the tag immediately. The next request waits for fresh data. For read-your-own-writes. |
revalidateTag(tag, "max") | Server Actions and Route Handlers | Marks the tag stale. Visitors get the old data while it refreshes in the background. |
revalidatePath(path) | Server Actions and Route Handlers | Invalidates everything cached for one route path. Prefer tags when you can. |
The single-argument revalidateTag(tag) is deprecated in Next.js 16; always pass a profile such as "max".
Pick the API for each situation.
Caching in older Next.js code
Before Cache Components, caching was configured per fetch and per route: fetch(url, { next: { revalidate: 60, tags: ["posts"] } }), fetch(url, { cache: "force-cache" }), export const revalidate = 60 or export const dynamic = "force-dynamic" in a page, and unstable_cache() for database calls. Next.js 13 and 14 cached fetch by default; Next.js 15 switched that off. You will meet all of these in existing projects. The concepts (tag, revalidate, stale-while-revalidate) are the same; Next.js 16 moves them into use cache, cacheLife and cacheTag.
Fresh, stale, or expired?
cacheLife gives a cached entry two server-side timers:
- before
revalidateseconds: fresh, served as is - from
revalidateuntilexpire: stale, served instantly while a background refresh runs - from
expireon: expired, the next request waits for fresh data
Write cacheState(ageSeconds, profile). profile is either a preset name or an object { revalidate, expire } where expire: null means never.
| Preset | revalidate | expire |
|---|---|---|
default | 900 | never |
seconds | 1 | 60 |
minutes | 60 | 3600 |
hours | 3600 | 86400 |
days | 86400 | 604800 |
weeks | 604800 | 2592000 |
max | 2592000 | 31536000 |
cacheState(120, "minutes") → "stale"
cacheState(30, "hours") → "fresh"Write your own React.cache
In a Server Component tree, getUser("1") might be called by the layout, the page, and generateMetadata. React.cache makes those calls share one result. Build the core of it.
Write memoize(fn). It returns a new function that:
- calls
fnonly the first time it sees a given set of arguments, and returns the stored result after that - treats arguments as equal when
JSON.stringify(args)is equal - stores whatever
fnreturns, including a Promise, so two calls made at the same moment share one in-flight request
let calls = 0;
const getUser = memoize(async (id: string) => { calls++; return { id }; });
await Promise.all([getUser("1"), getUser("1"), getUser("2")]);
calls // 2- request memoization
- Deduplicating identical
fetch(orReact.cache) calls within a single render pass, so data is fetched once per request. - use cache
- A directive that caches an async function's or component's output, keyed by its arguments, across requests.
- cacheLife
- Sets a cached entry's
stale,revalidateandexpiretimes, using a preset likehoursor a custom object. - cacheTag
- Labels cached data so it can be invalidated later with
updateTagorrevalidateTag. - runtime API
- Something only known per request, like
cookies(),headers()orsearchParams. It must be read outside cached scopes, inside Suspense. - updateTag
- Immediately expires a cache tag from a Server Action, so the next render shows fresh data (read-your-own-writes).