Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 09 / Stage 3

Data fetching in Server Components

Goal: Fetch data the way an async Server Component actually wants it fetched: in parallel instead of a waterfall, deduplicated within one render pass when two parts of a page need the same thing, and with a clean "not found" path — all against a local, simulated-latency data source (never a real network call), so every timing number in this part is reproducible. Built against Mandi Fresh, a Pune-based online grocery marketplace, and its product detail page. Time: ~6 h · Level: finished Stage 2 (the Server/Client boundary, Suspense/streaming) Verified against: Next.js 16.4.6 / React 19.3.0 (this repo's pinned version, see TOOLING.md), with cacheComponents: true — this install's default, confirmed in TOOLING.md and Part 5.

What you will learn

  • Two independent local data sources, each with its own simulated latency, read directly by await inside async Server Components
  • Why awaiting two unrelated sources one after another builds a waterfall — and why nothing about the code looks wrong
  • Fixing the waterfall with Promise.all, and measuring the real time saved with real curl timings, not an estimate
  • Why this install's cacheComponents: true forces both versions behind <Suspense> — and what the exact build-time error looks like if you forget
  • That Next.js's automatic fetch request memoization is a property of the patched global fetch, confirmed by reading this install's own patch-fetch.js — and that it does not apply to a plain local async function, which is exactly what this part's two data sources are
  • React's own cache(), used instead, to deduplicate a local function's calls within one render pass — verified by literally counting the calls
  • notFound() for a missing product, and a genuinely surprising thing this install does with the HTTP status code the first time an unlisted id is requested

Topics in this part

Practice

Every exercise adds a scratch route under harness/app/mandi/ (never inside _-prefixed folders — Next.js treats a leading underscore as a private folder, excluded from routing entirely; verified for real while building this part: app/mandi/_scratch/ex1/page.tsx 404ed even though the exact same file at app/mandi/scratch-ex1/page.tsx worked), runs a real command against it, and then removes what it added, restoring app/mandi/ to the exact state Part 9's README ends on. Copy the exact commands you ran and their real output into your own notes; do not type output from memory.

A note on next dev and this harness: only one next dev process is allowed per project at a time — starting a second one prints ⨯ Another next dev server is already running and refuses to start, even on a different port. If that happens, either reuse the server that's already running or wait for it to stop. next build and next start don't share this restriction.


Exercise 1: A third parallel source

Scenario: Mandi Fresh wants to add an estimated delivery time to the product page, from a third simulated service. What to do: Create app/mandi/scratch-ex1/page.tsx. Inside it, write a local getDelivery() that waits 300ms and returns a string, then build a page that reads reviews, stock, and delivery for "g1" all via one Promise.all, wrapped in <Suspense>. Curl it a few times and confirm the timing is close to the slowest of the three delays (400ms, reviews), not their sum.

Sample output (run for real against this course's harness):

$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/scratch-ex1   # warm-up
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/scratch-ex1
0.475s
0.477s
0.457s

💡 Hint: This is section 2's exact technique extended to three sources instead of two — Promise.all doesn't care how many promises you give it.


Exercise 2: cache() on a second module

Scenario: You want to prove section 4's finding generalizes — it isn't something special about stock.ts. What to do: Create app/mandi/scratch-ex2/page.tsx. Write a scratch fetchReviews() with its own cache()-based per-request counter (the same cache(() => ({ count: 0 })) pattern stock.ts uses), wrap it in cache() as getReviewsCached, then call getReviewsCached("g1") twice in one component and display the call count plus whether the two results are === the same object.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/mandi/scratch-ex2 | grep -o 'reviews calls:.*calls'
reviews calls: 1, a===b: true

💡 Hint: a === b being true is worth noticing on its own — cache() doesn't just skip the second call, it hands back the literal same object the first call produced.


Exercise 3: Two real components, not one function with two awaits

Scenario: Section 4's Panel function calls getStock twice itself. A real page is more likely to have two separate components (a badge, a warning banner) that each independently need the same data. What to do: Create app/mandi/scratch-ex3/page.tsx with two separate async function components, StockBadge and LowStockWarning, each independently calling getStock("g1") from lib/stock.ts. Combine them with Promise.all in a parent, then render the warehouse call count after both resolve. Confirm the count is still what you'd expect without cache().

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/mandi/scratch-ex3 | grep -oE '<li id="(badge|warning|calls)">[^<]*'
<li id="badge">In stock: 42 units
<li id="warning">Plenty in stock
<li id="calls">Warehouse calls this request: 2

💡 Hint: The number doesn't change from section 4's single-function version — what changes is that this shape is the realistic one: two independent pieces of UI, not one function awaiting the same thing twice on purpose.


Exercise 4: Trigger the real missing-<Suspense> build error

Scenario: You want this error in your own terminal, from your own mistake, not copied from the README. What to do: Create app/mandi/scratch-ex4/page.tsx as a page that directly awaits getReviews("g1") with no <Suspense> anywhere. Run next build and capture the real error. Delete the file and rebuild clean afterward — a build left in this broken state blocks everyone else using this harness.

Sample output (run for real against this course's harness):

$ npm run build
...
Error: Route "/mandi/scratch-ex4": Next.js encountered uncached or runtime data during prerendering.

`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.

Ways to fix this:
  - [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
  - [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
  - [block] Set `export const instant = false` to allow a blocking route
...
Export encountered an error on /mandi/scratch-ex4/page: /mandi/scratch-ex4, exiting the build.

After deleting the file:

$ npx next typegen && npm run build
...
✓ Generating static pages using 17 workers (60/60) in ...ms

💡 Hint: Deleting a scratch route leaves a stale reference in .next/dev/types/validator.ts that fails tsc on the next build — run npx next typegen first to regenerate it before rebuilding, or you'll chase a confusing, unrelated-looking type error.


Exercise 5: Timing with curl -w, not a separate timer

Scenario: Section 2 measured timing by wrapping curl in a Python timer. curl can time itself. What to do: Warm up /mandi/products/g4 and /mandi/products/g4/sequential with one request each, then measure both with curl -s -o /dev/null -w "%{time_total}s\n" instead of an external timer. Confirm the numbers land in the same ballpark as section 2's.

Sample output (run for real against this course's harness):

$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4   # warm-up, discarded
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4
0.424694s
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4/sequential   # warm-up, discarded
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4/sequential
0.777512s

💡 Hint: %{time_total} is curl's own measured wall-clock time for the whole request — one less moving part than spawning a separate process to read the clock before and after.


Exercise 6: cache() keys by argument, not just by function

Scenario: Section 4 only tested getStockCached with the same argument ("g1") twice. Prove it isn't globally memoizing "the function's one answer." What to do: Create app/mandi/scratch-ex6/page.tsx. Call getStockCached("g1"), then getStockCached("g2"), then getStockCached("g1") again, all in the same render pass, and display the warehouse call count.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/mandi/scratch-ex6 | grep -o 'calls: [0-9]*'
calls: 2

💡 Hint: 2, not 1 and not 3 — one real call for "g1", one real call for "g2" (a different cache key), and the second "g1" reuses the first call's result instead of triggering a third.


Exercise 7: Reproduce the cold-start 200 → warm 404 with a different id

Scenario: Part 9's README section 5 showed this with one specific made-up id (zzz). Prove it's a general behavior of unlisted dynamic params, not something special about that string. What to do: Run next build && next start on a fresh port. Pick an id you're confident has never been requested before (anything not g1–g4), request it once, check the status code, then request it again and check the status code a second time.

Sample output (run for real against this course's harness):

$ npm run build && npm run start -- -p PORT
...
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/products/exercise5-test   # first-ever request
HTTP/1.1 200 OK
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/products/exercise5-test   # second request, same id
HTTP/1.1 404 Not Found
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/products/exercise5-test   # third request
HTTP/1.1 404 Not Found

💡 Hint: If you see 200 on every request, you probably reused a next dev session or an id that was already requested earlier in this same next start process — the finding is specifically about the very first request to a given path since the server started, under a production build.


Next

Part 10: Caching with Cache Components

Show the solutions for Part 9 (7 files)

solutions/ex01.tsx

// Solution to Exercise 1. Drop in as harness/app/mandi/scratch-ex1/page.tsx.
// Delete afterward — not part of the harness's canonical Part 9 state.
import { Suspense } from "react";
import { getReviews } from "../lib/reviews";
import { getStock } from "../lib/stock";

function wait(ms: number) {
  return new Promise<void>((resolve) => setTimeout(resolve, ms));
}

// 300ms — the simulated cost of a third upstream, deliberately the
// fastest of the three so the math stays easy to check by hand:
// max(400, 350, 300) = 400ms, not 1050ms.
async function getDelivery(): Promise<string> {
  await wait(300);
  return "2 days";
}

async function Panel() {
  const [reviews, stock, delivery] = await Promise.all([getReviews("g1"), getStock("g1"), getDelivery()]);
  return (
    <p>
      {reviews?.reviewCount} reviews, {stock.unitsAvailable} in stock, delivery in {delivery}
    </p>
  );
}

export default function Ex1Page() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <Panel />
    </Suspense>
  );
}

// $ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/scratch-ex1   # warm-up
// $ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/scratch-ex1
// 0.475s
// 0.477s
// 0.457s
// Confirmed for real against this harness: close to reviews' 400ms (the
// slowest of the three), not 400+350+300=1050ms.

solutions/ex02.tsx

// Solution to Exercise 2. Drop in as harness/app/mandi/scratch-ex2/page.tsx.
// Delete afterward.
import { Suspense } from "react";
import { cache } from "react";

type ReviewSummary = { productId: string; averageRating: number; reviewCount: number };

const reviewsByProduct: Record<string, ReviewSummary> = {
  g1: { productId: "g1", averageRating: 4.2, reviewCount: 318 },
};

function wait(ms: number) {
  return new Promise<void>((resolve) => setTimeout(resolve, ms));
}

// Same per-request-counter pattern as lib/stock.ts's warehouseCallsThisRequest.
const reviewCallsThisRequest = cache(() => ({ count: 0 }));

async function fetchReviews(id: string): Promise<ReviewSummary | null> {
  reviewCallsThisRequest().count++;
  await wait(400);
  return reviewsByProduct[id] ?? null;
}

const getReviewsCached = cache(fetchReviews);

async function Panel() {
  const a = await getReviewsCached("g1");
  const b = await getReviewsCached("g1");
  const calls = reviewCallsThisRequest().count;
  return (
    <p id="calls">
      reviews calls: {calls}, a===b: {String(a === b)}
    </p>
  );
}

export default function Ex2Page() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <Panel />
    </Suspense>
  );
}

// $ curl -s http://localhost:PORT/mandi/scratch-ex2 | grep -o 'reviews calls:.*calls'
// reviews calls: 1, a===b: true
// Confirmed for real: the second call never re-ran fetchReviews, AND it
// got back the exact same object the first call produced.

solutions/ex03.tsx

// Solution to Exercise 3. Drop in as harness/app/mandi/scratch-ex3/page.tsx.
// Delete afterward.
import { Suspense } from "react";
import { getStock, warehouseCallsThisRequest } from "../lib/stock";

async function StockBadge() {
  const stock = await getStock("g1");
  return <li id="badge">In stock: {stock.unitsAvailable} units</li>;
}

async function LowStockWarning() {
  const stock = await getStock("g1");
  return <li id="warning">{stock.unitsAvailable < 20 ? "Low stock" : "Plenty in stock"}</li>;
}

async function CallCount() {
  return <li id="calls">Warehouse calls this request: {warehouseCallsThisRequest().count}</li>;
}

async function Panel() {
  // Two genuinely separate components, combined with Promise.all so React
  // can render them concurrently — the realistic "two widgets, one page"
  // shape, instead of one function awaiting the same thing twice.
  const [badge, warning] = await Promise.all([StockBadge(), LowStockWarning()]);
  const calls = await CallCount();
  return (
    <ul>
      {badge}
      {warning}
      {calls}
    </ul>
  );
}

export default function Ex3Page() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <Panel />
    </Suspense>
  );
}

// $ curl -s http://localhost:PORT/mandi/scratch-ex3 | grep -oE '<li id="(badge|warning|calls)">[^<]*'
// <li id="badge">In stock: 42 units
// <li id="warning">Plenty in stock
// <li id="calls">Warehouse calls this request: 2
// Same count as section 4's single-function version — the realistic
// two-component shape doesn't change the result, it just makes the
// scenario honest.

solutions/ex04.md

# Solution to Exercise 4

**The broken version** — drop in as `harness/app/mandi/scratch-ex4/page.tsx`:
```tsx
import { getReviews } from "../lib/reviews";

// No <Suspense> anywhere - this should fail the build.
export default async function Ex4Page() {
  const reviews = await getReviews("g1");
  return <p>{reviews?.reviewCount} reviews</p>;
}
```
Real build error, captured against this harness:
```text
$ npm run build
...
Error: Route "/mandi/scratch-ex4": Next.js encountered uncached or runtime data during prerendering.

`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.

Ways to fix this:
  - [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
  - [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
  - [block] Set `export const instant = false` to allow a blocking route

Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
    at body (<anonymous>)
    at html (<anonymous>)
...
Export encountered an error on /mandi/scratch-ex4/page: /mandi/scratch-ex4, exiting the build.
⨯ Next.js build worker exited with code: 1 and signal: null
```

**Cleanup — delete the file, then rebuild clean:**
```text
$ rm -rf app/mandi/scratch-ex4
$ npx next typegen
Generating route types...
✓ Types generated successfully
$ npm run build
...
✓ Generating static pages using 17 workers (60/60) in ...ms
```
The `next typegen` step matters: deleting a route file without it leaves a stale reference in `.next/dev/types/validator.ts` (generated while the route existed), and the next `tsc` pass fails on `Cannot find module '../../../app/mandi/scratch-ex4/page.js'` — a confusing error that has nothing to do with the actual fix. Verified for real against this harness: skipping `next typegen` reproduces exactly that error after deleting the scratch file.

The real fix (not part of this exercise's scope, but worth knowing) is one of the three options the error itself lists — most often wrapping the data-reading component in `<Suspense>`, the way every page.tsx in this part actually does it.

solutions/ex05.md

# Solution to Exercise 5

No new file — this exercise re-measures `/mandi/products/g4` and `/mandi/products/g4/sequential`, already built in sections 1–2, using `curl`'s own timer instead of an external one.

```text
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4   # warm-up, discarded
0.900s (varies — first compile)
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4
0.424694s
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4/sequential   # warm-up, discarded
$ curl -s -o /dev/null -w "%{time_total}s\n" http://localhost:PORT/mandi/products/g4/sequential
0.777512s
```
Both numbers land in the same range section 2 measured for `g2` with a hand-rolled Python timer (~460ms parallel, ~820ms sequential) — a few tens of milliseconds of difference between products and between runs is normal scheduling noise, not a different result. `curl -w "%{time_total}"` is the simpler tool for this: it's curl's own measurement of the full request/response cycle, with one fewer moving part (no separate `time.time()` calls, no risk of the shell commands around them adding their own overhead) than timing curl from the outside.

solutions/ex06.tsx

// Solution to Exercise 6. Drop in as harness/app/mandi/scratch-ex6/page.tsx.
// Delete afterward.
import { Suspense } from "react";
import { getStockCached, warehouseCallsThisRequest } from "../lib/stock";

async function Panel() {
  const a = await getStockCached("g1");
  const b = await getStockCached("g2"); // different argument - different cache key
  const c = await getStockCached("g1"); // same argument as `a` - reuses it, no new call
  const calls = warehouseCallsThisRequest().count;
  return (
    <p id="calls">
      g1: {a.unitsAvailable}, g2: {b.unitsAvailable}, g1 again: {c.unitsAvailable}, calls: {calls}
    </p>
  );
}

export default function Ex6Page() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <Panel />
    </Suspense>
  );
}

// $ curl -s http://localhost:PORT/mandi/scratch-ex6 | grep -o 'calls: [0-9]*'
// calls: 2
// One real call for "g1", one real call for "g2" (arguments are part of
// the cache key — confirmed in this install), and the second "g1" call
// reused the first instead of becoming a third call.

solutions/ex07.md

# Solution to Exercise 7

No new file — reuses `/mandi/products/[id]` with an id guaranteed to be brand-new to this specific `next start` process.

```text
$ npm run build && npm run start -- -p PORT
...
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/products/exercise5-test   # first-ever request
HTTP/1.1 200 OK
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/products/exercise5-test   # second request, same id
HTTP/1.1 404 Not Found
$ curl -s -D - -o /dev/null http://localhost:PORT/mandi/products/exercise5-test   # third request
HTTP/1.1 404 Not Found
```
Same shape as the README's section 5 finding (which used `zzz`), now reproduced with a different, unrelated string (`exercise5-test`) — confirming this is general "first request to an unlisted dynamic param" behavior, not something tied to one specific id. The mechanism is the same either time: the first request's response starts streaming (status `200` committed) before Next.js has finished resolving that this id will 404, and once it resolves that, this install's ISR "upgrade" mechanism caches the resolved, now-known-404 result so every later request to the same path gets a direct `404` with no stream and no shell.

A second, equally valid way to see this without guessing a "never requested" string: restart the server fresh (`next start` again) and immediately curl an unlisted id exactly once before doing anything else — that first request is always the one that can show `200`.

Common mistakes

Mistake Why it is wrong Fix
await getReviews(id); await getStock(id); written just because that's reading order Builds a real waterfall — the second read waits for the first for no reason — proven in section 2 Promise.all([getReviews(id), getStock(id)]) when neither depends on the other
Assuming any awaited local function gets "free" deduplication like fetch() Next's automatic memoization patches the global fetch specifically (confirmed from patch-fetch.js in this install) — a local async function gets none of it Wrap the function in React's cache() yourself, verified in section 4
Expecting cache() to always make a page visibly faster When calls run concurrently via Promise.all, wall-clock time may barely change — cache()'s real win is fewer calls to the real backend, not always a faster page Measure call counts and timing separately; don't assume one implies the other
Forgetting <Suspense> around an await with real (even local, even constant-ish) latency cacheComponents: true rejects it during prerendering with the same error family Part 5 and TOOLING.md found for new Date() Wrap the data-reading component in <Suspense>, as both product-detail pages do here
Trusting a single curl against a brand-new dynamic URL to prove it 404s The very first request to an unlisted id can return 200 with a streamed fallback, verified in section 5 Check the second request too, or grep the body for NEXT_HTTP_ERROR_FALLBACK rather than trusting the status line alone on a cold path

Quick recap

  • Two independent local data sources, each with its own simulated latency (reviews.ts 400ms, stock.ts 350ms) — never a real network call.
  • Sequential awaits build a real, measurable waterfall (~820ms); Promise.all fixes it (~460ms) — both numbers measured against this harness, not estimated.
  • cacheComponents: true requires <Suspense> around any real-latency await during prerendering, even when generateStaticParams already knows every param.
  • Next's automatic fetch memoization is specific to the patched global fetch (read directly from patch-fetch.js) — a local async function needs React's own cache() for the same effect, proven with a real call counter (2 calls → 1 call).
  • cache() saves real backend calls even when it doesn't visibly save wall-clock time under Promise.all — don't conflate the two.
  • notFound() on a missing id is simple when the local data source can only say "found" or "not found" — and the very first request to a brand-new unlisted id can still return 200 before Next.js "upgrades" it to a direct 404 on every later request.

Checklist

  • I built both the sequential and parallel versions of Mandi Fresh's product page and measured the real timing difference with curl, not an estimate.
  • I can explain, from patch-fetch.js's own source, why automatic request memoization doesn't apply to a plain local async function.
  • I wrapped a local data function in React's cache() and proved — by counting, not guessing — that a second identical call in the same render pass didn't re-run it.
  • I can state the actual trade-off cache() bought me in my own test (fewer calls, not necessarily less time) instead of assuming it's always "faster."
  • I triggered the real "uncached or runtime data during prerendering" build error by removing a <Suspense> boundary, and fixed it by putting it back.
  • I requested a brand-new unlisted product id twice in a row against a real next build && next start and saw the status code change from the first request to the second.

Search the guide