Skip to content

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.

18 min read0/4 questions

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:

app/blog/page.tsx
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:

TypeScriptwaterfall.ts
const fakeFetch = (name: string, ms: number) => new Promise<string>((r) => setTimeout(() => r(name), ms)); let t = Date.now();const artist = await fakeFetch("artist", 300);const albums = await fakeFetch("albums", 300);console.log(`sequential: ${Date.now() - t}ms`); t = Date.now();const [a, b] = await Promise.all([fakeFetch("artist", 300), fakeFetch("albums", 300)]);console.log(`parallel: ${Date.now() - t}ms`);
Output
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:

lib/user.ts
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:

TypeScriptmemo.ts
let queries = 0;const store = new Map<string, Promise<{ id: string }>>(); function getUser(id: string) { if (!store.has(id)) { queries++; store.set(id, Promise.resolve({ id })); } return store.get(id)!;} // layout, page and generateMetadata all ask for the same userawait Promise.all([getUser("7"), getUser("7"), getUser("7")]);console.log("database queries:", queries);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

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);
Need a nudge? Hints walk you through it.

Static or dynamic: runtime data

Some data only exists when a real request arrives. Next.js calls these runtime APIs:

  • cookies() and headers() from next/headers
  • the searchParams prop
  • params, unless the value was listed by generateStaticParams at build time
  • connection() from next/server, which explicitly says "wait for a request" (use it before Math.random() or Date.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.

app/dashboard/page.tsx
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.

Quick check
In Next.js 16 with Cache Components, a page calls await fetch(url) at the top level with no use cache and no Suspense. What happens at next build?
Need a nudge? A hint rules out a wrong answer.

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:

lib/products.ts
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") and getProducts("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() or headers(). 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.

Quick check
You want to cache a user's recommendations, so you write a use cache function that calls cookies() to read the user ID. What is the recommended fix for the resulting error?
Need a nudge? A hint rules out a wrong answer.

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.

Profilestalerevalidateexpire
default5m15mnever
seconds30s1s1m
minutes5m1m1h
hours5m1h1d
days5m1d1w
weeks5m1w30d
max5m30d1y

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.

TypeScriptcache-state.ts
const profiles: Record<string, [revalidate: number, expire: number]> = { minutes: [60, 3600], hours: [3600, 86400], days: [86400, 604800],}; function state(ageSeconds: number, profile: string) { const [revalidate, expire] = profiles[profile]; if (ageSeconds < revalidate) return "fresh: serve it"; if (ageSeconds < expire) return "stale: serve it, refresh in background"; return "expired: wait for fresh data";} console.log(state(30, "minutes"));console.log(state(600, "minutes"));console.log(state(7200, "minutes"));
Output
Press Run (⌘ Enter) to see what happens.

Where the cached copies live

One request through the cache layers
Browser: client cache (stale)Browserclient cache (stale)CDN: static shellCDNstatic shellNext.js server: renders holesNext.js serverrenders holesuse cache store: memory or remoteuse cache storememory or remotePostgresPostgresGET /shopstream holeslookupSQL

The prerendered static shell (static markup plus use cache output from build time) comes straight from the CDN.

1/5

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.

app/admin/actions.ts
"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");
APIWhere you can call itBehaviour
updateTag(tag)Server Actions onlyExpires the tag immediately. The next request waits for fresh data. For read-your-own-writes.
revalidateTag(tag, "max")Server Actions and Route HandlersMarks the tag stale. Visitors get the old data while it refreshes in the background.
revalidatePath(path)Server Actions and Route HandlersInvalidates 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".

Match the pairs0/4 matched

Pick the API for each situation.

Choose an item, then its match on the other side.
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.

ChallengeEasy

Fresh, stale, or expired?

cacheLife gives a cached entry two server-side timers:

  • before revalidate seconds: fresh, served as is
  • from revalidate until expire: stale, served instantly while a background refresh runs
  • from expire on: 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.

Presetrevalidateexpire
default900never
seconds160
minutes603600
hours360086400
days86400604800
weeks6048002592000
max259200031536000
cacheState(120, "minutes")  → "stale"
cacheState(30, "hours")     → "fresh"
TypeScript
type Profile = string | { revalidate: number; expire: number | null }; function cacheState(age: number, profile: Profile): "fresh" | "stale" | "expired" { return "fresh";}
ChallengeMedium

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 fn only 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 fn returns, 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
TypeScript
function memoize<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R { // Keep a Map from argument key to result. return fn;}
Key terms
request memoization
Deduplicating identical fetch (or React.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, revalidate and expire times, using a preset like hours or a custom object.
cacheTag
Labels cached data so it can be invalidated later with updateTag or revalidateTag.
runtime API
Something only known per request, like cookies(), headers() or searchParams. 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).