Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 3

Lab: Move a Signed-In Dashboard to the Server

Build a small Next.js 16 shop app with a static landing page and a signed-in dashboard, watch the server stream a slow panel, save a note through a Server Action without JavaScript, and prove authorisation with two accounts and a forged cookie.

Contentsand lesson path

What you will learn

  • Compare client-side rendering, server-side rendering, static generation with revalidation and streaming, and choose a mode per route from data freshness and performance needs.
  • Split a page into Server and Client Components, placing the use client boundary as low as possible and keeping secrets and server-only code out of the client bundle.
  • Fetch data in Server Components, stream slow sections with Suspense, and control caching and revalidation by time and on demand.
  • Mutate data with Server Actions or Route Handlers that validate input on the server and revalidate affected routes, and diagnose hydration mismatches.
  • Add sign-in through an identity provider or auth library (OAuth 2.0 / OpenID Connect), keep the session in a secure HttpOnly cookie rather than browser storage, and enforce authorization in Server Components, Server Actions and Route Handlers instead of only hiding UI.

Prerequisites: Next.js App Router & Routing

01. Goal and setup

This lab builds the shop app the other lessons used as their example: a static landing page, a dashboard rendered per request from a server-side session, a risk panel that streams in behind Suspense, a Server Action that validates and saves a note, and a notes API that answers only with the signed-in user's rows. You verify everything with curl, including what happens to a forged cookie.

You need Node.js 22 or newer and npm. The lab was tested with Node 22.23, Next.js 16.4.6 (Turbopack), React 19.3.1 and TypeScript 7.0. Do not install older 16.4 or 19.3 releases: some have published security advisories. There is no database: the data layer keeps notes and sessions in memory and adds fixed delays to stand in for query time.

Terminal — scaffold the project
mkdir shop-demo && cd shop-demo
npm init -y
npm install [email protected] [email protected] [email protected]
npm install -D typescript @types/react @types/react-dom @types/node
Illustrative output (package counts and timings vary)
added 24 packages, and audited 25 packages in 30s
found 0 vulnerabilities
added 10 packages, and audited 35 packages in 6s
found 0 vulnerabilities

Inside package.json, replace the scripts section so you can run Next directly:

package.json — scripts only
"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start"
},

02. Step 1: The skeleton and the landing page

The App Router maps folders to URLs (the full model is in the App Router skill). Here you need three rules: app/layout.tsx wraps every page, app/page.tsx is /, and a folder with a route.ts becomes an API route. Create the root layout and a landing page:

TSX · app/layout.tsx and app/page.tsx
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body style={{ fontFamily: "system-ui, sans-serif", margin: "2rem" }}>
        {children}
      </body>
    </html>
  );
}

// app/page.tsx
export default function Home() {
  return (
    <main>
      <h1>Fresh Market</h1>
      <p>Handmade food boxes, delivered weekly.</p>
    </main>
  );
}

Build once to confirm the skeleton compiles. Next detects TypeScript and writes a tsconfig.json for you:

Expected output — `npm run build` (tail)
Route (app)
┌ ○ /
└ ○ /_not-found


○  (Static)  prerendered as static content

Both routes are marked ○ (Static): nothing in them reads request data, so Next prerendered them at build time.

03. Step 2: Session cookie and data layer

A session cookie must not say who the user is, because any HTTP client can send any cookie value: a cookie holding ben:member can be edited to amara:admin. So the cookie carries only a session id, a long random string, and the server keeps a table that maps each id to a user. An edited or guessed id matches no row and counts as signed out. randomBytes is Node's cryptographically secure generator, and 32 bytes are far too many to guess. The data layer is a fake database with a fast portfolio and a slow risk feed:

TSX · lib/session.ts
import { randomBytes } from 'node:crypto';
import { cookies } from 'next/headers';

export type Session = { user: string; role: 'admin' | 'member' };
export const SESSION_COOKIE = 'session';
export const SESSION_MAX_AGE = 60 * 60 * 8; // seconds: one working day

// The user records. A real app keeps them in its database, keyed by the
// identity provider's stable user id (the `sub` claim of the ID token).
const users = new Map<string, Session['role']>([
  ['amara', 'admin'],
  ['ben', 'member'],
]);

// The session table: random id -> user. A real app uses a database or Redis.
type Stored = Session & { expiresAt: number };
const g = globalThis as unknown as { __sessions?: Map<string, Stored> };
const sessions = (g.__sessions ??= new Map<string, Stored>());

