Skip to content
Derar Sattouf

Next.js Server Components and Caching: Data Fetching Patterns

Updated Next.js & frontend

Next.js Server Components and Caching: Data Fetching Patterns

The Next.js App Router changed where data fetching lives. Instead of getServerSideProps and client-side useEffect fetches, components run on the server, await data directly, and stream HTML to the browser. Done well, that gives fast pages with small JavaScript bundles. Done poorly, it gives request waterfalls, accidentally dynamic pages, confusing stale data, and client bundles bloated with code that should have stayed on the server.

Caching is the part that has changed most. Next.js 15 made fetch uncached by default, and Next.js 16 introduced Cache Components: an opt-in model built around the use cache directive, cacheLife, cacheTag, updateTag and revalidateTag, where pages are assembled from a static shell, cached pieces and streamed dynamic pieces. The examples target Next.js 16, the version this site runs on, with Cache Components on. The previous model gets its own section near the end for apps that have not migrated. Names and defaults in this area still evolve, so check the docs that ship with your installed version (they are in node_modules/next/dist/docs/).

Server Components are the default. Add "use client" only for interactivity, browser APIs and client state, and push it to the leaves of the tree. Fetch where the data is used, and deduplicate repeated lookups with React.cache rather than prop drilling. Avoid waterfalls: start independent work together with Promise.all, and wrap slow or runtime-dependent parts in Suspense so they stream.

With Cache Components enabled (cacheComponents: true), uncached async work and runtime APIs (cookies, headers, searchParams) must sit inside Suspense, or be cached with use cache. Everything else is prerendered into the static shell. Cache with intent: use cache plus cacheLife for lifetime and cacheTag for invalidation, and never put per-user data in a shared cache unless the user is part of the cache key. After a mutation, call updateTag (read-your-own-writes) or revalidateTag(tag, "max") (stale-while-revalidate) from a Server Action.

Treat Server Actions like public endpoints: authenticate, validate and authorize inside each one. And don't leak data: pass minimal DTOs to Client Components, and use server-only for modules that must never ship to the browser.

The mental model

Request -> Server renders the React tree
            |- Server Components: run only on the server, can await data, ship no JS
            |- Client Components: render on the server once, then hydrate in the browser
         -> HTML + RSC payload streamed to the browser

With Cache Components, the render is split into three kinds of output:
   static shell   : synchronous work and cached (use cache) output, prerendered
   cached dynamic : use cache results, revalidated by lifetime or tag
   streamed       : uncached async work and runtime APIs, inside Suspense, per request

Consequences:

  • A Server Component can query a database, read secrets and import heavy libraries without touching the client bundle.
  • Props crossing from a Server to a Client Component must be serializable (no functions or class instances). Server Actions are the exception.
  • Once a file has "use client", everything it imports becomes client code. Keep that boundary small.
// app/products/page.tsx (Server Component, no directive needed)
import { getProducts } from "@/lib/data";
import { AddToCartButton } from "./add-to-cart-button"; // client leaf

export default async function ProductsPage() {
  const products = await getProducts(); // direct data access
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          {p.name} ${p.price}
          <AddToCartButton productId={p.id} />
        </li>
      ))}
    </ul>
  );
}
// app/products/add-to-cart-button.tsx
"use client";
import { useTransition } from "react";
import { addToCart } from "./actions";

export function AddToCartButton({ productId }: { productId: string }) {
  const [pending, start] = useTransition();
  return (
    <button disabled={pending} onClick={() => start(() => addToCart(productId))}>
      {pending ? "Adding..." : "Add to cart"}
    </button>
  );
}

Remember that in recent versions params and searchParams are promises, so page components await them.

Enabling Cache Components

In Next.js 16 the new caching model is controlled by a config flag. New apps created with the recommended create-next-app defaults already have it on; for an existing app:

// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true, // set explicitly; see the docs for the migration note
};

export default nextConfig;

What changes when cacheComponents is on:

  1. Components are prerendered by default. Synchronous work and imports go into the static shell.
  2. Anything that needs request-time information or uncached async work must be either cached with use cache or wrapped in Suspense. If you forget, the dev overlay reports a "blocking route" insight with a fix suggestion instead of silently making the whole route dynamic.
  3. The older route segment configs such as export const dynamic, revalidate and fetchCache give way to use cache, cacheLife and Suspense. Check the migration guide in the docs if you are upgrading.

Fetch where you use it and deduplicate

In Server Components you can fetch in the component that needs the data. When several components need the same record, wrap the data function in React's cache, which memoizes per request:

// lib/data.ts
import { cache } from "react";
import { db } from "./db";

