Skip to content

Extend It

The Course
•
20 min study

Work in the lab below, or in your downloaded project with npm run dev. Each feature uses a different day's idea.

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.
Exercise

1. Search

Add a Search box to the list that filters notes by title as you type, and works together with the tag filter: on #routing, typing params gives /?tag=routing&q=params.

Your working space 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.
Hint 1: the idea

Day 3's SearchBox does exactly this: it copies the current search params, sets q, and calls router.replace. Copy it into app/SearchBox.jsx.

Hint 2: a first step

Read q from searchParams alongside tag (default ""), and filter the loaded notes by title.

Show one solution

In app/page.jsx:

JavaScript
import SearchBox from "./SearchBox.jsx";
JavaScript
const { tag, q } = await searchParams;
const query = Array.isArray(q) ? q[0] : (q ?? "");
const notes = (await getNotes(tag)).filter((note) => note.title.toLowerCase().includes(query.toLowerCase()));
JSX
<SearchBox />

app/SearchBox.jsx is Day 3's, unchanged:

JSX
"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";

export default function SearchBox() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  function handleChange(event) {
    const params = new URLSearchParams(searchParams);
    if (event.target.value) params.set("q", event.target.value);
    else params.delete("q");
    const query = params.toString();
    router.replace(query ? `${pathname}?${query}` : pathname);
  }

  return (
    <label>
      Search <input defaultValue={searchParams.get("q") ?? ""} onChange={handleChange} />
    </label>
  );
}
Exercise

2. One note from the API

Add GET /api/notes/[id], answering with one note, or a 404 with { "error": "No note 42" }.

Your working space 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.
Hint 1: the idea

An API route is a request handler, not a page component. Resolve its dynamic id before loading the record.

Hint 2: a first step

app/api/notes/[id]/route.js, with GET(request, { params }), as in Day 6. Remember Number(id): ids in lib/notes.js are numbers.

Show one solution
JavaScript
import { getNote } from "@/lib/notes.js";

export async function GET(request, { params }) {
  const { id } = await params;
  const note = await getNote(Number(id));
  if (!note) return Response.json({ error: `No note ${id}` }, { status: 404 });
  return Response.json(note);
}

In the downloaded project, open http://localhost:3000/api/notes/1 to see it.

Exercise

3. Tag counts

Show how many notes each tag has: #routing (2) #components (1) #data (0), whatever tag is selected.

Your working space 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.
Hint 1: the idea

A filtered list cannot tell you the totals for every tag. Counts need the full data set.

Hint 2: a first step

The page already has the notes for the selected tag. Load all notes too, with getNotes(), and count each tag from those.

Show one solution
JavaScript
const notes = await getNotes(tag);
const all = await getNotes();
const count = (t) => all.filter((note) => note.tag === t).length;
JSX
<Link key={t} href={`/?tag=${t}`}>
  #{t} ({count(t)})
</Link>

The two queries don't depend on each other. For a real database, load them together with Promise.all, as on Day 4.

Was this article helpful?

Your response is saved on this device.