export function createSession(user: string): string | null {
  const role = users.get(user);
  if (!role) return null;
  const id = randomBytes(32).toString('base64url'); // 256 random bits
  sessions.set(id, { user, role, expiresAt: Date.now() + SESSION_MAX_AGE * 1000 });
  return id;
}

export function deleteSession(id: string | undefined) {
  if (id) sessions.delete(id);
}

export async function getSession(): Promise<Session | null> {
  const id = (await cookies()).get(SESSION_COOKIE)?.value;
  const stored = id ? sessions.get(id) : undefined;
  if (!id || !stored) return null; // no cookie, or an id we never issued
  if (stored.expiresAt < Date.now()) {
    sessions.delete(id);
    return null;
  }
  return { user: stored.user, role: stored.role };
}
TSX · lib/data.ts
// Demo store attached to globalThis so Route Handlers and Server Components
// share the exact same state in production bundles. A real app uses a database.
type Note = { id: number; title: string };
const globalStore = globalThis as unknown as {
  __demoNotes?: Map<string, Note[]>;
};
const notes = (globalStore.__demoNotes ??= new Map<string, Note[]>());

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export async function getPortfolio(user: string) {
  await sleep(60);
  return { user, total: '£12,480',
    holdings: ['AAPL', 'NVDA', 'MSFT'].map((s) => ({ symbol: s })) };
}

export async function getRiskFeed(user: string) {
  await sleep(2000); // the slow external risk API
  return ['AAPL 2.1%', 'NVDA 5.4%', 'MSFT 1.3%'].map((s) => ({ label: s }));
}

export function listNotes(user: string) {
  return notes.get(user) ?? [];
}

export function addNote(user: string, title: string) {
  const list = notes.get(user) ?? [];
  const note = { id: list.length + 1, title };
  list.push(note);
  notes.set(user, list);
  return note;
}
TSX · app/api/session/route.ts
import { NextResponse, type NextRequest } from 'next/server';
import {
  createSession, deleteSession, getSession, SESSION_COOKIE, SESSION_MAX_AGE,
} from '../../../lib/session';

export async function GET() {
  const session = await getSession();
  if (!session) {
    return NextResponse.json({ error: 'not signed in' }, { status: 401 });
  }
  return NextResponse.json(session);
}

export async function POST(request: Request) {
  const body = (await request.json().catch(() => null)) as
    | { user?: string }
    | null;
  const user = typeof body?.user === 'string' ? body.user.trim() : '';
  // Stand-in for an identity provider: it trusts the name it is sent.
  const id = createSession(user);
  if (!id) {
    return NextResponse.json({ error: 'unknown user' }, { status: 401 });
  }
  const response = NextResponse.json({ user }, { status: 201 });
  response.cookies.set(SESSION_COOKIE, id, {
    httpOnly: true, // page scripts cannot read it
    secure: true, // HTTPS only (browsers make an exception for localhost)
    sameSite: 'lax', // not sent on cross-site POSTs
    path: '/', // sent to every route of the app
    maxAge: SESSION_MAX_AGE, // the browser drops it after 8 hours
  });
  return response;
}

export async function DELETE(request: NextRequest) {
  deleteSession(request.cookies.get(SESSION_COOKIE)?.value); // server forgets
  const response = NextResponse.json({ signedOut: true });
  response.cookies.delete(SESSION_COOKIE); // browser forgets
  return response;
}

httpOnly hides the cookie from page scripts, so code injected through a cross-site scripting (XSS) bug cannot steal it. secure means HTTPS only; browsers and curl make an exception for http://localhost, which is why the lab still works, but on any other plain-HTTP address the browser drops the cookie. sameSite: 'lax' keeps it off form posts that start on another site, path: '/' sends it to every route, and maxAge makes the browser forget it after eight hours, while the server checks its own expiresAt.

Sign-out has two halves: DELETE removes the row from the session table and tells the browser to delete its copy. The server half matters most, because a copy saved earlier stops working once its id is gone. The Next.js authentication guide also describes stateless sessions, where the user data itself is signed or encrypted with a server secret (iron-session or jose) and verified on every request.

04. Step 3: The dashboard, its panels and the note form

The dashboard page reads the session, fetches the fast portfolio in the shell, streams the slow risk panel inside Suspense, and renders the note form as the only Client Component on the page. First the action and the form:

TSX · app/dashboard/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { addNote } from '../../lib/data';
import { getSession } from '../../lib/session';

export type NoteState =
  | { status: 'idle' }
  | { status: 'saved' }
  | { status: 'error'; message: string };