export const getUser = cache(async (id: string) => {
  return db.user.findUnique({ where: { id } });
});
async function Header({ id }: { id: string }) {
  const u = await getUser(id);
  return <h1>{u?.name}</h1>;
}
async function Sidebar({ id }: { id: string }) {
  const u = await getUser(id);
  return <aside>{u?.plan}</aside>;
}
// getUser(id) runs once per request even though two components call it

React.cache is per-request deduplication, not cross-request caching. They are different tools: cache avoids duplicate work inside one render, use cache persists a result across requests.

Eliminate waterfalls

A waterfall is sequential awaiting of independent work:

// SLOW: total = a + b + c
const user = await getUser(id);
const orders = await getOrders(id);
const recs = await getRecommendations(id);

Start them together:

// FAST: total = max(a, b, c)
const [user, orders, recs] = await Promise.all([
  getUser(id),
  getOrders(id),
  getRecommendations(id),
]);

Better still, do not make the page wait for the slowest piece. Stream it:

import { Suspense } from "react";

export default async function Dashboard({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;

  return (
    <>
      <h1>Dashboard</h1>
      <Suspense fallback={<Skeleton rows={1} />}>
        <Greeting userId={id} />
      </Suspense>
      <Suspense fallback={<Skeleton rows={5} />}>
        <RecentOrders userId={id} />
      </Suspense>
      <Suspense fallback={<Skeleton rows={3} />}>
        <Recommendations userId={id} />
      </Suspense>
    </>
  );
}

async function RecentOrders({ userId }: { userId: string }) {
  const orders = await getOrders(userId);
  return <OrderTable orders={orders} />;
}

The shell (heading, layout, fallbacks) appears immediately; each boundary fills in as its data resolves. Put boundaries around independent slow sections, and give fallbacks the same dimensions as the final content to prevent layout shift.

When a child's data does not depend on the parent's await, start the promise early and pass it down. A Client Component can unwrap it with React's use:

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const ordersPromise = getOrders(id); // start now, do not await
  return (
    <Suspense fallback={<Skeleton rows={5} />}>
      <Orders promise={ordersPromise} />
    </Suspense>
  );
}

Caching with use cache

Put the use cache directive at the top of an async function or component to cache its return value. Arguments and captured values become part of the cache key. Pair every directive with a cacheLife; without one, the implicit default profile applies.

Data-level and UI-level caching

// lib/data.ts: data-level
import { cacheLife, cacheTag } from "next/cache";

export async function getProduct(slug: string) {
  "use cache";
  cacheLife("hours");
  cacheTag(`product:${slug}`, "products");
  return db.product.findUnique({ where: { slug } });
}
// app/blog/page.tsx: UI-level
import { cacheLife, cacheTag } from "next/cache";

async function BlogPosts() {
  "use cache";
  cacheLife("hours");
  cacheTag("posts");

  const res = await fetch("https://api.example.com/posts");
  const posts: { id: string; title: string }[] = await res.json();
  return (
    <ul>
      {posts.map((p) => (
        <li key={p.id}>{p.title}</li>
      ))}
    </ul>
  );
}

Put the directive at the top of a file to cache every exported function in it.

Built-in lifetime profiles

Per the Next.js 16 docs, cacheLife accepts a profile name, or an object with stale, revalidate and expire in seconds:

Profilestalerevalidateexpire
default5m15mnever
seconds30s1s60s
minutes5m1m1h
hours5m1h1d
days5m1d1w
weeks5m1w30d
max5m30d1y
"use cache";
cacheLife({ stale: 3600, revalidate: 7200, expire: 86400 });

Very short-lived caches (the seconds profile, revalidate: 0, or expire under five minutes) are excluded from prerendering and become dynamic holes, so do not use them expecting a static shell.

What is allowed inside a cached scope

You cannot read cookies(), headers() or searchParams directly inside a use cache function. Read them outside, extract the value you need, and pass it as an argument so it becomes part of the cache key:

import { cookies } from "next/headers";
import { Suspense } from "react";

export default function Page() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ProfileContent />
    </Suspense>
  );
}

async function ProfileContent() {
  const session = (await cookies()).get("session")?.value; // runtime API, outside the cache
  return <CachedProfile sessionId={session} />;
}

async function CachedProfile({ sessionId }: { sessionId?: string }) {
  "use cache";
  cacheLife("minutes");
  // sessionId is part of the cache key
  const data = await fetchUserData(sessionId);
  return <div>{data.name}</div>;
}

There are also variants for special cases: use cache: private gives a lifetime to functions that read runtime data directly (so results can join prefetches), and use cache: remote stores entries in a shared remote cache handler, which is important on serverless where the default in-memory cache does not persist across instances. Both come with trade-offs; read their reference pages before using them. Cached entries are also tied to the build or deployment ID, so they do not carry over to a new deploy.

Randomness and timestamps

