AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 7

    Next.js App Router and Full-Stack React

    TechLearningPro's player from lessons 5 and 6 rendered in the browser and then asked the browser to fetch the outline.

    Course progress0%
    Focus
    18 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 07 · Full-Stack Engineering Foundations

    Lesson Overview

    TechLearningPro's player from lessons 5 and 6 rendered in the browser and then asked the browser to fetch the outline. That works, and it has a cost: the learner stares at "Loading lesson…" on every cold visit, the catalog title is invisible to a simple HTML fetch, and any secret you mistakenly import into the player ships in the JavaScript bundle. The team also had a pages/ habit of getServerSideProps beside a new app/ folder, and nobody could say which router owned /lessons.

    The App Router is Next.js's file-based router for React Server Components. A page.tsx is a route. A layout.tsx is shared UI that stays mounted across navigations under that segment. By default, components in app/ run on the server. A file with 'use client' at the top is a Client Component, and that is where useState, useQuery, and event handlers live. The point of this lesson is the boundary: what may run only on the server, what must ship to the browser, and how a read, a route handler, and a server action share one lesson id without becoming three APIs.

    The Next.js course is the full framework track. This lesson lands the App Router slice the AI platform needs: one dynamic lesson route, a server read, a client island for the checkbox, a route handler, and a server action that does not trust the browser. Accessible UI Engineering and Design Systems then holds the controls to a WCAG bar. Backend Engineering with Node.js replaces the in-memory fixture with a real service when you are ready.

    Version contract, so snippets are not folklore:

    • Client components use React 18 APIs (useState, useTransition). Do not use React 19-only hooks such as useActionState in this lesson.
    • Server module samples follow the Next.js 14 App Router pairing that ships with React 18: params on a page is a plain object, and cookies() / headers() from next/headers are synchronous.
    • Next.js 15 changed those request APIs to async (await params, await cookies()) and stopped caching fetch by default. A labeled note shows the difference. Read your package.json and the current Next.js App Router docs before you paste either form into a repo.
    • This lesson does not use the Pages Router. Imports of next/router, getServerSideProps, and getStaticProps are the wrong module for app/. Client navigation hooks are useRouter, usePathname, and useSearchParams from next/navigation.

    No sample contains a secret, a model API key, or a made-up vendor URL. Server code reads process.env.CATALOG_API_BASE_URL only as a placeholder name for a base URL you configure outside the bundle. If the variable is missing, the sample fails closed.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Explain what the App Router decides from the file tree: route, layout, loading, error, and not-found.
    2. State why components in app/ are Server Components unless marked 'use client'.
    3. Draw the client boundary and list what crosses it: serializable props, not functions from the server, not secrets.
    4. Fetch on the server with an explicit cache mode so Next.js 14 and 15 readers do not assume the same default.
    5. Add loading.tsx and a Client Component error.tsx that do not leak internal errors to the learner.
    6. Implement a Route Handler that validates lessonId and returns JSON without trusting a user id from the query string.
    7. Implement a Server Action that validates input and leaves authorization as an explicit server-side seam.
    8. Keep TanStack Query clients per browser session and per server request, never as a module singleton in server code.
    9. Use next/link and next/navigation instead of Pages Router APIs.
    10. Name the Next.js 15 async request-API change so an upgrade does not ship a sync cookies() call that no longer typechecks.
    11. Test a pure validator and a server function without standing up a production host.
    12. Hand lesson 8 a page that uses real buttons, headings, and labels rather than clickable divs.

    Prerequisites

    • Lessons 5 and 6: presentational LessonOutline, query keys, and the rule that the server authorizes writes.
    • TypeScript for Production Full-Stack Development for props that cross the server/client boundary. They must be serializable.
    • A Next.js app on the App Router. Create it with the official create-next-app prompt from the Next.js docs for your chosen version, and commit the lockfile. This lesson does not invent CLI flags.
    • Comfort reading environment variables. Server-only variables must not use the NEXT_PUBLIC_ prefix. That prefix inlines the value into browser JavaScript.

    If the repo still has only pages/, do not half-migrate inside this assignment. New lesson routes go under app/ only.

    Detailed Core Concepts

    What the App Router is for

    The App Router maps folders under app/ to URL segments. app/lessons/[lessonId]/page.tsx handles /lessons/react-components and receives lessonId. app/layout.tsx wraps the whole application. Nested layouts wrap a segment. Layouts preserve client state when you navigate between sibling pages, which is why a layout is the wrong place to store the current lesson payload: it will not remount just because lessonId changed.

    Special files are conventions, not components you mount by hand:

    FileRole
    page.tsxThe route's UI. A folder without a page is not a route.
    layout.tsxShared UI for the segment and its children.
    loading.tsxSuspense fallback while the segment waits.
    error.tsxError UI for the segment. It must be a Client Component.
    not-found.tsxUI for notFound() from next/navigation.
    route.tsAn HTTP handler instead of a page. Export GET, POST, and the other methods you support.

    Server Components and the client boundary

    A Server Component can await a fetch, read server-only modules, and send the rendered result to the client. It does not have useState, browser events, or window. A Client Component can use state and effects, and it is included in the browser bundle. The directive 'use client' marks the module and the modules it imports, until a child is passed in from a server parent as children.

    That last sentence is the composition rule. You cannot import a Server Component into a Client Component. You can render a Server Component as children of a client shell if the server parent passes it. For the player, the server page loads the lesson and passes plain data into a small client island:

    text
    app/lessons/[lessonId]/page.tsx Server Component, awaits the read
    |
    v props: { lessonId, title, items } serializable
    features/lesson-player/LessonIsland.tsx 'use client', events, mutation
    |
    v
    LessonOutline.tsx presentational, no fetch

    Props that cross the boundary must be JSON-serializable. No class instances, no functions defined on the server, no Map. Callbacks the island needs are either client functions or Server Actions referenced from the client.

    Why the boundary exists

    Without it, teams mark the root layout 'use client' and the entire tree ships to the browser. Server data fetching, smaller bundles, and secret-keeping disappear together. The opposite mistake is trying to use useState in a Server Component and then sprinkling the directive on every file until the server has nothing left to do.

    The boundary is also a trust line. Code in a Client Component is visible to the learner. API keys, database URLs with passwords, and service tokens stay in server modules. NEXT_PUBLIC_ variables are public by design. Catalog base URLs that are not secret can still stay server-only if only the server fetches them.

    Data fetching and cache intent

    fetch in a Server Component participates in Next.js caching. The default has changed:

    • Next.js 14 cached fetch unless you set cache: 'no-store' or a revalidate option, with important exceptions when dynamic functions such as cookies() made the route dynamic.
    • Next.js 15 does not cache fetch unless you opt in.

    This course's lesson payload is per learner once completion exists, so it must not be cached in a shared public cache. Set the mode in code:

    tsx
    await fetch(url, { cache: "no-store", headers: { accept: "application/json" } });

    For public, non-personalized catalog copy you may opt into caching with { next: { revalidate: 60, tags: ["catalog"] } } and later call revalidateTag("catalog") or revalidatePath from next/cache after a publish. Do not tag a personalized progress response as public catalog. export const dynamic = "force-dynamic" and export const revalidate = 60 are segment configs documented by Next.js; use them when the segment's policy is clearer at the page than on one call. Verify the current default in the docs for your version so a tutorial written for the other major version does not leak one learner's outline into a static page.

    Route Handlers

    app/api/lessons/[lessonId]/route.ts exports functions named after HTTP methods. They run on the server. They are the JSON API lesson 6 already called. Validate the id. Use the session for the learner identity. Return NextResponse.json. Do not accept userId from the query string as the person whose progress you return.

    Server Actions

    A Server Action is a function marked with 'use server' that the client can call. Next.js posts to it. It is still an HTTP endpoint: anyone who can reach the site can invoke it with a crafted body. Validate arguments. Authorize with the server session. Do not take the learner id from the argument list. Next.js documents an Origin check for Server Action requests; do not disable it to "make local development easier" in a shared environment.

    This lesson uses useTransition on the client to track pending UI, which is valid React 18. It does not use useFormState / useActionState, because that hook's module and name depend on the React major version.

    Navigation

    <Link href={"/lessons/" + lessonId}> from next/link is the in-app navigation primitive. Build paths from known ids you validated, not from a raw ?next= query that an attacker can set to an external site. If you read a return path, allow only relative paths you recognize.

    redirect("/login") and notFound() from next/navigation are server-side control flow. notFound() renders the nearest not-found UI. redirect throws a special signal; do not catch it and turn it into a 500.

    Errors and loading

    loading.tsx shows while the async page waits. error.tsx receives an error object and reset. Log error.digest or a stable name on the server if you have a logger, and show fixed copy to the learner. The error object in production is not a place to render stack traces. error.tsx starts with 'use client'.

    Pages Router is a different product surface

    You will see older articles use pages/lessons/[lessonId].tsx, useRouter from next/router, and context.params inside getServerSideProps. Those APIs are real and they are not this lesson. Mixing them with app/ in one mental model is how people call router.query and get nothing.

    Architecture and Design Diagrams

    flowchart TB
      subgraph edge [Browser]
        Link[next/link navigation]
        Island["LessonIsland use client"]
        Outline[LessonOutline]
      end
    
      subgraph next [Next.js server]
        Layout[app/layout.tsx]
        Page["app/lessons/lessonId/page.tsx"]
        Action["markItemComplete server action"]
        Route["app/api/lessons/lessonId/route.ts"]
      end
    
      subgraph data [Your backend later]
        API[Progress service]
        DB[(Database)]
      end
    
      Link --> Page
      Layout --> Page
      Page -->|"serializable props, cache no-store"| Island
      Island --> Outline
      Island --> Action
      Action --> API
      Route --> API
      API --> DB
    text
    GET /lessons/:lessonId
    -> Server Component page
    -> fetch cache: no-store
    -> authorize on the server
    -> HTML plus client island
    -> hydrate island only
    POST server action markItemComplete(itemId)
    -> Origin check performed by the framework
    -> validate itemId
    -> session, not a client userId, decides who is writing
    -> failure returns { ok: false } without writing
    -> success revalidates this path
    GET /api/lessons/:lessonId
    -> same authorization rule as the page
    -> JSON for the lesson 6 client, or for non-Next callers you actually support

    Trust boundary: Server Components and Route Handlers and Server Actions are on the server, but their inputs are still caller-controlled. The client island is fully exposed. NEXT_PUBLIC_ values are on the wrong side of the line for secrets.

    Technical Explanation

    Request for /lessons/react-components on Next.js 14:

    1. Next.js matches app/lessons/[lessonId]/page.tsx.
    2. The page function receives { params: { lessonId: "react-components" } }.
    3. The page validates the id against a conservative pattern. Invalid ids call notFound().
    4. The page fetches with cache: "no-store" and forwards the incoming cookie only to your own origin, if you have a session. This sample uses a server-side fixture when no catalog URL is configured, so the lesson runs without a secret.
    5. The page returns JSX that includes <LessonIsland ... /> with plain props.
    6. The server sends rendered output. The browser hydrates the island.
    7. A click calls the server action with the item id. The action checks the id again. Authorization against a real session is a function you plug in when lesson 48 exists; the seam must not default to "allow."

    If loading.tsx exists, Next.js shows it while step 4 is in flight. If the page throws, error.tsx renders. notFound() does not go through error.tsx; it uses not-found.tsx.

    Next.js 15 difference, same route:

    tsx
    export default async function Page(props: { params: Promise<{ lessonId: string }> }) {
    const { lessonId } = await props.params;
    // rest of the server read stays the same
    }

    cookies() and headers() would also be awaited. Do not memorize one snippet for every version. Encode the version in the PR description when you touch request APIs.

    Dynamic rendering: calling cookies() or headers(), or using no-store, opts the route out of static prerender. Personalized progress should be dynamic. A marketing page about the course should not call cookies() "just in case" or it will not be static.

    Practical Implementation

    File layout:

    text
    app/layout.tsx
    app/lessons/[lessonId]/page.tsx
    app/lessons/[lessonId]/loading.tsx
    app/lessons/[lessonId]/error.tsx
    app/lessons/[lessonId]/not-found.tsx
    app/api/lessons/[lessonId]/route.ts
    src/features/lesson-player/ids.ts
    src/features/lesson-player/LessonIsland.tsx
    src/features/lesson-player/actions.ts

    Simple example: validate ids once

    ts
    // src/features/lesson-player/ids.ts
    const LESSON_ID = /^[a-z0-9-]{1,80}$/;
    export function isLessonId(value: string): boolean {
    return LESSON_ID.test(value);
    }

    Use the same helper in the page, the route, and the action. One pattern, one test.

    Intermediate example: server page and client island

    Next.js 14 page signature:

    tsx
    // app/lessons/[lessonId]/page.tsx
    import type { Metadata } from "next";
    import { notFound } from "next/navigation";
    import { LessonIsland } from "../../../src/features/lesson-player/LessonIsland";
    import { isLessonId } from "../../../src/features/lesson-player/ids";
    import { loadLesson } from "../../../src/features/lesson-player/loadLesson";
    type PageProps = { params: { lessonId: string } };
    export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
    if (!isLessonId(params.lessonId)) return { title: "Lesson" };
    return { title: params.lessonId };
    }
    export default async function LessonPage({ params }: PageProps) {
    if (!isLessonId(params.lessonId)) notFound();
    const lesson = await loadLesson(params.lessonId);
    if (!lesson) notFound();
    return (
    <LessonIsland
    lessonId={lesson.id}
    title={lesson.title}
    items={lesson.items}
    />
    );
    }
    tsx
    // src/features/lesson-player/loadLesson.ts
    import { isLessonId } from "./ids";
    export type LessonRecord = {
    id: string;
    title: string;
    items: { id: string; title: string; complete: boolean }[];
    };
    const FIXTURES: Record<string, LessonRecord> = {
    "react-components": {
    id: "react-components",
    title: "React fundamentals",
    items: [
    { id: "props-and-state", title: "Props and state", complete: false },
    { id: "server-client", title: "Server and client", complete: false },
    ],
    },
    };
    export async function loadLesson(lessonId: string): Promise<LessonRecord | null> {
    if (!isLessonId(lessonId)) return null;
    const base = process.env.CATALOG_API_BASE_URL;
    if (!base) {
    return FIXTURES[lessonId] ?? null;
    }
    const response = await fetch(`${base}/v1/lessons/${encodeURIComponent(lessonId)}`, {
    cache: "no-store",
    headers: { accept: "application/json" },
    });
    if (response.status === 404) return null;
    if (!response.ok) {
    throw new Error(`lesson_request_failed:${response.status}`);
    }
    const body: unknown = await response.json();
    if (!isLessonRecord(body)) {
    throw new Error("lesson_payload_invalid");
    }
    return body;
    }
    function isLessonRecord(value: unknown): value is LessonRecord {
    if (typeof value !== "object" || value === null) return false;
    const record = value as Record<string, unknown>;
    return typeof record.id === "string" && typeof record.title === "string" && Array.isArray(record.items);
    }

    CATALOG_API_BASE_URL is optional. Unset, the fixture serves two known lessons. Set, the server calls your own API. Do not prefix it with NEXT_PUBLIC_. Do not commit a real .env.

    tsx
    // app/lessons/[lessonId]/loading.tsx
    export default function LoadingLesson() {
    return <p>Loading lesson…</p>;
    }
    tsx
    // app/lessons/[lessonId]/error.tsx
    "use client";
    export default function LessonError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
    return (
    <div role="alert">
    <p>This lesson could not be displayed.</p>
    <button type="button" onClick={() => reset()}>
    Try again
    </button>
    </div>
    );
    }

    Do not render error.message or error.stack in this component.

    Enterprise example: route handler and server action

    tsx
    // app/api/lessons/[lessonId]/route.ts
    import { NextResponse } from "next/server";
    import { isLessonId } from "../../../../src/features/lesson-player/ids";
    import { loadLesson } from "../../../../src/features/lesson-player/loadLesson";
    type Context = { params: { lessonId: string } };
    export async function GET(_request: Request, context: Context) {
    const { lessonId } = context.params;
    if (!isLessonId(lessonId)) {
    return NextResponse.json({ error: "invalid_lesson_id" }, { status: 400 });
    }
    try {
    const lesson = await loadLesson(lessonId);
    if (!lesson) {
    return NextResponse.json({ error: "not_found" }, { status: 404 });
    }
    return NextResponse.json(lesson);
    } catch {
    return NextResponse.json({ error: "lesson_unavailable" }, { status: 502 });
    }
    }

    On Next.js 15, context.params is a Promise and you await it. The status codes and the refusal to read userId from the URL stay the same.

    tsx
    // src/features/lesson-player/actions.ts
    "use server";
    import { revalidatePath } from "next/cache";
    import { isLessonId } from "./ids";
    export type ActionResult = { ok: true } | { ok: false; error: "invalid" | "unauthorized" };
    export async function markItemComplete(lessonId: string, itemId: string): Promise<ActionResult> {
    if (!isLessonId(lessonId) || !isLessonId(itemId)) {
    return { ok: false, error: "invalid" };
    }
    const allowed = await sessionMayWriteProgress();
    if (!allowed) {
    return { ok: false, error: "unauthorized" };
    }
    revalidatePath(`/lessons/${lessonId}`);
    return { ok: true };
    }
    async function sessionMayWriteProgress(): Promise<boolean> {
    // Lesson 48 replaces this seam with a real session lookup.
    // The safe default is deny. A classroom fixture may return true only
    // behind an explicit non-production flag you do not commit as a secret.
    return process.env.ALLOW_FIXTURE_WRITES === "true";
    }

    ALLOW_FIXTURE_WRITES is a local switch, not a credential. Production leaves it unset, and the action returns unauthorized. That is deliberate. Do not "temporarily" return true in source.

    tsx
    // src/features/lesson-player/LessonIsland.tsx
    "use client";
    import { useState, useTransition } from "react";
    import { markItemComplete } from "./actions";
    import { LessonOutline } from "./LessonOutline";
    import type { OutlineItem } from "./types";
    type LessonIslandProps = {
    lessonId: string;
    title: string;
    items: readonly OutlineItem[];
    };
    export function LessonIsland({ lessonId, title, items }: LessonIslandProps) {
    const [message, setMessage] = useState<string | null>(null);
    const [isPending, startTransition] = useTransition();
    function toggle(itemId: string) {
    setMessage(null);
    startTransition(async () => {
    const result = await markItemComplete(lessonId, itemId);
    setMessage(result.ok ? "Saved." : "That update was not accepted.");
    });
    }
    return (
    <article>
    <h1>{title}</h1>
    <LessonOutline items={items} onToggle={toggle} />
    {isPending ? <p>Saving…</p> : null}
    {message ? <p role="status">{message}</p> : null}
    </article>
    );
    }

    The island does not import loadLesson. The server does not import useState. LessonOutline from lesson 5 stays a props-only component; add 'use client' on it only if its module is imported by the island and your bundler requires the client graph to include it. Importing a module with hooks into the island already places that module on the client. A file with no hooks and no browser APIs can stay shared. If the compiler complains, put 'use client' on LessonOutline and keep it free of server imports.

    Root layout, minimal and server-rendered:

    tsx
    // app/layout.tsx
    import type { ReactNode } from "react";
    export const metadata = { title: "TechLearningPro" };
    export default function RootLayout({ children }: { children: ReactNode }) {
    return (
    <html lang="en">
    <body>{children}</body>
    </html>
    );
    }

    Do not mark this layout 'use client'.

    Security

    Server Actions and Route Handlers are public functions with server privileges. Validate ids with isLessonId. Ignore client-supplied user ids, roles, and tenant ids. sessionMayWriteProgress defaults to deny.

    Do not put secrets in 'use client' modules or in NEXT_PUBLIC_ variables. CATALOG_API_BASE_URL stays server-only. A database password does not belong in this lesson at all.

    cache: "no-store" on personalized reads prevents a shared cached response from being reused. Public catalog caching is opt-in and must not include completion flags.

    Do not pass unsanitized redirect targets from query parameters. Internal Link hrefs are built from validated ids.

    Error UI shows fixed strings. error.digest can be logged server-side if you need a correlation id; do not print stacks in the page.

    Content that is model-generated later still crosses this boundary as text props. The island renders {title} as text. Do not add dangerouslySetInnerHTML because a model returned tags.

    Cookie-authenticated actions need the framework's origin checks left on, plus the authorization seam. CSRF is why a random site must not be able to mark a lesson complete just because the browser will attach a cookie. Follow the current Next.js security notes for Server Actions when you upgrade.

    Dependency hygiene: generate the app with the official toolchain, commit the lockfile, and read Next.js security advisories for the major version you run. This lesson does not pin a fake patch version.

    Testing

    Pure tests first:

    ts
    import { describe, expect, it } from "vitest";
    import { isLessonId } from "./ids";
    describe("isLessonId", () => {
    it("accepts a slug", () => {
    expect(isLessonId("react-components")).toBe(true);
    });
    it("rejects path traversal and empty strings", () => {
    expect(isLessonId("../admin")).toBe(false);
    expect(isLessonId("")).toBe(false);
    expect(isLessonId("A".repeat(81))).toBe(false);
    });
    });

    Action test with the fixture flag off:

    ts
    import { afterEach, describe, expect, it } from "vitest";
    import { markItemComplete } from "./actions";
    describe("markItemComplete", () => {
    const previous = process.env.ALLOW_FIXTURE_WRITES;
    afterEach(() => {
    process.env.ALLOW_FIXTURE_WRITES = previous;
    });
    it("rejects invalid ids without writing", async () => {
    process.env.ALLOW_FIXTURE_WRITES = "true";
    const result = await markItemComplete("../x", "props-and-state");
    expect(result).toEqual({ ok: false, error: "invalid" });
    });
    it("denies writes when the fixture flag is unset", async () => {
    delete process.env.ALLOW_FIXTURE_WRITES;
    const result = await markItemComplete("react-components", "props-and-state");
    expect(result).toEqual({ ok: false, error: "unauthorized" });
    });
    });

    Importing a server action in Vitest may require your test runner to compile the 'use server' directive. If the runner cannot, move the decision logic into decideComplete(ids, allowed) and keep the action a thin wrapper. Test decideComplete. Do not skip the deny test.

    For the page, a Next.js integration test or a Playwright test belongs to later testing lessons. Here, a request against next dev that you perform manually should show the fixture title for /lessons/react-components, the not-found UI for /lessons/../admin (the pattern fails before fetch), and no stack trace when loadLesson throws. Record the version you ran.

    Client island tests from lesson 5 still apply to LessonOutline. Mock markItemComplete in the island test and assert the unauthorized message is the fixed string.

    Performance

    • Fetch personalized data on the server with no-store so the HTML can include the outline without a second client waterfall. The island hydrates for interaction only.
    • Do not 'use client' the layout to "make hooks easier." You will ship the shell and every import on every page.
    • Public, identical catalog pages can use revalidate and tags. Personalized pages should not.
    • Avoid serial fetches when two reads are independent: start both promises and await Promise.all. This lesson has one read; the habit matters when a page also loads a module title.
    • loading.tsx keeps the navigation feeling immediate. It does not fix a slow query. Trace the server fetch before you add a client spinner as well.
    • Images, when you add them, go through next/image as documented for your version so you get explicit dimensions and optimization. This lesson's player has no image.
    • Do not prefetch private routes you have not thought about. Link prefetch behavior is version-sensitive; check the docs before relying on it for authenticated URLs.
    • A client QueryClient from lesson 6, if you still use it for secondary widgets, is created in a Client Component with useState(() => new QueryClient()), not in a server module.

    Enterprise Real-World Scenarios

    Scenario A: Root layout marked 'use client'

    Every page pulled the data hooks into the browser. A server-only config module threw because fs was bundled for the client.

    What good looks like. The layout stays a Server Component. Islands are leaves. Server-only loaders are imported from the page, not from the island.

    Scenario B: Cached completion

    A fetch of progress used the Next.js 14 default cache. A second learner on a statically cached path could be served the wrong body if the URL did not vary by identity, or the same learner kept seeing pre-write data.

    What good looks like. cache: "no-store" on personalized reads, and a cache key story you can explain. Public pages opt in deliberately.

    Scenario C: Server Action trusts userId

    The client passed userId so the action could "save a click" on session lookup. Any caller could complete lessons for someone else.

    What good looks like. The action takes lesson and item ids only. The session function decides the actor. The default is deny.

    Scenario D: NEXT_PUBLIC_API_SECRET

    A key in a public env var showed up in the browser bundle and in a support screenshot.

    What good looks like. Secrets stay in server env vars and in the host's secret store, never in the lesson source. This assignment needs no secret at all.

    Scenario E: Pages Router snippet in an App Router file

    useRouter().query.lessonId was undefined because the import was next/router inside app/.

    What good looks like. params on the server page, or useParams from next/navigation in a client component. One router per route.

    Best Practices

    1. Keep app/ and pages/ from owning the same URL.
    2. Default to Server Components. Add 'use client' at the leaf that needs state or events.
    3. Pass serializable props across the boundary.
    4. Set cache: "no-store" for personalized lesson reads until you have a written cache policy.
    5. Validate ids in the page, the route handler, and the action with one helper.
    6. Default write authorization to deny.
    7. Never take the actor's identity from the client.
    8. Keep secrets out of NEXT_PUBLIC_ and out of client modules.
    9. Show fixed error copy. Log diagnostics on the server.
    10. Use notFound() for unknown lessons and error.tsx for failures.
    11. Use next/link and next/navigation.
    12. Revalidate the specific path after a successful write.
    13. Create a QueryClient per request if you hydrate one on the server. Do not use a global.
    14. Document whether the PR targets Next.js 14 sync request APIs or Next.js 15 async ones.
    15. Fail closed when CATALOG_API_BASE_URL is unset by using fixtures, not by calling a guessed host.
    16. Do not disable Server Action origin checks.
    17. Avoid open redirects built from query parameters.
    18. Render model and catalog text as text.
    19. Do not mark the root layout as a Client Component.
    20. Read the Next.js docs for your exact version when cache defaults or params types surprise you.

    Common Mistakes and Anti-Patterns

    1. 'use client' on the layout. Symptom: large bundles and server-only imports breaking. Cause: convenience. Fix: push the directive down.
    2. Importing a server loader into the island. Symptom: secrets or fs in the client graph. Cause: a shared barrel file. Fix: split loadLesson and LessonIsland modules.
    3. Assuming one fetch cache default. Symptom: stale or surprisingly dynamic routes after an upgrade. Cause: Next.js 14 versus 15. Fix: set cache or revalidate explicitly.
    4. Sync params after a Next.js 15 upgrade. Symptom: type errors or undefined ids. Cause: params became a promise. Fix: await props.params.
    5. userId argument on the action. Symptom: one learner writes another's progress. Cause: client treated as the session. Fix: server session, deny by default.
    6. Rendering error.message. Symptom: internal URLs or queries on screen. Cause: debugging left in error.tsx. Fix: fixed copy and a server log.
    7. Public cache on progress JSON. Symptom: wrong completion. Cause: a shared tag on a private payload. Fix: no-store until the data is truly public.
    8. NEXT_PUBLIC_ secret. Symptom: key in the bundle. Cause: the prefix was copied from a client tutorial. Fix: server env only, and rotate the key if it leaked.
    9. Pages Router hooks in app/. Symptom: empty query. Cause: next/router. Fix: next/navigation.
    10. Catching redirect or notFound. Symptom: a 500 instead of a redirect. Cause: a broad try/catch around the page. Fix: catch only the fetch error you throw yourself.

    Knowledge Check

    1. What problem does the App Router boundary solve?

    It lets the lesson page read data on the server, send HTML that already contains the outline, and keep secrets and authorization out of the browser bundle. The client island exists for interaction, not for owning the first load.

    2. What alternatives exist, and when would you choose each?

    A client-only SPA from lessons 5 and 6 is enough for a tool behind a login you already painted, and it shows a loading state on first paint. The Pages Router is a supported older API if the app is already on pages/ and you are not migrating today. The App Router is the choice for new TechLearningPro surfaces in this course. Static rendering fits public identical pages. no-store fits progress. Server Actions fit small writes from this UI; a Route Handler fits callers that need an HTTP JSON contract.

    3. Which trust boundaries matter?

    Server Components, actions, and route handlers run on the server and still receive attacker-controlled ids. The client island and every NEXT_PUBLIC_ value are public. The session, not a prop, is the learner's identity. Personalized responses are not shared cache entries. Props crossing the boundary are data, not capabilities, except for Server Action references the framework wires up.

    4. What can fail, and how should the system respond?

    A bad id calls notFound(). A down upstream throws, error.tsx shows fixed copy, and the route handler returns 502 without the upstream body. An action with a bad id returns { ok: false, error: "invalid" }. An action without the fixture flag returns unauthorized and does not revalidatePath after a fake success. Missing env does not cause a call to an invented host.

    5. How would you test this?

    Unit-test isLessonId including traversal strings. Unit-test the action for invalid input and for deny-by-default. Render the outline island with the action mocked. Record a manual or Playwright check of the fixture route, the not-found route, and the absence of a stack trace. State the Next.js version beside the results.

    Interview Questions and Answers

    Q1. What is a Server Component?

    A component that runs on the server as part of the App Router render. It can await data and is not shipped as client JavaScript by default. It cannot use state or browser events. A file becomes a Client Component when it is in the 'use client' graph.

    Q2. Why can't the client import a Server Component?

    The server component's module may depend on server-only code. The supported composition is for a Server Component to render a Client Component and pass serializable props, or to pass server-rendered children into a client shell from a server parent.

    Q3. Where do you put useState?

    In a Client Component, the island that needs it. Not in page.tsx unless that page is marked 'use client', which gives up the server fetch in that module. Prefer a server page plus an island.

    Q4. How do Next.js 14 and 15 differ for fetch caching and params?

    Next.js 14 cached fetch by default in the App Router and passed params as a plain object. Next.js 15 uncached fetch by default and made params, searchParams, cookies(), and headers() asynchronous. Set cache mode explicitly and match the signature to the version you run.

    Q5. What is a Server Action?

    A server function the client can invoke, declared with 'use server'. It is still a remote call. Validate inputs and authorize on the server. Do not treat it as a private method.

    Q6. Why does error.tsx have to be a Client Component?

    The framework needs a client boundary so the UI can offer reset and recover. You still must not display internal error details there.

    Q7. When would you choose a Route Handler over a Server Action?

    When you need a plain HTTP endpoint: the lesson 6 fetch, a webhook you have designed, or a non-React client. Server Actions are for calls from this React UI. Both require the same validation and authorization.

    Q8. How do you keep a secret out of the browser?

    Read it only in server modules, do not use the NEXT_PUBLIC_ prefix, and do not import that module from a Client Component. If it leaked, rotate it. This lesson's samples avoid secrets entirely.

    Q9. Why is cache: "no-store" on the lesson read?

    Completion is personalized. A shared or static cache can serve the wrong body or a stale one. Public caching is a separate decision for data that is the same for every learner.

    Q10. What is wrong with accepting userId in markItemComplete?

    The caller can set it to any value. Identity has to come from the server session. Extra id arguments become forged writes.

    Q11. What does revalidatePath do here?

    After a successful write it marks the lesson path stale so the next server render does not keep a cached copy you opted into. It is not a substitute for no-store, and it should not run when authorization failed.

    Q12. Why leave sessionMayWriteProgress returning false?

    Because a sample that returns true teaches the wrong default and can be copied into production. The fixture flag is explicit, off by default, and is not a password.

    Assignment

    Problem. Ship one App Router lesson page for TechLearningPro that server-renders a fixture outline, hydrates a client island, exposes a validated JSON route, and denies writes unless a non-secret local flag is set.

    Tasks.

    1. Add the app/lessons/[lessonId] page, loading, error, and not-found files. State in the README line of your solution whether you used Next.js 14 sync params or Next.js 15 await params.
    2. Load the fixture when CATALOG_API_BASE_URL is unset. If it is set, fetch with cache: "no-store" and a type guard. Do not call any host other than that base URL.
    3. Add LessonIsland with useTransition and fixed status text. Reuse LessonOutline.
    4. Add the Route Handler. Return 400 for illegal ids, 404 for unknown fixtures, and JSON for the known lesson. Do not read a user id from the query string.
    5. Add markItemComplete with validation and deny-by-default. Call revalidatePath only after an allowed write.
    6. Test isLessonId and the deny/invalid action paths.
    7. Confirm the root layout is a Server Component and that no NEXT_PUBLIC_ secret exists. Write the cache sentence: personalized reads use no-store.

    Deliverable. Source, test output, the Next.js version you ran, and a short boundary diagram. No .env secrets in the submission.

    Challenge. A staff preview must render two tenants' outlines in one process. Explain where a module-level cache or a module-level QueryClient would mix them, and how per-request clients plus server-side tenant binding from the session prevent it. Do not implement a fake tenant header that the client can set.

    Rubric. Architecture and the server/client split 20%. Working route, action, and types 25%. Security of ids, cache, secrets, and deny-by-default 20%. Tests and the error/not-found paths 20%. Version note and trade-off write-up 15%.

    Lesson Summary

    The App Router gives TechLearningPro a server page that loads the lesson, a client island that handles the checkbox, and two server endpoints — a route handler and a server action — that share one id validator and refuse to trust the browser for identity. Cache mode is explicit because personalized progress is not a public static payload. Next.js 14 and 15 differ on params and fetch defaults; the lesson states both so an upgrade is a conscious edit.

    Accessible UI Engineering and Design Systems takes this island and makes the controls meet a contract a keyboard and a screen reader can use. The Next.js course expands caching, authentication, and deployment. The React course stays the client-runtime reference when the island grows. Backend Engineering with Node.js is where the fixture stops being the system of record.

    Further Reading

    • Next.js App Router for the version you installed: segments, loading, error, and not-found.
    • Next.js docs on Server and Client Components, Route Handlers, and Server Actions. Use the docs switcher for your major version when 14 and 15 disagree.
    • React useTransition for the pending state in the island.
    • next/cache revalidatePath and the fetch caching guide for your release.
    • React course and Next.js course for the longer tracks beside this module.
    • Next.js security advisories for your exact version before you deploy Server Actions.
    Ready to mark this lesson complete?Track your journey across the entire course.