export async function saveNote(
  _prev: NoteState,
  formData: FormData,
): Promise<NoteState> { // without it, status widens to string
  const session = await getSession(); // its own request, its own check
  if (!session) {
    return { status: 'error',
      message: 'Sign in before saving a note.' };
  }
  const title = formData.get('title');
  if (typeof title !== 'string' || title.trim().length === 0
      || title.length > 100) {
    return { status: 'error',
      message: 'Give the note a title of 1 to 100 characters.' };
  }
  addNote(session.user, title.trim());
  revalidatePath('/dashboard');
  return { status: 'saved' };
}
TSX · app/dashboard/note-form.tsx
'use client';

import { useActionState } from 'react';
import { saveNote, type NoteState } from './actions';

const initial: NoteState = { status: 'idle' };

export default function NoteForm() {
  const [state, formAction, pending] = useActionState(saveNote, initial);
  return (
    <form action={formAction}>
      <h2>Quick note</h2>
      <label htmlFor="title">Note title</label>
      <input id="title" name="title" maxLength={100} required />
      <button type="submit" disabled={pending}>
        {pending ? 'Saving…' : 'Save note'}
      </button>
      <p role="status">
        {state.status === 'error' ? state.message
          : state.status === 'saved' ? 'Note saved.' : ''}
      </p>
    </form>
  );
}
TSX · app/dashboard/page.tsx
import { Suspense } from 'react';
import { getPortfolio, getRiskFeed, listNotes } from '../../lib/data';
import { getSession } from '../../lib/session';
import NoteForm from './note-form';

export default async function DashboardPage() {
  const session = await getSession();
  if (!session) {
    return (
      <main><h1>Dashboard</h1>
        <p>Please sign in to view your portfolio.</p></main>
    );
  }
  const portfolio = await getPortfolio(session.user);
  return (
    <main>
      <h1>{`Portfolio for ${session.user}`}</h1>
      <p>Total value: {portfolio.total}</p>
      <Suspense fallback={<p role="status">Loading risk data…</p>}>
        <RiskPanel user={session.user} />
      </Suspense>
      <section aria-labelledby="notes-heading">
        <h2 id="notes-heading">Your notes</h2>
        {listNotes(session.user).length === 0 ? (
          <p>No notes yet</p>
        ) : (
          <ul>
            {listNotes(session.user).map((n) => (
              <li key={n.id}>{n.title}</li>
            ))}
          </ul>
        )}
      </section>
      <NoteForm />
    </main>
  );
}

async function RiskPanel({ user }: { user: string }) {
  const rows = await getRiskFeed(user);
  return (
    <section aria-labelledby="risk-heading">
      <h2 id="risk-heading">Volatility feed</h2>
      <ul>{rows.map((r) => <li key={r.label}>{r.label}</li>)}</ul>
    </section>
  );
}
TSX · app/api/notes/route.ts
import { NextResponse } from 'next/server';
import { addNote, listNotes } from '../../../lib/data';
import { getSession } from '../../../lib/session';

export async function GET() {
  const session = await getSession();
  if (!session) {
    return NextResponse.json({ error: 'sign in first' },
      { status: 401 });
  }
  return NextResponse.json(
    { user: session.user, notes: listNotes(session.user) });
}

export async function POST(request: Request) {
  const session = await getSession();
  if (!session) {
    return NextResponse.json({ error: 'sign in first' },
      { status: 401 });
  }
  const body = (await request.json().catch(() => null)) as
    | { title?: string }
    | null;
  const title = body?.title;
  if (typeof title !== 'string' || title.trim().length === 0
      || title.length > 100) {
    return NextResponse.json({ error: 'title is required' },
      { status: 422 });
  }
  return NextResponse.json(addNote(session.user, title.trim()),
    { status: 201 });
}

05. Step 4: Build, start, sign in, forge a cookie

Build again and read the table: the landing page stayed static, everything that touches the session went dynamic. Then start the production server on port 3100 in a second terminal:

Terminal
npm run build
npm run start -- -p 3100
Illustrative output — `npm run build` (tail) and `npm run start` (timings vary)
Route (app)
┌ ○ /
├ ○ /_not-found
├ ƒ /api/notes
├ ƒ /api/session
└ ƒ /dashboard


○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand

▲ Next.js 16.4.6
- Local:         http://localhost:3100
✓ Ready in 556ms

Sign in as amara. -c amara.txt makes curl save the cookies it receives into a file and -b amara.txt sends them back, as a browser does; treat each cookie file as one browser. tr puts each cookie attribute on its own line:

