Skip to article content
FrontendXLesson 06 / 20

Data Fetching in Server Components

A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.

intermediate · about 50 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Fetch data in server components with fetch and with non-fetch clients such as ORMs.
  • Avoid waterfalls by parallelizing independent reads and deduplicating shared reads with React cache().
  • Apply the version-qualified fetch caching defaults of Next.js 15 and 16.

Overview

#

Fetch where you render

In the App Router you fetch inside the server component that uses the data. There is no getServerSideProps layer to route through:

snippet.tsx
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const [product, reviews] = await Promise.all([
    getProduct(id),
    getReviews(id),
  ]);
  return <ProductView product={product} reviews={reviews} />;
}

The default is uncached since Next.js 15

Version-qualified behavior: before Next.js 15, fetch requests were cached by default. Since Next.js 15, an unconfigured fetch is not cached; it behaves like cache: 'no-store'. Opt in explicitly per call with { cache: 'force-cache' } for indefinite caching, or { next: { revalidate: 60 } } for time-based revalidation, or { next: { tags: ['products'] } } for tag-based on-demand invalidation. Route-level overrides exist through the fetchCache segment config, but per-call explicitness is the maintainable default.

Calls through database clients and ORMs are never auto-cached by Next.js regardless of version. Cache them deliberately with React cache() for per-request dedupe, unstable_cache for cross-request caching in the previous model, or use cache under Cache Components.

Waterfalls and dedupe

A waterfall happens when a read awaits another read it does not actually need: const user = await getUser(); const posts = await getPosts(user.id); is legitimate, but two independent awaits written sequentially waste the first latency. Start independent promises together with Promise.all, or start them without awaiting and pass the promises into Suspense-wrapped children.

When the same read is needed by both generateMetadata and the page, wrap it in React's cache() from the react import. That dedupes within one server render. It is per-request memoization, not a cross-request cache; do not confuse it with the Data Cache.

Client-side fetching still has a place

