Part 15 / Stage 4
An auth pattern
Goal: Build a real, working session-cookie login (not a sketch), protect a route group's layout with it, and prove — with a real reproduced gap, not a warning taken on faith — why the protection has to live in the page itself, not just its layout's nav. Built as a new
app/account/universe: a login form (Part 12's Server Action pattern), a protected(protected)/dashboardroute group, andproxy.ts(Part 14) extended with an optimistic check. Time: ~6 h · Level: finished Part 14 (Middleware and the request pipeline) Verified against: Next.js 16.4.6 / React 19.3.0,cacheComponents: true+partialPrefetching: true,iron-session9.1.1 — all installed and run for real in this harness, versions confirmed in section 1.
What you will learn
- Why this part uses
iron-sessionfor the session-cookie layer specifically, with the same kind of version-churn evidenceDESIGN-NOTES.mdalready used to pickbetter-sqlite3over Prisma - A real signed/encrypted session cookie: creating one from a Server Action, reading it from a Server Component, destroying it on logout
- The Data Access Layer (DAL) pattern the installed docs recommend: one
getCurrentUser/requireUserpair, called from everywhere that needs to know who's signed in "use cache: private"— the directive that lets a cached function readcookies()under this install's default Cache Components model, and why a plain"use cache"can't- The central, reproduced finding of this part: a parent layout's own auth check does not protect the page it wraps — proven by actually serving protected-looking content to an unauthenticated request, then fixing it
- The Server Component vs. middleware trade-off, measured rather than asserted: an authoritative DAL check that always returns
200(with the redirect embedded in the stream) vs. an optimistic proxy check that returns a real top-level307— and why this course keeps both
Topics in this part
Practice
Every exercise adds a scratch route under harness/app/account/scratch-*/
(or temporarily edits an existing file, restoring it afterward — noted per
exercise), runs a real command against it, and then removes/restores
what it added. Copy the exact commands you ran and their real output
into your own notes; do not type output from memory — a sealed session
cookie's exact bytes are different on every run, but the shape of each
result below (status codes, which fields are present) reproduces exactly.
Exercise 1: getCurrentUser() never redirects — confirmed on a page with no session at all
Scenario: Section 3's README draws a line between getCurrentUser() (optional, returns null) and requireUser() (redirects). Prove the optional one actually stays on the page.
What to do: Create app/account/scratch-whoami/page.tsx — a Server Component, wrapped in <Suspense>, that calls getCurrentUser() and renders either the user's name or "Not signed in" depending on the result. Request it with no session cookie at all.
Sample output (run for real against this course's harness):
$ curl -s http://localhost:PORT/account/scratch-whoami
...<p id="whoami">Not signed in (and not redirected!)</p>...
💡 Hint: No 307, no embedded NEXT_REDIRECT marker anywhere in the response — the page rendered completely normally for a request with zero session cookie. getCurrentUser() is exactly what a public page's "Log in / Welcome, Priya" nav link should call; requireUser() is for the pages that must not render at all without a session.
Exercise 2: Role-gated content really is gated, not just hidden by data
Scenario: DashboardContent renders an "Admin tools" paragraph only when user.role === "admin". Confirm a logged-in customer genuinely never sees it, not just that the UI happens not to display it due to missing data.
What to do: Log in as [email protected] / mango123 (a customer account) and fetch /account/dashboard with the resulting session cookie.
Sample output (run for real against this course's harness):
$ curl -s -b cookies.txt http://localhost:PORT/account/dashboard | grep -c "Admin tools"
0
💡 Hint: 0 — the string "Admin tools" does not appear anywhere in the response at all, confirmed by grep -c, not just visually absent in a browser. The check (user.role === "admin") runs on the server, inside the same Server Component that already ran requireUser() — a customer's response genuinely never contains the admin markup to begin with, unlike a client-side-only "hide this div" approach that would still ship the HTML and just not display it.
Exercise 3: A tampered session cookie — treated as no session, not a crash
Scenario: iron-session's seal is tamper-evident. Confirm what "tamper-evident" means concretely: does a corrupted cookie crash the server, or does it just look like a logged-out visitor?
What to do: Log in for real, save the cookie jar, then edit one character of the sealed quickcart_session value (e.g. change its Fe26.2 version prefix to Fe99.2) and request /account/dashboard with the tampered cookie.
Sample output (run for real against this course's harness):
$ curl -s -D - -o /dev/null -b tampered-cookies.txt http://localhost:PORT/account/dashboard
HTTP/1.1 307 Temporary Redirect
location: /account/login
Server log: no error, no stack trace, no crash.
💡 Hint: A tampered cookie is treated exactly like no cookie at all — unsealData (inside getIronSession) can't tell "this was tampered with" apart from "this was never valid," so the only safe response is to start over with an empty session, which requireUser()/the proxy's optimistic check both then treat as "not signed in." This is also why the session-config module throws loudly at startup if SESSION_PASSWORD is missing (session-config.ts), rather than falling back to a default: a wrong-but-present password would make every real session look tampered, silently logging everyone out with no error anywhere to explain why.
Exercise 4: Logging out actually destroys the cookie, not just the in-memory reference
Scenario: Confirm session.destroy() produces a real Set-Cookie that removes the cookie from the browser, not just a response that happens to redirect.
What to do: Log in, confirm the dashboard works, then submit the real logout Server Action (read its hidden $ACTION_ID_... field off the dashboard's own rendered HTML, same technique as Part 12 exercise 1) and inspect the exact Set-Cookie header it returns.
Sample output (run for real against this course's harness):
$ curl -s -D - -X POST http://localhost:PORT/account/dashboard -F '$ACTION_ID_<real-id>=' -b cookies.txt
HTTP/1.1 303 See Other
Set-Cookie: quickcart_session=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=lax
Location: /account/login
$ curl -s -D - -o /dev/null -b cookies.txt http://localhost:PORT/account/dashboard # same (now-stale) cookie jar
HTTP/1.1 307 Temporary Redirect
💡 Hint: Max-Age=0 and an empty value is the standard way a server tells a browser "delete this cookie now" — not merely "I'll stop checking it." Reusing the exact same (pre-logout) cookie jar against the dashboard afterward still gets redirected, confirming the session was actually destroyed server-side too, not just unset client-side.
Exercise 5: Disable the proxy's optimistic check and watch the status code change, live
Scenario: Section 5 showed the DAL-only response is always 200 (redirect embedded in the stream) and the proxy-backed response is a real 307. Reproduce the difference yourself, on the exact same unauthenticated request, by toggling one thing.
What to do: Temporarily remove the if (pathname.startsWith("/account/dashboard")) { ... } block from proxy.ts (restoring it immediately after). Request /account/dashboard with no session cookie, both before and after the edit.
Sample output (run for real against this course's harness):
# with the optimistic check in proxy.ts (normal state):
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/account/dashboard
status=307
# with the block temporarily removed:
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/account/dashboard
status=200
💡 Hint: The only thing that changed is whether proxy.ts runs its own session check before the request ever reaches app/account/(protected)/dashboard/page.tsx. requireUser() inside the page is still there in both cases, still redirecting correctly (the embedded NEXT_REDIRECT marker is present in the 200 response's body either way) — what the proxy adds is purely a faster, real-status-code short-circuit for the common case, exactly section 5's point.
Next
Show the solutions for Part 15 (5 files)
solutions/ex01.md
# Solution to Exercise 1
```tsx
// app/account/scratch-whoami/page.tsx (scratch — created, run, then deleted)
import { Suspense } from "react";
import { getCurrentUser } from "../lib/auth";
export default function WhoAmIPage() {
return (
<Suspense fallback={<p>Checking...</p>}>
<WhoAmI />
</Suspense>
);
}
async function WhoAmI() {
const user = await getCurrentUser();
return <p id="whoami">{user ? `Signed in as ${user.name}` : "Not signed in (and not redirected!)"}</p>;
}
```
**Run for real against this harness, with no session cookie at all:**
```text
$ curl -s http://localhost:PORT/account/scratch-whoami
...<p id="whoami">Not signed in (and not redirected!)</p>...
```
No `307`, no `NEXT_REDIRECT` marker anywhere in the response body —
`getCurrentUser()` returned `null` and the component rendered its
"not signed in" branch normally, exactly like any other conditional
render. This is the function this course's harness would reach for in a
public page's nav ("Log in" vs. "Welcome back, Priya"); `requireUser()`
(every other example in this part) is for pages that must not render
content at all without a session. Scratch route removed with `rm -rf
app/account/scratch-whoami` after this check.
solutions/ex02.md
# Solution to Exercise 2
No new file needed — logged in as the seeded customer account and
requested the existing dashboard.
**Login, then dashboard request, run for real against this harness:**
```text
$ curl -s -c cookies.txt http://localhost:PORT/account/login -o login.html
# (read the real hidden $ACTION_* fields out of login.html, same as Part 12 exercise 1)
$ curl -s -c cookies.txt -b cookies.txt -X POST http://localhost:PORT/account/login \
-F '$ACTION_REF_1=' -F '$ACTION_1:0=...' -F '$ACTION_1:1=["$undefined"]' -F '$ACTION_KEY=...' \
-F '[email protected]' -F 'password=mango123' -o /dev/null
$ curl -s -b cookies.txt http://localhost:PORT/account/dashboard | grep -c "Admin tools"
0
```
`[email protected]` is seeded with `role: "customer"` in
`app/account/lib/users.ts`. `DashboardContent`'s own JSX only includes the
"Admin tools" paragraph inside a `{user.role === "admin" && (...)}`
block, evaluated entirely on the server — a customer's response never
contains that markup at all, confirmed here by `grep -c` returning `0`
rather than a count of hidden-but-present elements. Logging in as
`[email protected]` / `adminpass` instead and repeating the same
command returns `1`, confirming the gate works in both directions.
solutions/ex03.md
# Solution to Exercise 3
**Login, then tamper the cookie, run for real against this harness:**
```text
$ curl -s -c cookies.txt ... (log in as [email protected] / mango123, as in Exercise 2)
$ cat cookies.txt | grep quickcart_session
#HttpOnly_localhost FALSE / TRUE ... quickcart_session Fe26.2*1*786f3c2c...
```
Edited the saved cookie-jar file by hand, changing the seal's own version
prefix from `Fe26.2` to `Fe99.2` (any single-character change inside the
seal works identically) and saved it as `tampered-cookies.txt`.
**Request with the tampered cookie:**
```text
$ curl -s -D - -o /dev/null -b tampered-cookies.txt http://localhost:PORT/account/dashboard
HTTP/1.1 307 Temporary Redirect
location: /account/login
```
Server log: no error, no stack trace — nothing at all out of the
ordinary.
A tampered seal is indistinguishable, from the server's point of view,
from a cookie that was never valid in the first place — `iron-session`'s
`unsealData` (used internally by `getIronSession`) can't tell "this was
deliberately corrupted" apart from "garbage," so the only safe behavior
is to treat it as an empty, fresh session. Both the proxy's optimistic
check and `requireUser()` then see `session.userId` as `undefined` and
redirect exactly as they would for a request with no cookie at all —
confirmed here by getting the identical `307`/`location` pair Exercise 5
shows for the genuinely-no-cookie case.
solutions/ex04.md
# Solution to Exercise 4
**Login, read the logout action id off the dashboard's own HTML, then
log out — run for real against this harness:**
```text
$ curl -s -c cookies.txt ... (log in as [email protected] / mango123)
$ curl -s -b cookies.txt http://localhost:PORT/account/dashboard -o dash.html
$ grep -o '\$ACTION_ID_[0-9a-f]*' dash.html | head -1
$ACTION_ID_00bb176103fee05cbfd62305fc25f1c457493298f2
$ curl -s -c cookies.txt -b cookies.txt -D - -X POST http://localhost:PORT/account/dashboard \
-F '$ACTION_ID_00bb176103fee05cbfd62305fc25f1c457493298f2='
HTTP/1.1 303 See Other
Set-Cookie: quickcart_session=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=lax
Location: /account/login
```
**Reusing the same (now-stale) cookie jar against the dashboard again:**
```text
$ curl -s -D - -o /dev/null -b cookies.txt http://localhost:PORT/account/dashboard
HTTP/1.1 307 Temporary Redirect
location: /account/login
```
`session.destroy()` (inside the `logout` Server Action) produces a real
`Set-Cookie` with an empty value and `Max-Age=0` — the standard HTTP
instruction for a browser to delete a cookie immediately, not merely a
hint to stop checking it. Re-sending the exact same cookie the client
jar still holds confirms the server-side effect too: the dashboard
redirects again, proving the session was destroyed on the server (an
unsealed empty session, same as a never-logged-in visitor), not just
cleared from the client's jar.
solutions/ex05.md
# Solution to Exercise 5
**Normal state — the optimistic check present in `proxy.ts`:**
```text
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/account/dashboard
status=307
```
**`proxy.ts`, temporarily edited** — the whole
`if (pathname.startsWith("/account/dashboard")) { ... }` block removed
(and `"/account/dashboard"`/`"/account/dashboard/:path*"` dropped from
`config.matcher`, since nothing in the file needs them anymore), leaving
only the Part 14-era `/status` logic:
```text
$ npm run build && npm run start -p PORT
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/account/dashboard
status=200
```
**Restored `proxy.ts` to its real Part 15 state, rebuilt, confirmed
`307` again before moving on.**
The only variable that changed between the two runs is whether
`proxy.ts` itself performs a session check before the request reaches
`app/account/(protected)/dashboard/page.tsx` at all. `requireUser()`
inside the page keeps running and keeps redirecting correctly in both
cases — the `200` response still carries the embedded `NEXT_REDIRECT`
marker in its body, confirmed by grepping it, exactly like section 4's
finding. The proxy doesn't change *whether* the visitor is protected; it
only changes whether the protection shows up as a fast, real HTTP status
code or as a `200` the client has to interpret after the fact.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Reaching for a full "Auth Library" (Clerk, Auth0, NextAuth, ...) for an offline/local course exercise | Nearly all require an external account/API key; NextAuth specifically has the same version-churn signature DESIGN-NOTES.md already used to reject Prisma |
Use the installed docs' own named session management library (iron-session) plus the hand-rolled DAL pattern they document alongside it |
| Checking auth only in a shared layout's nav component | A layout does not control whether {children} renders — section 4 reproduced real content served to an unauthenticated request with exactly this setup |
Call the DAL's requireUser() (or equivalent) inside every protected page/component itself, not just a parent layout |
Trying to read cookies() inside a plain "use cache" function |
The installed docs' own table states this is simply not allowed — cookies()/headers()/searchParams need "use cache: private" |
Use "use cache: private" for any cached function that reads the session |
Expecting a protected Server Component's redirect() to produce a real top-level 307 under Cache Components |
A session read is always behind a <Suspense> boundary (a build error otherwise), so the response is 200 with the redirect embedded in the stream — reproduced across three repeated requests in section 5, not just a first-hit quirk |
Add an optimistic proxy check (section 5) if a real, fast top-level redirect matters for the common case; keep the DAL check as the actual guarantee either way |
| Treating the proxy's optimistic check as sufficient on its own | The installed docs state directly that Proxy "should not be used as a full session management or authorization solution" — and a later matcher refactor could silently stop covering a path (Part 14, section 6) | Always keep the authoritative check in the DAL, called from inside the protected page/action/route itself |
Comparing a submitted password (or its hash) with === |
Leaks timing information about how many leading bytes matched | Use crypto.timingSafeEqual (this part's verifyCredentials) or an equivalent constant-time comparison |
Quick recap
iron-sessionwas chosen the same evidence-based wayDESIGN-NOTES.mdchosebetter-sqlite3over Prisma: a stable, recentlatesttag, no external service required, and it's the exact library the installed Next.js docs themselves name and use as their own Cache Components auth example.- A session is a sealed, encrypted cookie (
getIronSession(await cookies(), options)), created withsession.save()inside a Server Action and destroyed withsession.destroy()on logout — nothing about the session is readable or forgeable without the server's own password. - The DAL pattern centralizes "who is signed in" into one
getCurrentUser/requireUserpair;"use cache: private"is what lets that pair readcookies()while still being cacheable under this install's default Cache Components model. - A parent layout's own auth check does not protect the routes it wraps — proven by actually serving protected content to an unauthenticated request with only the layout checking, then fixing it by calling the DAL inside the page itself. This is this part's single most important, and most easily-missed, lesson.
- The Server Component DAL check is authoritative but always returns
200(redirect embedded in the stream) under Cache Components; an optimistic proxy check (iron-session's ownnextProxyCookiesadapter) gets a real top-level307instead — measured side by side, not asserted. Keep both; the proxy check is a fast common-case optimization, never a substitute for the DAL.
Checklist
- I can state, with the actual npm evidence, why this part uses
iron-sessionrather than a full external Auth Library or NextAuth specifically. - I logged in for real with
curl, read the real sealed session cookie in theSet-Cookieheader, and used it on a later request to reach a protected page. - I reproduced the central finding myself: removed a protected page's own
requireUser()call (keeping the layout's nav check), and watched protected-looking content render for an unauthenticated request — then restored the check. - I can explain why
"use cache: private", not plain"use cache", is required for a cached function that readscookies(). - I compared the DAL-only redirect (always
200, redirect embedded in the stream, reproduced across repeated requests) against the proxy-based optimistic redirect (a real307) and can state why this course keeps both rather than picking one.