Part 05 / Stage 2
Server Components by default
Goal: Understand the single biggest mental shift coming from a client-only React background: every component you write is a Server Component unless you say otherwise. Learn exactly what that buys you (direct,
await-based data access, secrets that never leave the server) and exactly what it forbids (hooks, event handlers), by building a real internal "wholesale desk" page for Apna Bazaar that ships zero client-side JavaScript of its own. Time: ~5 h · Level: 🟢 finished Stage 1 (routing, layouts, navigation), comfortable with React's component/props model
What you will learn
- Why Next.js's App Router defaults every component to a Server Component — no directive, no opt-in, it is simply the starting state
asyncServer Components:awaityour data directly inside the component that needs it, with nouseEffectand no loading state you manage by hand- What a Server Component genuinely cannot do —
useState,useEffect, and anyonClick-style event handler — reproduced as a real build error, not a rule taken on faith server-only: a one-line import that turns "please don't use this from the client" into a build-time guarantee- How to actually tell where a piece of code ran — reading a server-only
console.log, and whytypeof windowis a reliable server/client tell - How to prove a page shipped no client-side JavaScript of its own, by reading the real build output rather than assuming it
Topics in this part
Practice
Every exercise adds files under harness/app/store/ (or a sibling scratch folder), runs a real command against them, and then removes what it added, restoring the harness to the exact state Part 5's README ends on: /store/wholesale present, everything else exactly as Part 4 left it. Copy the exact commands you ran and their real output into your own notes; do not type output from memory.
Exercise 1: A second zero-JS Server Component page
Scenario: Apna Bazaar's owner also wants a one-page staff roster, for internal use only.
What to do: Create app/store/(shop)/staff/page.tsx with an <h1>Staff roster</h1> and a short <ul> of two names. No "use client", no hooks. Run next build and confirm /store/staff appears as ○ (Static). Then diff its chunk list against /store/about's (section 6's technique) and confirm there is no difference. Delete the folder and rebuild afterward.
Sample output (run for real against this course's harness):
$ npm run build
...
├ ○ /store/staff
...
$ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/staff.html | sort -u) <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/about.html | sort -u)
(no output — identical)
💡 Hint: This is section 6's exact technique, just on a page you built yourself instead of wholesale.
Exercise 2: Trigger and fix a server-only leak
Scenario: You're about to add a second internal data module — supplier contract terms — and want to prove the leak-prevention actually works before trusting it.
What to do: Create a scratch module contract.ts starting with import "server-only";, exporting a CONTRACT_TERMS string. Import it directly into a scratch Client Component ("use client") and render it. Run next build and capture the real error. Then fix it the right way: read CONTRACT_TERMS in the Server Component page instead, and pass it down as a plain string prop to the Client Component. Rebuild to confirm it's green, then delete every scratch file.
Sample output (run for real against this course's harness):
$ npm run build
...
Error: Turbopack build failed with 2 errors:
./app/store/_scratch/ex2/contract.ts:1:1
Error: You're importing a module that depends on "server-only" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use client", so this module is also a Client Component.
...
./app/store/_scratch/ex2/contract.ts:1:1
Error: 'server-only' cannot be imported from a Client Component module
...
After the fix:
$ npm run build
...
├ ○ /store/ex2
...
$ grep -o '<p>[^<]*</p>' .next/server/app/store/ex2.html
<p>Net 30, FOB Jaipur warehouse</p>
💡 Hint: The fix is the Server/Client composition rule from section 1, applied on purpose — the secret value is read on the server and only the already-resolved string crosses the boundary, never the module that fetched it.
Exercise 3: Reproduce the timer-based prerendering rejection
Scenario: You want to see section 2's "going deeper" finding with your own hands, not just read it.
What to do: Create app/store/(shop)/ex3/page.tsx with an async helper function that does await new Promise((resolve) => setTimeout(resolve, 10)); before returning a plain string, and an async page component that awaits it. Run next build and capture the real error. Then change the helper to await Promise.resolve(); instead, rebuild, and confirm it's green. Delete the folder afterward.
Sample output (run for real against this course's harness):
$ npm run build
...
Error: Route "/store/ex3": 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.
...
After the fix:
$ npm run build
...
├ ○ /store/ex3
...
💡 Hint: The error fires even though the timer's resolved value ("ready") never changes between builds — it's the unpredictable timing that trips cacheComponents, not the value.
Exercise 4: Trigger the useState-with-no-directive error
Scenario: You want the exact error message in your own notes, from your own harness, not copied from the README.
What to do: Create a scratch component that imports useState from react and calls it, with no "use client" anywhere in the file. Import it into a scratch page and run next build. Capture the exact error, including the file and line it points at. Delete both scratch files afterward.
Sample output (run for real against this course's harness):
$ npm run build
...
Error: Turbopack build failed with 1 error:
./app/store/_scratch/no-directive/Comp.tsx:1:10
Error: You're importing a module that depends on `useState` into a React Server Component module. This API is only available in Client Components. To fix, mark the file (or its parent) with the `"use client"` directive.
Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
💡 Hint: Note which file the error blames — the component that calls useState, not the page that imports it. Adding "use client" to the page instead would not fix this (and would be Part 6's "pushed the boundary too high" mistake).
Exercise 5: Prove a console.log placement for yourself
Scenario: You want to be sure "the terminal, never the browser" is really true, on a page you wrote, not just wholesale.
What to do: Create a scratch page with one console.log("...", typeof window) line inside its Server Component body. Run next build and find the log line in the build's own terminal output. Then grep the generated HTML (.next/server/app/store/.../your-page.html) for the same log text and confirm it does not appear. Delete the scratch page afterward.
Sample output (run for real against this course's harness):
$ npm run build
...
Ex5Page rendering, typeof window: undefined
Ex5Page rendering, typeof window: undefined
...
$ grep -c "Ex5Page rendering" .next/server/app/store/ex5.html
0
💡 Hint: The log line appearing twice is not a mistake in your code — section 5 already found this for WholesalePage too.
Exercise 6: The mirrored guard — client-only in a Server Component
Scenario: Section 4 only proved one direction (server-only blocking a Client Component import). Prove the opposite guard exists too.
What to do: Create a scratch module starting with import "client-only"; that reads window.localStorage. Import it directly into a plain Server Component (no "use client" anywhere) and call it. Run next build and capture the real error. Delete the scratch files afterward.
Sample output (run for real against this course's harness):
$ npm run build
...
Error: Turbopack build failed with 2 errors:
./app/store/_scratch/ex6/browserStorage.ts:1:1
Error: You're importing a component that imports client-only. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
Learn more: https://nextjs.org/docs/app/building-your-application/rendering
...
💡 Hint: client-only was already present in this harness's node_modules before this part added anything — it ships as a dependency of the framework itself, not something this course installed.
Exercise 7: Find the exact chunk a Client Component adds
Scenario: Section 6 diffed /store (which has QuickJump) against /store/about and found one extra chunk. Do the same comparison for a different pair of pages.
What to do: Diff /store/products's chunk list against /store/about's. Then diff /store (home page, has QuickJump) against /store/products. State, from the diff alone, which of the two pages has a Client Component and which doesn't — then confirm it by grepping the extra chunk for "Surprise me".
Sample output (run for real against this course's harness):
$ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/products.html | sort -u) <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/about.html | sort -u)
(no output — identical: /store/products has no Client Component of its own)
$ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store.html | sort -u) <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/products.html | sort -u)
2a3
> chunks/0woabm1x0sg0t.js
(The exact chunk hash varies between builds — rerun the diff on your own build rather than trusting this number.)
💡 Hint: /store/products lists products with plain <Link>s, the same pattern /store/about uses — neither needs a Client Component. /store's extra chunk is QuickJump, Part 3's "Surprise me" button.
Next
Part 6: Client Components and the boundary
Show the solutions for Part 5 (7 files)
solutions/ex01.tsx
// Solution to Exercise 1. Drop in as harness/app/store/(shop)/staff/page.tsx,
// then: npm run build (check the route table for /store/staff as ○), then
// diff its chunk list against /store/about's (section 6's technique).
// Delete the folder afterward — this is not part of the harness's
// canonical Part 5 state.
export default function StaffPage() {
return (
<main>
<h1>Staff roster</h1>
<ul>
<li>Asha — store manager</li>
<li>Ravi — packing</li>
</ul>
</main>
);
}
// $ npm run build
// ...
// ├ ○ /store/staff
// ...
// $ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/staff.html | sort -u) \
// <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/about.html | sort -u)
// (no output — identical chunk lists, confirmed for real against this harness)
solutions/ex02.md
# Solution to Exercise 2
**The broken version** — drop in as `harness/app/store/_scratch/ex2/contract.ts` and `harness/app/store/_scratch/ex2/Leaky.tsx`, imported from a scratch page:
```ts
// contract.ts
import "server-only";
export const CONTRACT_TERMS = "Net 30, FOB Jaipur warehouse";
```
```tsx
// Leaky.tsx
"use client";
import { CONTRACT_TERMS } from "./contract";
export default function Leaky() {
return <p>{CONTRACT_TERMS}</p>;
}
```
Real build error, captured against this harness:
```text
$ npm run build
...
Error: Turbopack build failed with 2 errors:
./app/store/_scratch/ex2/contract.ts:1:1
Error: You're importing a module that depends on "server-only" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use client", so this module is also a Client Component.
Learn more: https://nextjs.org/docs/app/building-your-application/rendering
...
./app/store/_scratch/ex2/contract.ts:1:1
Error: 'server-only' cannot be imported from a Client Component module
...
It should only be used from a Server Component.
```
**The fix** — read the secret on the server, pass only the resolved string across the boundary:
```tsx
// Leaky.tsx
"use client";
export default function Leaky({ terms }: { terms: string }) {
return <p>{terms}</p>;
}
```
```tsx
// harness/app/store/(shop)/ex2/page.tsx
import Leaky from "../../_scratch/ex2/Leaky";
import { CONTRACT_TERMS } from "../../_scratch/ex2/contract";
export default function Ex2Page() {
return <Leaky terms={CONTRACT_TERMS} />;
}
```
Rebuilds clean, confirmed for real:
```text
$ npm run build
...
├ ○ /store/ex2
...
$ grep -o '<p>[^<]*</p>' .next/server/app/store/ex2.html
<p>Net 30, FOB Jaipur warehouse</p>
```
`contract.ts` itself is still never imported by the Client Component — only `page.tsx` (a Server Component) imports it, which is exactly what `import "server-only"` allows.
Delete `app/store/_scratch/ex2/` and `app/store/(shop)/ex2/` afterward.
solutions/ex03.tsx
// Solution to Exercise 3. Drop in as harness/app/store/(shop)/ex3/page.tsx.
// Broken version — builds fail with "uncached or runtime data during
// prerendering", even though the resolved value never changes:
//
// async function getSlowValue() {
// await new Promise((resolve) => setTimeout(resolve, 10));
// return "ready";
// }
// Fixed version — no timer, builds clean:
async function getSlowValue() {
await Promise.resolve();
return "ready";
}
export default async function Ex3Page() {
const value = await getSlowValue();
return (
<main>
<p>{value}</p>
</main>
);
}
// Broken version, run for real against this harness:
// $ npm run build
// ...
// Error: Route "/store/ex3": 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.
// ...
//
// Fixed version, run for real:
// $ npm run build
// ...
// ├ ○ /store/ex3
// ...
//
// Delete harness/app/store/(shop)/ex3/ afterward.
solutions/ex04.tsx
// Solution to Exercise 4. Drop in as
// harness/app/store/_scratch/no-directive/Comp.tsx, imported into a
// scratch page under harness/app/store/(shop)/.
import { useState } from "react";
export default function MissingDirective() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
// $ npm run build
// ...
// Error: Turbopack build failed with 1 error:
// ./app/store/_scratch/no-directive/Comp.tsx:1:10
// Error: You're importing a module that depends on `useState` into a React Server Component module. This API is only available in Client Components. To fix, mark the file (or its parent) with the `"use client"` directive.
// Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
//
// The error blames line 1 (the `useState` import), not the JSX that uses
// it, and not the page that imports this component — the directive has
// to go on this file itself (or a parent module between here and the
// page), per the error's own wording.
//
// Delete the scratch component and the scratch page afterward.
solutions/ex05.tsx
// Solution to Exercise 5. Drop in as harness/app/store/(shop)/ex5/page.tsx.
export default function Ex5Page() {
console.log("Ex5Page rendering, typeof window:", typeof window);
return (
<main>
<p>hello</p>
</main>
);
}
// $ npm run build
// ...
// Ex5Page rendering, typeof window: undefined
// Ex5Page rendering, typeof window: undefined
// ...
// $ grep -c "Ex5Page rendering" .next/server/app/store/ex5.html
// 0
//
// The log shows up twice in the build's own terminal output (the same
// double-render Part 5's README section 5 found for WholesalePage), and
// zero times in the generated HTML — confirming it never reaches
// anything a browser would see.
//
// Delete harness/app/store/(shop)/ex5/ afterward.
solutions/ex06.ts
// Solution to Exercise 6. Drop in as
// harness/app/store/_scratch/ex6/browserStorage.ts, imported directly
// (no "use client" anywhere) into a scratch page.
import "client-only";
export function readLastViewed(): string | null {
return window.localStorage.getItem("lastViewed");
}
// harness/app/store/(shop)/ex6/page.tsx:
//
// import { readLastViewed } from "../../_scratch/ex6/browserStorage";
//
// export default function Ex6Page() {
// const lastViewed = readLastViewed();
// return <main><p>{lastViewed}</p></main>;
// }
// $ npm run build
// ...
// Error: Turbopack build failed with 2 errors:
// ./app/store/_scratch/ex6/browserStorage.ts:1:1
// Error: You're importing a component that imports client-only. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
// Learn more: https://nextjs.org/docs/app/building-your-application/rendering
// ...
//
// This is the mirror image of Exercise 2/section 4's server-only error:
// client-only blocks a browser-only module from a Server Component,
// exactly as server-only blocks a server-only module from a Client
// Component — same mechanism, opposite direction.
//
// Delete the scratch module and the scratch page afterward.
solutions/ex07.md
# Solution to Exercise 7
Run both diffs for real against the harness (no files need adding or removing — this exercise only reads existing build output):
```text
$ npm run build
...
$ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/products.html | sort -u) \
<(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/about.html | sort -u)
(no output — identical)
$ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store.html | sort -u) \
<(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/products.html | sort -u)
2a3
> chunks/0woabm1x0sg0t.js
```
**Reading the two diffs:** the first is empty, so `/store/products` has no extra chunk beyond the shared framework chunks `/store/about` already needs — `/store/products` has no Client Component of its own, matching its source (a plain `<Link>`-based list, same pattern as `/store/about`). The second diff has exactly one extra line, so `/store` (the home page) has exactly one Client Component `/store/products` doesn't.
Confirming which component that extra chunk actually is:
```text
$ grep -c 'Surprise me' .next/static/chunks/0woabm1x0sg0t.js
1
```
That is `QuickJump`, Part 3's "Surprise me" button on the home page — the one Client Component `/store` has that `/store/products` doesn't.
(The chunk hash `0woabm1x0sg0t.js` is a build artifact and will almost certainly be a different string on your own build — rerun the diff rather than trusting this exact filename.)
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Asking "how do I make this a Server Component?" | It already is one — every component defaults to Server Component, reproduced in section 1 | Only ask the opposite question: does this component need "use client"? |
Reaching for useEffect + useState to fetch data in a page |
The component can simply await the data directly, as WholesalePage does in section 2 |
const data = await getData(); right in the async component body |
Using useState or an event handler with no "use client" anywhere in the file or its imports |
Build-time error, reproduced for real in section 3 — not a runtime surprise | Add "use client" to the top of that specific file (Part 6) |
| Trusting yourself to never import a server-only module from a Client Component | One accidental import ships a secret to every browser; server-only's guard is the only thing that is actually enforced, proven in section 4 |
import "server-only"; at the top of any module holding secrets or server-only logic |
Assuming a slow await always breaks the build the same way new Date() does |
It's not about the value changing — a setTimeout-backed Promise resolving to a constant still fails the exact same prerendering check, verified in section 2's "going deeper" note |
Keep awaited work instant for now; reach for <Suspense> (Part 7) or "use cache" (Stage 3) for real slow data |
| Debugging "did this run on the server?" by checking the browser's console | A Server Component's console.log never reaches it — proven in section 5 |
Check the terminal running next dev/next build, or test typeof window === "undefined" |
Assuming a build log's console.log ran exactly once |
Static generation re-rendered WholesalePage twice for one page in one build, observed consistently in section 5 |
Keep Server Component side effects idempotent, or confine them to logging |
Quick recap
- Every component is a Server Component unless
"use client"opts it (or something it imports) out — there is no separate step to "turn on" server rendering. - An
asyncServer Component canawaitits data directly in the component body; nouseEffect, no hand-rolled loading state. cacheComponents: truerejects anyawaitwhose timing could vary — proven for both a non-deterministic value (TOOLING.md'snew Date()) and a bare timer resolving to a constant (this part's finding).useState,useEffect, and event handlers all fail at build time inside a Server Component, with a specific, readable error naming the exact fix.import "server-only"turns "this module must never reach the browser" into an enforced build failure, not a convention to remember.console.logplustypeof windoware the two reliable ways to tell, from the code's own behavior, whether something ran on the server.- "Ships zero client-side JavaScript" is checkable directly: diff a page's chunk list against a known-pure-server page's, and it should be identical.
Checklist
- I can explain why "every component is a Server Component by default" is the opposite of the client-only React mental model.
- I built an
asyncServer Component thatawaits a data-layer function directly, with nouseEffectanywhere. - I triggered the real
useState-in-a-Server-Component build error myself, read its exact message, and deleted the file afterward. - I added
import "server-only"to a module and triggered the real build error by importing it from a Client Component. - I found a
console.logfrom a Server Component in a build's terminal output and confirmed it never appeared in the page's HTTP response. - I diffed two pages' chunk lists and can state, from that diff, exactly how many extra chunks a Client Component adds.