Terminal — sign in and read the session back
curl -si -c amara.txt -X POST http://localhost:3100/api/session \
  -H "Content-Type: application/json" -d '{"user":"amara"}' \
  | grep -iE "^HTTP|^set-cookie|^\{" | tr ";" "\n"
curl -s -w '\n' -b amara.txt http://localhost:3100/api/session
Illustrative output (the session id and dates differ on every run)
HTTP/1.1 201 Created
set-cookie: session=-KP7Qcm6TuDL1akaD-mU2DjWn2oQ6rDUxSXLf5g6L8Q
 Path=/
 Expires=Tue, 17 Nov 2026 06:25:58 GMT
 Max-Age=28800
 Secure
 HttpOnly
 SameSite=lax
{"user":"amara"}
{"user":"amara","role":"admin"}

The cookie value is random and says nothing about amara; her role came from the server's user record. Now play the attacker: no cookie, two hand-made cookies, and a sign-in for a name with no user record:

Terminal — no cookie, forged cookies, unknown user
curl -s http://localhost:3100/dashboard | grep -o "Please sign in" | head -1
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3100/api/notes
curl -s -o /dev/null -w '%{http_code}\n' \
  -H "Cookie: session=amara:admin" http://localhost:3100/api/notes
curl -s -w "\n" -H "Cookie: session=ben" http://localhost:3100/api/session
curl -s -w '\n' -X POST http://localhost:3100/api/session \
  -H "Content-Type: application/json" -d '{"user":"mallory"}'
Expected output
Please sign in
401
401
{"error":"not signed in"}
{"error":"unknown user"}

Each forged value matched no row in the session table, so it counted as signed out. If the cookie held user:role directly, session=amara:admin would have made you an admin.

06. Step 5: Watch the slow panel stream

Fetch the dashboard with a script that prints each chunk as it arrives, timed from the moment the request starts. It reads the cookie from COOKIE; awk takes the session id from amara's cookie file (column 6 is the name, column 7 the value):