Math.random(), Date.now() and crypto.randomUUID() produce different values per call, so Cache Components requires you to choose. Either defer to request time with await connection() inside a Suspense boundary, or cache the result so everyone sees the same value until revalidation.

import { connection } from "next/server";

async function RequestId() {
  await connection();
  return <p>Request ID: {crypto.randomUUID()}</p>;
}

Decide your strategy per data type

DataStrategyExample
Truly staticPrerendered into the shell, no async workMarketing copy, docs
Changes occasionallyuse cache plus a long cacheLife plus tags, invalidated by webhook or actionCMS content, product catalog
Changes on a scheduleuse cache with a short cacheLife profileExchange rates, leaderboards
Per-userRuntime API in Suspense, or cache keyed by userCart, dashboard, auth state
RealtimeUncached inside Suspense, or client-side subscriptionLive prices, chat

For content from a CMS, the docs recommend tagging data with a long lifetime such as max to keep it in the static shell and calling revalidateTag from a webhook when content changes. This avoids needless recomputation.

A common surprise before Cache Components was a single cookies() call in a shared layout making every page dynamic. The new model contains this: put the cookie read in a small component inside Suspense, and the rest of the page stays static and cached.

export default function ProductPage() {
  return (
    <>
      <ProductDetails /> {/* cached */}
      <Suspense fallback={<span>...</span>}>
        <UserGreeting /> {/* reads cookies(): streams at request time */}
      </Suspense>
    </>
  );
}

Mutations: Server Actions and revalidation

Server Actions are server functions callable from forms or client code. Under the hood they are public HTTP endpoints, so treat them like API routes.

// app/products/actions.ts
"use server";
import { z } from "zod";
import { updateTag } from "next/cache";
import { auth } from "@/lib/auth";

const Input = z.object({ id: z.string().uuid(), name: z.string().min(1).max(120) });

export async function renameProduct(formData: FormData) {
  const session = await auth();
  if (!session?.user) throw new Error("Unauthorized"); // authenticate

  const parsed = Input.safeParse(Object.fromEntries(formData)); // validate
  if (!parsed.success) return { error: parsed.error.flatten() };

  const product = await db.product.findUnique({ where: { id: parsed.data.id } });
  if (!product || product.ownerId !== session.user.id) {
    throw new Error("Forbidden"); // authorize per resource
  }

  await db.product.update({ where: { id: product.id }, data: { name: parsed.data.name } });

  updateTag(`product:${product.slug}`); // read-your-own-writes
  return { ok: true };
}

Choosing the invalidation function

FunctionWhereBehaviorUse when
updateTag(tag)Server Actions onlyExpires immediately; the user sees their changeA user just edited something and must see it
revalidateTag(tag, "max")Server Actions and Route HandlersStale-while-revalidate; serves stale while refreshingBackground updates, webhooks, slight delay is fine
revalidatePath(path)Server Actions and Route HandlersInvalidates a route's cached dataYou do not know the tags; prefer tags when possible
refresh()Server Actions onlyRefreshes the client router for uncached dataUpdating dynamic UI not covered by tags

In Next.js 16 the single-argument revalidateTag(tag) is deprecated; pass a profile such as "max" as the second argument, or use updateTag in Server Actions. Tags are case-sensitive and limited to 256 characters.

Also use useActionState for form state and useOptimistic for instant feedback:

"use client";
import { useActionState } from "react";
import { renameProduct } from "./actions";

export function RenameForm({ id }: { id: string }) {
  const [state, action, pending] = useActionState(
    async (_prev: unknown, fd: FormData) => renameProduct(fd),
    null,
  );
  return (
    <form action={action}>
      <input type="hidden" name="id" value={id} />
      <input name="name" required />
      <button disabled={pending}>Save</button>
      {state && "error" in state && <p role="alert">Fix the highlighted fields.</p>}
    </form>
  );
}

For route handlers and external clients, see the Next.js API tutorial.

Security and data hygiene

  • Do not pass entire database rows to Client Components. Everything you pass is serialized into the page and visible in the browser. Map to a minimal object.
// BAD: leaks passwordHash, email and internal flags to the client payload
<ProfileClient user={user} />

// GOOD
<ProfileClient user={{ id: user.id, name: user.name, avatarUrl: user.avatarUrl }} />
  • Add import "server-only" to modules that must never reach the client (database clients, secrets). The build fails if a client file imports them.
  • Do authorization in your data access layer (for example getOrderForUser(userId, orderId)), not only in layouts. Layouts do not re-render on every navigation, so layout-only checks can be bypassed.
  • Environment variables without the NEXT_PUBLIC_ prefix stay on the server. Never put secrets in prefixed variables.
  • With Cache Components, think carefully about auth: cached output is shared across users unless the user is in the cache key. The docs have a dedicated guide on authentication with Cache Components.
  • Keep dependencies and the framework current; see the Next.js upgrade and security checklist.

