Skip to content

Come Back Later

The Course
•
20 min study

Come back to this a few days after finishing the course. Try everything without looking back at earlier lessons first.

Bug hunt

This Study Notes app has four bugs, from Days 3, 4, 5 and 6. Try these, in order, and note what goes wrong each time:

  1. Go to Settings, then back to Notes. Watch how the list appears.
  2. Open any note.
  3. New note: type a title only, and press Save note.
  4. Settings: press Dark.
Four bugs Next.js · 15 files
import { cookies } from "next/headers"; import NavLinks from "./NavLinks.jsx"; import "./globals.css"; export const metadata = { title: { template: "%s · Study Notes", default: "Study Notes" }, description: "Short notes on what you've learned.", }; export default async function RootLayout({ children }) { const theme = (await cookies()).get("theme")?.value ?? "light"; return ( <html lang="en"> <body data-theme={theme}> <header> <NavLinks /> </header> {children} </body> </html> ); } import Link from "next/link"; import { getNotes, TAGS } from "@/lib/notes.js"; import NoteStats from "./NoteStats.jsx"; export default async function NotesPage({ searchParams }) { const { tag } = await searchParams; const notes = await getNotes(tag); return ( <main> <h1>{tag ? `Notes tagged ${tag}` : "All notes"}</h1> <p className="tags"> <Link href="/">All</Link> {TAGS.map((t) => ( <Link key={t} href={`/?tag=${t}`}> #{t} </Link> ))} </p> {notes.length === 0 && <p className="muted">No notes here yet.</p>} {notes.map((note) => ( <article key={note.id} className="card"> <Link href={`/notes/${note.id}`}>{note.title}</Link> <span className="muted">#{note.tag}</span> </article> ))} <NoteStats /> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { createNote, deleteNote, TAGS } from "@/lib/notes.js"; export async function addNote(previous, formData) { const values = { title: String(formData.get("title") ?? "").trim(), body: String(formData.get("body") ?? "").trim(), tag: String(formData.get("tag") ?? ""), }; const errors = {}; if (values.title === "") errors.title = "Give the note a title."; else if (values.title.length > 60) errors.title = "Keep the title under 60 characters."; if (values.body === "") errors.body = "Write the note itself."; if (!TAGS.includes(values.tag)) values.tag = TAGS[0]; if (Object.keys(errors).length > 0) return { errors, values: { title: "", body: "", tag: values.tag } }; const note = await createNote(values); revalidatePath("/"); redirect(`/notes/${note.id}`); } export async function removeNote(id) { await deleteNote(id); revalidatePath("/"); redirect("/"); } export async function saveTheme(formData) { const theme = formData.get("theme") === "dark" ? "dark" : "light"; (await cookies()).set("colour-theme", theme, { maxAge: 60 * 60 * 24 * 365 }); } "use client"; export default function AppError({ retry }) { return ( <main> <h1>Something went wrong</h1> <button onClick={() => retry()}>Try again</button> </main> ); } "use client"; import Link from "next/link"; import { usePathname } from "next/navigation"; const links = [ { href: "/", label: "Notes" }, { href: "/new", label: "New note" }, { href: "/settings", label: "Settings" }, ]; export default function NavLinks() { const pathname = usePathname(); return ( <nav> {links.map((link) => ( <Link key={link.href} href={link.href} aria-current={pathname === link.href ? "page" : undefined}> {link.label} </Link> ))} </nav> ); } import { getStats } from "@/lib/notes.js"; export default async function NoteStats() { const { count, words } = await getStats(); return ( <p className="muted"> {count} notes · {words} words </p> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } nav a[aria-current="page"] { font-weight: 700; text-decoration: none; color: inherit; } .tags a { margin-right: 0.5rem; } .error { color: #b42318; } body[data-theme="dark"] { background: #16202a; color: #e6edf3; } body[data-theme="dark"] a { color: #7cc7e8; } body[data-theme="dark"] .card { border-color: #3a4756; } "use client"; import { useActionState } from "react"; import { addNote } from "../actions.js"; const empty = { errors: {}, values: { title: "", body: "", tag: "routing" } }; export default function NoteForm({ tags }) { const [state, formAction, pending] = useActionState(addNote, empty); const { errors, values } = state; return ( <form action={formAction}> <p> <label> Title <input name="title" defaultValue={values.title} aria-invalid={Boolean(errors.title)} aria-describedby="title-error" /> </label> <br /> <span id="title-error" className="error" role="alert">{errors.title}</span> </p> <p> <label> Note <textarea name="body" rows={3} defaultValue={values.body} aria-invalid={Boolean(errors.body)} aria-describedby="body-error" /> </label> <br /> <span id="body-error" className="error" role="alert">{errors.body}</span> </p> <p> <label> Tag{" "} <select name="tag" defaultValue={values.tag}> {tags.map((tag) => <option key={tag}>{tag}</option>)} </select> </label> </p> <button disabled={pending}>{pending ? "Saving…" : "Save note"}</button> </form> ); } import NoteForm from "./NoteForm.jsx"; import { TAGS } from "@/lib/notes.js"; export const metadata = { title: "New note" }; export default function NewNotePage() { return ( <main> <h1>New note</h1> <NoteForm tags={TAGS} /> </main> ); } import { cookies } from "next/headers"; import { saveTheme } from "../actions.js"; export const metadata = { title: "Settings" }; export default async function SettingsPage() { const theme = (await cookies()).get("theme")?.value ?? "light"; return ( <main> <h1>Settings</h1> <p>Theme: {theme}</p> <form action={saveTheme}> <button name="theme" value="light">Light</button>{" "} <button name="theme" value="dark">Dark</button> </form> </main> ); } import { getNotes } from "@/lib/notes.js"; // GET /api/notes, or /api/notes?tag=routing: the notes as JSON, for other apps. export async function GET(request) { const tag = new URL(request.url).searchParams.get("tag"); return Response.json(await getNotes(tag)); } export default function Loading() { return ( <main> <p className="muted">Opening note…</p> </main> ); } import Link from "next/link"; export default function NoteNotFound() { return ( <main> <h1>No such note</h1> <p> It may have been deleted. See <Link href="/">all notes</Link>. </p> </main> ); } import Link from "next/link"; import { notFound } from "next/navigation"; import { getNote } from "@/lib/notes.js"; import { removeNote } from "../../actions.js"; export async function generateMetadata({ params }) { const { id } = await params; const note = await getNote(Number(id)); return { title: note ? note.title : "Not found" }; } export default async function NotePage({ params }) { const { id } = params; const note = await getNote(Number(id)); if (!note) notFound(); return ( <main> <h1>{note.title}</h1> <p>{note.body}</p> <p> <Link href={`/?tag=${note.tag}`}>#{note.tag}</Link> </p> <form action={removeNote.bind(null, note.id)}> <button>Delete note</button> </form> </main> ); } // A pretend database of notes, kept in the server's memory. A real app would // use a database; this one is emptied whenever the server restarts. const notes = [ { id: 1, title: "Folders are routes", body: "app/about/page.jsx is the page at /about.", tag: "routing" }, { id: 2, title: "Server components by default", body: "Add \"use client\" only for parts that need state or events.", tag: "components" }, { id: 3, title: "params is a promise", body: "Always await params before reading a slug.", tag: "routing" }, ]; let nextId = 4; export const TAGS = ["routing", "components", "data"]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function getNotes(tag) { await wait(100); return tag ? notes.filter((note) => note.tag === tag) : notes; } export async function getNote(id) { await wait(100); return notes.find((note) => note.id === id) ?? null; } // Slow on purpose: it stands in for a query that has to look at everything. export async function getStats() { await wait(1200); const words = notes.reduce((sum, note) => sum + note.body.split(/\s+/).length, 0); return { count: notes.length, words }; } export async function createNote({ title, body, tag }) { await wait(300); const note = { id: nextId++, title, body, tag }; notes.push(note); return note; } export async function deleteNote(id) { await wait(300); const index = notes.findIndex((note) => note.id === id); if (index !== -1) notes.splice(index, 1); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: what you should have seen
  1. Nothing changes for over a second, then the list and the stats appear together.
  2. No such note, for a note that's right there in the list.
  3. Write the note itself. appears, but the title you typed is gone.
  4. The theme stays light, and Settings still says Theme: light.
Hint 2: where to look

How app/page.jsx renders NoteStats; how app/notes/[id]/page.jsx reads params; what addNote returns on an error; and the cookie's name in saveTheme compared with the layout.

Show the four bugs and the fixed app
  1. The slow stats aren't in a boundary (Day 4). The whole page waits for them. Wrap <NoteStats /> in <Suspense> with a fallback, so the list shows first.
  2. params isn't awaited (Day 3). const { id } = params; reads from a promise, so id is undefined, no note is found, and the page calls notFound(). Use await params. The console says so too: params is a Promise and must be unwrapped with await.
  3. The error result drops the values (Day 5). addNote returns empty values with its errors, so the form's defaultValues are empty. Return the values that were sent.
  4. The cookie has two names (Day 6). saveTheme sets colour-theme, but the layout and Settings read theme. Use one name.
Fixed: Study Notes Next.js · 15 files
import { cookies } from "next/headers"; import NavLinks from "./NavLinks.jsx"; import "./globals.css"; export const metadata = { title: { template: "%s · Study Notes", default: "Study Notes" }, description: "Short notes on what you've learned.", }; export default async function RootLayout({ children }) { const theme = (await cookies()).get("theme")?.value ?? "light"; return ( <html lang="en"> <body data-theme={theme}> <header> <NavLinks /> </header> {children} </body> </html> ); } import Link from "next/link"; import { Suspense } from "react"; import { getNotes, TAGS } from "@/lib/notes.js"; import NoteStats from "./NoteStats.jsx"; export default async function NotesPage({ searchParams }) { const { tag } = await searchParams; const notes = await getNotes(tag); return ( <main> <h1>{tag ? `Notes tagged ${tag}` : "All notes"}</h1> <p className="tags"> <Link href="/">All</Link> {TAGS.map((t) => ( <Link key={t} href={`/?tag=${t}`}> #{t} </Link> ))} </p> {notes.length === 0 && <p className="muted">No notes here yet.</p>} {notes.map((note) => ( <article key={note.id} className="card"> <Link href={`/notes/${note.id}`}>{note.title}</Link> <span className="muted">#{note.tag}</span> </article> ))} {/* A new key for each filter: changing it shows "Counting…" straight away, instead of keeping the old page until the slow stats are ready. */} <Suspense key={tag ?? "all"} fallback={<p className="muted">Counting…</p>}> <NoteStats /> </Suspense> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { createNote, deleteNote, TAGS } from "@/lib/notes.js"; export async function addNote(previous, formData) { const values = { title: String(formData.get("title") ?? "").trim(), body: String(formData.get("body") ?? "").trim(), tag: String(formData.get("tag") ?? ""), }; const errors = {}; if (values.title === "") errors.title = "Give the note a title."; else if (values.title.length > 60) errors.title = "Keep the title under 60 characters."; if (values.body === "") errors.body = "Write the note itself."; if (!TAGS.includes(values.tag)) values.tag = TAGS[0]; if (Object.keys(errors).length > 0) return { errors, values }; const note = await createNote(values); revalidatePath("/"); redirect(`/notes/${note.id}`); } export async function removeNote(id) { await deleteNote(id); revalidatePath("/"); redirect("/"); } export async function saveTheme(formData) { const theme = formData.get("theme") === "dark" ? "dark" : "light"; (await cookies()).set("theme", theme, { maxAge: 60 * 60 * 24 * 365 }); } "use client"; export default function AppError({ retry }) { return ( <main> <h1>Something went wrong</h1> <button onClick={() => retry()}>Try again</button> </main> ); } "use client"; import Link from "next/link"; import { usePathname } from "next/navigation"; const links = [ { href: "/", label: "Notes" }, { href: "/new", label: "New note" }, { href: "/settings", label: "Settings" }, ]; export default function NavLinks() { const pathname = usePathname(); return ( <nav> {links.map((link) => ( <Link key={link.href} href={link.href} aria-current={pathname === link.href ? "page" : undefined}> {link.label} </Link> ))} </nav> ); } import { getStats } from "@/lib/notes.js"; export default async function NoteStats() { const { count, words } = await getStats(); return ( <p className="muted"> {count} notes · {words} words </p> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } nav a[aria-current="page"] { font-weight: 700; text-decoration: none; color: inherit; } .tags a { margin-right: 0.5rem; } .error { color: #b42318; } body[data-theme="dark"] { background: #16202a; color: #e6edf3; } body[data-theme="dark"] a { color: #7cc7e8; } body[data-theme="dark"] .card { border-color: #3a4756; } "use client"; import { useActionState } from "react"; import { addNote } from "../actions.js"; const empty = { errors: {}, values: { title: "", body: "", tag: "routing" } }; export default function NoteForm({ tags }) { const [state, formAction, pending] = useActionState(addNote, empty); const { errors, values } = state; return ( <form action={formAction}> <p> <label> Title <input name="title" defaultValue={values.title} aria-invalid={Boolean(errors.title)} aria-describedby="title-error" /> </label> <br /> <span id="title-error" className="error" role="alert">{errors.title}</span> </p> <p> <label> Note <textarea name="body" rows={3} defaultValue={values.body} aria-invalid={Boolean(errors.body)} aria-describedby="body-error" /> </label> <br /> <span id="body-error" className="error" role="alert">{errors.body}</span> </p> <p> <label> Tag{" "} <select name="tag" defaultValue={values.tag}> {tags.map((tag) => <option key={tag}>{tag}</option>)} </select> </label> </p> <button disabled={pending}>{pending ? "Saving…" : "Save note"}</button> </form> ); } import NoteForm from "./NoteForm.jsx"; import { TAGS } from "@/lib/notes.js"; export const metadata = { title: "New note" }; export default function NewNotePage() { return ( <main> <h1>New note</h1> <NoteForm tags={TAGS} /> </main> ); } import { cookies } from "next/headers"; import { saveTheme } from "../actions.js"; export const metadata = { title: "Settings" }; export default async function SettingsPage() { const theme = (await cookies()).get("theme")?.value ?? "light"; return ( <main> <h1>Settings</h1> <p>Theme: {theme}</p> <form action={saveTheme}> <button name="theme" value="light">Light</button>{" "} <button name="theme" value="dark">Dark</button> </form> </main> ); } import { getNotes } from "@/lib/notes.js"; // GET /api/notes, or /api/notes?tag=routing: the notes as JSON, for other apps. export async function GET(request) { const tag = new URL(request.url).searchParams.get("tag"); return Response.json(await getNotes(tag)); } export default function Loading() { return ( <main> <p className="muted">Opening note…</p> </main> ); } import Link from "next/link"; export default function NoteNotFound() { return ( <main> <h1>No such note</h1> <p> It may have been deleted. See <Link href="/">all notes</Link>. </p> </main> ); } import Link from "next/link"; import { notFound } from "next/navigation"; import { getNote } from "@/lib/notes.js"; import { removeNote } from "../../actions.js"; export async function generateMetadata({ params }) { const { id } = await params; const note = await getNote(Number(id)); return { title: note ? note.title : "Not found" }; } export default async function NotePage({ params }) { const { id } = await params; const note = await getNote(Number(id)); if (!note) notFound(); return ( <main> <h1>{note.title}</h1> <p>{note.body}</p> <p> <Link href={`/?tag=${note.tag}`}>#{note.tag}</Link> </p> <form action={removeNote.bind(null, note.id)}> <button>Delete note</button> </form> </main> ); } // A pretend database of notes, kept in the server's memory. A real app would // use a database; this one is emptied whenever the server restarts. const notes = [ { id: 1, title: "Folders are routes", body: "app/about/page.jsx is the page at /about.", tag: "routing" }, { id: 2, title: "Server components by default", body: "Add \"use client\" only for parts that need state or events.", tag: "components" }, { id: 3, title: "params is a promise", body: "Always await params before reading a slug.", tag: "routing" }, ]; let nextId = 4; export const TAGS = ["routing", "components", "data"]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function getNotes(tag) { await wait(100); return tag ? notes.filter((note) => note.tag === tag) : notes; } export async function getNote(id) { await wait(100); return notes.find((note) => note.id === id) ?? null; } // Slow on purpose: it stands in for a query that has to look at everything. export async function getStats() { await wait(1200); const words = notes.reduce((sum, note) => sum + note.body.split(/\s+/).length, 0); return { count: notes.length, words }; } export async function createNote({ title, body, tag }) { await wait(300); const note = { id: nextId++, title, body, tag }; notes.push(note); return note; } export async function deleteNote(id) { await wait(300); const index = notes.findIndex((note) => note.id === id); if (index !== -1) notes.splice(index, 1); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

Recall questions

Answer each in a sentence or two, then check the lesson it came from.

  1. Which files does Next.js treat specially in a folder, and what does each do? (Days 1 and 4)
  2. When must a component be a client component? (Day 2)
  3. Why must a client component read window in an effect, on real Next.js? (Day 2)
  4. How does a page read /notes/2's 2, and ?tag=data's data? (Day 3)
  5. What's the difference between router.push and router.replace? (Day 3)
  6. Why does reset() alone not fix an error from server data? (Day 4)
  7. What does revalidatePath do after a server action? (Day 5)
  8. Why does a server action check its input even when the form uses required? (Day 5)
  9. When would you write a route handler instead of a server action? (Day 6)

Ready for the next step?

You're ready to move on if you can, without help:

  • lay out a multi-page site with layouts, links and not-found pages
  • split a page into server components for data and client components for interaction
  • build pages from URL segments and search params
  • show loading states, stream slow parts and handle errors
  • save data with validated server actions
  • write a small JSON API, use a cookie, and give pages titles
  • run, build and explain a Next.js app on your own computer

If one of these feels shaky, redo that day's checkpoint from scratch.

Was this article helpful?

Your response is saved on this device.