Data that must update live, depends on browser-only context, or belongs to a third-party widget can be fetched in client components with SWR or React Query. The App Router default is server fetching; reach for the client deliberately, not by habit.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    In Next.js 15 and 16, how many times does the external API get called when this page is requested twice in a row with no caching options? async function getData() { const res = await fetch('https://api.example.com/items'); return res.json(); } export default async function Page() { const data = await getData(); return <List items={data} />; }

    Choose the best answer
  2. Exercise 2Explain

    Explain the difference between React cache(), the Next.js Data Cache, and use cache, including which one survives across requests.

    Reveal the reference answer
    reference.text
    React cache() memoizes a function's result for the duration of one server render, so metadata and the page sharing a read execute it once per request; it never survives across requests. The Next.js Data Cache (fetch with force-cache, revalidate, or tags, and unstable_cache for non-fetch work) persists results across requests in the previous caching model, with time-based or on-demand invalidation. use cache under Cache Components is the current directive-based cross-request cache for components and functions, configured with cacheLife and invalidated with cacheTag-based APIs. Only the latter two survive across requests; React cache() is per-request.

    Authored expected output: Per-request memoization versus two cross-request caches, with their invalidation models.

    Three similarly named mechanisms with different scopes are the top source of caching bugs.

  3. Exercise 3Implement

    Rewrite this waterfall so the independent reads run in parallel, and keep the dependent read correct. const user = await getUser(id); const settings = await getSettings(); const orders = await getOrders(user.id);

    starter.tsx
    export default async function Page({ params }: { params: Promise<{ id: string }> }) {
      const { id } = await params;
      // TODO: parallelize without breaking the dependency
    }

    Reveal the reference answer
    reference.tsx
    export default async function Page({ params }: { params: Promise<{ id: string }> }) {
      const { id } = await params;
      const userPromise = getUser(id);
      const settingsPromise = getSettings();
      const user = await userPromise;
      const [settings, orders] = await Promise.all([settingsPromise, getOrders(user.id)]);
      return <Profile user={user} settings={settings} orders={orders} />;
    }
    
    // getUser and getSettings start together; getOrders starts after user resolves because it depends on user.id.

    Authored expected output: Total latency is max(getUser, getSettings) plus getOrders, not the sum of all three.

    Start promises early, await only where a real data dependency exists.

  4. Exercise 4Debug

    A team upgraded from Next.js 14 to 15 and their dashboard now shows stale-free data but the API is rate-limiting them from the traffic spike. What changed and what is the minimal fix for the reads that rarely change? const res = await fetch('https://api.example.com/catalog');

    starter.ts
    const res = await fetch('https://api.example.com/catalog');

    Reveal the reference answer
    reference.ts
    Next.js 15 changed the default fetch behavior from cached to uncached, so every request now hits the API. Minimal fix for stable reads: opt back in per call with await fetch(url, { cache: 'force-cache' }) for content that changes only on publish, or { next: { revalidate: 3600 } } for hourly freshness, and keep truly live reads uncached. The migration guide documents this default change.

    Authored expected output: Rate-limited reads drop after explicit caching is added to stable endpoints.

    The 15 default change is silent: no error, just more upstream traffic.

  5. Exercise 5Test

    Write a pure function planReads(graph: Record<string, string[]>) where keys are read names and values are the names each read depends on. It returns groups of reads that can execute together (levels). Assert on: a = [], b = [], c = ['a'], d = ['a', 'b'] giving levels [[a, b], [c, d]]; and a cycle a = ['b'], b = ['a'] throwing an error.

    starter.ts
    export function planReads(graph: Record<string, string[]>): string[][] {
      // TODO
    }

    Reveal the reference answer
    reference.ts
    export function planReads(graph: Record<string, string[]>): string[][] {
      const levels: string[][] = [];
      const placed = new Set<string>();
      const remaining = Object.keys(graph);
      while (remaining.length > 0) {
        const ready = remaining.filter((name) => graph[name].every((dep) => placed.has(dep)));
        if (ready.length === 0) throw new Error('Cyclic dependency detected');
        levels.push(ready);
        ready.forEach((name) => placed.add(name));
        for (const name of ready) {
          const idx = remaining.indexOf(name);
          remaining.splice(idx, 1);
        }
      }
      return levels;
    }
    
    // Each level is one Promise.all batch; the cycle check prevents an infinite loop.

    Authored expected output: Both assertions pass.

    Scheduling reads into dependency levels is exactly how you reason about waterfalls.

  6. Exercise 6Interview

    An interviewer asks: a product page needs product data, reviews, and recommendations, where reviews take 800 ms and recommendations 1200 ms. How do you render it fast? Give the rendering plan and the caching plan.

    Reveal the reference answer
    reference.text
    Rendering plan: fetch product and reviews in parallel with Promise.all since the header needs the product; render recommendations in a child server component wrapped in its own Suspense boundary so it streams in after the shell, with a skeleton fallback. Do not block the whole page on the slowest read. Caching plan: product data is stable, so cache it (force-cache or use cache with a tag keyed to the product) and invalidate on publish; reviews change often, so either short revalidate or uncached inside the Suspense boundary; recommendations are per-user or per-product ML output, so keep them request-time inside the boundary. State the version-qualified default: since Next.js 15 nothing is cached unless you opt in.

    Authored expected output: Parallel fetch, per-section Suspense, differentiated caching per data volatility.

    The answer connects data fetching, streaming and caching instead of treating them separately.

Common misconceptions

#
  • fetch is cached by default. Since Next.js 15 the default is uncached; force-cache or revalidate must be explicit. This is a frequent interview trap.
  • React cache() caches across requests. It memoizes within a single server render only; cross-request caching needs the Data Cache or use cache.
  • ORM queries are cached like fetch. Database clients are never auto-cached; they need cache(), unstable_cache or use cache.
  • Sequential awaits are always wrong. Only independent reads parallelize; dependent reads genuinely must await their input.

Follow-up practice

#
  • nextjs-caching-layers
  • nextjs-cache-components

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.