Lab: convert a slow dashboard

  1. Baseline. Run next build and note which routes are static, partially prerendered or dynamic. Record Largest Contentful Paint and Time to First Byte.
  2. Find waterfalls. Search for consecutive await lines that do not depend on each other and convert them to Promise.all.
  3. Split by volatility. List each block on the page: static, cached, per-user, realtime.
  4. Cache the stable blocks. Add use cache, cacheLife and cacheTag to catalog and content components.
  5. Isolate the personal blocks. Move cookies() and headers() reads into small components and wrap them in Suspense with fallbacks that match their final size.
  6. Wire invalidation. In each Server Action that mutates data, call updateTag or revalidateTag for the affected tags.
  7. Re-measure. Compare TTFB, LCP and INP. See Core Web Vitals and INP for Next.js. Prefetch behavior can add further gains; see Speculation rules and instant navigation.
  8. Guard SEO. Confirm metadata and structured data still render in the static HTML; see the Next.js technical SEO checklist.

The previous caching model

If cacheComponents is off (the default for existing apps), the rules differ:

  • fetch requests are not cached by default; opt in with cache: "force-cache" or next: { revalidate, tags }.
  • Non-fetch functions are cached with unstable_cache.
  • Route segment config controls rendering: export const revalidate = 60, dynamic, and so on.
  • Reading cookies(), headers() or searchParams makes the whole route dynamic.
// Previous model
const res = await fetch(`https://api.example.com/products/${slug}`, {
  next: { revalidate: 3600, tags: [`product:${slug}`] },
});

The docs include a "Caching and Revalidating (Previous Model)" guide and a migration guide. Migrate deliberately: enable the flag on a branch, fix each blocking-route insight, and re-test per-user pages for cache leaks.

Where this usually goes wrong

MistakeWhy it hurtsFix
"use client" at the top of a layout or pageDrags the whole subtree to the clientPush to leaf components
Sequential awaits for independent dataSlow responsesPromise.all or separate Suspense boundaries
Fetching in useEffect what the server could streamSpinners, waterfalls, bigger bundlesFetch in Server Components
Reading cookies() outside Suspense with Cache ComponentsBlocking-route error or slow shellIsolate in a small component inside Suspense
Caching per-user results in a shared cacheData leaks between usersInclude the user in the cache key or do not cache
Forgetting invalidation after a mutationStale UIupdateTag or revalidateTag(tag, "max")
Single-argument revalidateTag(tag)Deprecated behaviorAdd a profile or use updateTag
Passing full DB rows to Client ComponentsData exposureMap to a minimal object
Calling your own Route Handler from a Server ComponentNeedless HTTP hopCall the data function directly
Putting use cache on a function that reads cookies()Error, and wrong sharing semanticsRead outside, pass the value in
Assuming in-memory cache persists on serverlessCold cachesConsider use cache: remote

When not to use these patterns

Highly interactive, client-state-heavy apps (editors, dashboards with constant local state) will have large client islands. Server Components still help for the shell, but do not force everything server-side. Tiny static sites may not need Cache Components complexity at all, and per-request unique content gains little from caching, so render it dynamically inside Suspense.

Realtime data (chat, trading) belongs in streaming transports or client subscriptions, not in use cache. Heavy business logic or multi-client APIs often deserve a separate backend.

Troubleshooting

SymptomLikely causeFix
Dev overlay "blocking route"Uncached async or runtime API outside SuspenseWrap in Suspense or cache with use cache
Data never updatesMissing tag or no invalidation callAdd cacheTag and call updateTag or revalidateTag
Users see each other's dataShared cache without user in the keyPass the user ID as an argument or avoid caching
Cache not reused in production on serverlessIn-memory cache per instanceUse use cache: remote or a cache handler
Error about cookies() inside use cacheRuntime API in cached scopeRead outside and pass as argument
Stale content after deployCache keyed by buildExpected; entries do not carry across deploys
Whole route dynamic unexpectedlyCache Components off and a runtime API in a layoutEnable the flag or isolate the read
Hydration mismatch with time or random valuesNon-deterministic renderUse connection() plus Suspense, or cache the value

Questions that come up

Do I have to enable Cache Components? No, it is opt-in via cacheComponents: true for existing apps. The docs say it becomes the standard model going forward, so new work benefits from learning it.

React.cache or use cache? React.cache deduplicates within one request. use cache persists across requests with a lifetime and tags. Use both for different jobs.

Is unstable_cache still needed? It belongs to the previous model; with Cache Components use use cache.

What replaced route segment revalidate? cacheLife inside a use cache scope. Check the migration guide for the exact mapping.

Where do middleware rules go now? Next.js 16 uses a proxy file convention for request interception; see the docs page on Proxy for the current name and behavior.

Sources and docs