JavaScript · fetch-stream.mjs
const start = Date.now(); // before the request, so the wait for headers counts
const res = await fetch("http://localhost:3100/dashboard", {
  headers: { cookie: process.env.COOKIE ?? "" },
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
for (;;) {
  const { done, value } = await reader.read();
  if (done) {
    console.log(`[${String(Date.now() - start).padStart(4)} ms] done`);
    break;
  }
  const text = decoder.decode(value);
  const has = (s) => (text.includes(s) ? "yes" : "no");
  console.log(`[${String(Date.now() - start).padStart(4)} ms]`
    + ` shell:${has("Portfolio for")} fallback:${has("Loading risk")}`
    + ` panel:${has("Volatility feed")}`);
}
Terminal
export COOKIE="session=$(awk '$6 == "session" { print $7 }' amara.txt)"
node fetch-stream.mjs
Illustrative output — `node fetch-stream.mjs` (timings and chunk count vary)
[ 168 ms] shell:yes fallback:yes panel:no
[ 169 ms] shell:yes fallback:yes panel:no
[2150 ms] shell:no fallback:no panel:yes
[2152 ms] shell:no fallback:no panel:yes
[2154 ms] shell:no fallback:no panel:no
[2155 ms] done

The shell and its Loading risk data… fallback arrived first; the panel followed about two seconds later. Predict what changes without <Suspense>, then check: remove the wrapper (keep <RiskPanel />), rebuild, sign in again and rerun. The first line now appears after about two seconds and already holds the panel: the server could not send the shell before the slow component finished. Restore the wrapper afterwards.

07. Step 6: Save a note through the Server Action

Without JavaScript the note form still works: Next renders hidden $ACTION_… fields that name the Server Action, and the browser posts them with the title. This script does the same and prints the status code and the message from the re-rendered page. An optional second argument posts with a different cookie:

JavaScript · post-note.mjs
// Submit the note form the way a browser without JavaScript does.
const url = "http://localhost:3100/dashboard";
const cookie = process.env.COOKIE ?? "";
const [title = "", postCookie = cookie] = process.argv.slice(2);
const html = await (await fetch(url, { headers: { cookie } })).text();
const form = new FormData();
const hidden = /<input type="hidden" name="([^"]+)"(?: value="([^"]*)")?\/>/g;
for (const [, name, value = ""] of html.matchAll(hidden)) {
  form.append(name, value.replaceAll("&quot;", '"').replaceAll("&amp;", "&"));
}
form.append("title", title);
const res = await fetch(url, {
  method: "POST", headers: { cookie: postCookie }, body: form,
});
const page = await res.text();
const message = page.match(/<\/button><p role="status">([^<]*)<\/p>/)?.[1]
  ?? page.match(/<p>(Please sign in[^<]*)<\/p>/)?.[1];
console.log(res.status, message);
Terminal — save, fail validation, forge
node post-note.mjs "Oat milk restock"
node post-note.mjs ""
node post-note.mjs "Forged note" "session=amara:admin"
curl -s -b amara.txt http://localhost:3100/dashboard \
  | grep -oE "<li>(Oat milk restock|Forged note)</li>"
Expected output
200 Note saved.
200 Give the note a title of 1 to 100 characters.
200 Please sign in to view your portfolio.
<li>Oat milk restock</li>

The first post saved the note, and revalidatePath sent the refreshed list back in the same response. The empty title failed validation. The forged post carried the real action fields with a made-up cookie, and the action's own getSession check refused it, so no "Forged note" is in the list. Now sign in as a second user:

Terminal — two accounts, one route
curl -s -w '\n' -c ben.txt -X POST http://localhost:3100/api/session \
  -H "Content-Type: application/json" -d '{"user":"ben"}'
curl -s -b ben.txt http://localhost:3100/dashboard \
  | grep -oE "Portfolio for [a-z]*|No notes yet|Oat milk" | sort -u
curl -s -w '\n' -b ben.txt http://localhost:3100/api/notes
curl -s -w '\n' -b amara.txt http://localhost:3100/api/notes
Expected output
{"user":"ben"}
No notes yet
Portfolio for ben
{"user":"ben","notes":[]}
{"user":"amara","notes":[{"id":1,"title":"Oat milk restock"}]}

Ben sees his own empty list on the same URL, and the API returns only the session user's rows, because every check sits next to the data. Next.js Proxy (proxy.ts, called middleware before Next 16) can redirect signed-out visitors before a route runs, but the authentication guide calls that an optimistic check: it reads only the cookie and does not replace these checks.

08. Step 7: Static and dynamic, side by side

The response headers summarise the rendering side of the lab:

Terminal
curl -sI http://localhost:3100/ | grep -i "cache-control\|x-nextjs-cache"
curl -sI -b amara.txt http://localhost:3100/dashboard \
  | grep -i "cache-control\|x-nextjs-cache"
Expected output
x-nextjs-cache: HIT
Cache-Control: s-maxage=31536000
Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate

The landing page is answered from the shared cache; the dashboard is private and uncached, because its HTML belongs to one session.

09. Step 8: Sign out, then replay the old cookie

Keep a copy of amara's session id, sign out, and then replay the copy, as an attacker who had stolen the cookie would:

Terminal
OLD=$(awk '$6 == "session" { print $7 }' amara.txt)
curl -si -b amara.txt -c amara.txt -X DELETE http://localhost:3100/api/session \
  | grep -iE "^HTTP|^set-cookie|^\{"
curl -s -w '\n' -b amara.txt http://localhost:3100/api/session
curl -s -o /dev/null -w '%{http_code}\n' \
  -H "Cookie: session=$OLD" http://localhost:3100/api/notes
curl -s -w '\n' -b ben.txt http://localhost:3100/api/session
Expected output
HTTP/1.1 200 OK
set-cookie: session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT
{"signedOut":true}
{"error":"not signed in"}
401
{"user":"ben","role":"member"}

The browser half emptied the cookie file, and the server half made the old id worthless, so the replayed copy gets 401 while Ben stays signed in.

10. Check your understanding

Practice check · 3 questions

Lab debrief

Three questions about what you just ran.

Q1. GET /api/notes with no session cookie returned 401. Which line of the route handler decided that?
Q2. In step 5 the risk panel's HTML arrived about two seconds after the shell. What made that possible?
Q3. In step 4, `Cookie: session=amara:admin` got 401 from /api/notes. What made the server refuse it?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

The risk feed is identical for everyone. Move it behind use cache with cacheTag("risk") (enable cacheComponents: true in next.config.ts first), invalidate the tag from a POST /api/risk/refresh route handler, and verify the refresh with curl.

Then add a "delete note" Server Action that refuses a note owned by someone else, and test it with both cookie files. Finally, revoke a role: createSession copies the role into the session, so changing amara to member in users has no effect until she signs in again. Make getSession read the role from the user record on each request and prove with curl that the change applies at once.

12. Review prompt

Without looking back, reproduce the build table and say why each route got its symbol. List, in order, every check a note goes through between a browser submit and the notes list. Then explain to a colleague why session=amara:admin was refused, what each half of sign-out deletes, and which part of the lab an OpenID Connect library would replace.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check