Skip to content

On Your Own: Recipe Box

The Course
•
40 min study

This is the course's final check: a different app, from a brief, with no walkthrough. Plan first: list the routes, decide which parts are client components, and which functions are server actions. Then build one working step at a time. lib/recipes.js has everything you need from the "database".

Plan on 75 to 90 minutes in all, over two or three sittings; the 40 minutes in the header is the first one. A sensible split:

  1. The list with its tag filter, and the recipe page with its loading and not-found files (about 40 minutes).
  2. The titles and the form, with its validation and pending button (about 30).
  3. Deleting, then the acceptance checks and the self-check below (about 15).

If you pause, write down what works and the next acceptance check to tackle. Try those checks before opening the solution.

The brief

A Recipe Box.

Routes

RouteShows
/Recipes, links All, breakfast, dinner, baking that filter with ?tag=, and each recipe as a link with its minutes: Pancakes · 20 min
/recipes/[id]The recipe's name, 20 minutes · breakfast, and a Delete recipe button
/newAdd a recipe: Name, Minutes and Tag fields, and Save recipe

Behaviour

  • A navigation bar on every page: Recipes and Add a recipe.
  • Page titles: Recipe Box on the list, Pancakes · Recipe Box on a recipe, Add a recipe · Recipe Box on the form.
  • Opening a recipe shows Loading recipe… while it loads (it's slow on purpose). An unknown id shows No such recipe with a link back.
  • The server checks the form: no name gives Enter a name., and minutes that aren't a whole number of at least 1 give Enter the minutes as a whole number., both announced with role="alert", keeping what was typed. While saving, the button says Saving….
  • Saving opens the new recipe. Deleting goes back to the list.

Acceptance checks: filter by breakfast; open Pancakes; on the form, type ten for minutes and save; then add Banana bread, 60 minutes, baking, and delete it again.

Your workspace Next.js · 4 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Recipe Box</header> {children} </body> </html> ); } import { getRecipes } from "@/lib/recipes.js"; // Build the Recipe Box here. See the brief. export default async function RecipesPage() { const recipes = await getRecipes(); return ( <main> <h1>Recipes</h1> <p className="muted">{recipes.length} recipes</p> </main> ); } 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; } // A pretend database of recipes, in the server's memory. const recipes = [ { id: 1, name: "Pancakes", minutes: 20, tag: "breakfast" }, { id: 2, name: "Tomato soup", minutes: 35, tag: "dinner" }, { id: 3, name: "Overnight oats", minutes: 5, tag: "breakfast" }, ]; let nextId = 4; export const TAGS = ["breakfast", "dinner", "baking"]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function getRecipes(tag) { await wait(100); return tag ? recipes.filter((recipe) => recipe.tag === tag) : recipes; } export async function getRecipe(id) { await wait(600); return recipes.find((recipe) => recipe.id === id) ?? null; } export async function createRecipe(recipe) { await wait(300); const saved = { id: nextId++, ...recipe }; recipes.push(saved); return saved; } export async function deleteRecipe(id) { await wait(300); const index = recipes.findIndex((recipe) => recipe.id === id); if (index !== -1) recipes.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.

Check your own work

Before opening the solution, go through this list. Each item names the day that taught it, so you know where to look if one fails.

  • Only the form file starts with "use client". Every page loads its data in a server component (Day 2).
  • /?tag=dinner filters on the server, and reloading keeps the filter; /?tag=nope shows an empty list rather than an error (Day 3).
  • /recipes/999 shows No such recipe, not a crash (Day 3), and opening a recipe shows Loading recipe… first (Day 4).
  • The checks are in the server action, not only in the browser: a required or type="number" on an input doesn't count, because anyone can remove it. After a failed save, what you typed stays in the fields (Day 5).
  • Saving… appears while saving, and the delete button belongs to one recipe through bind (Day 5).
  • The three page titles match the brief (Day 6).

Any box you can't tick is the next thing to work on, not a failure.

Hint 1: a plan

Server: app/page.jsx, app/recipes/[id]/page.jsx with loading.jsx and not-found.jsx, app/new/page.jsx, and app/actions.js. Client: only the form, app/new/RecipeForm.jsx.

Hint 2: start from Study Notes

Its list, note page, form and actions have the same shapes. Copy the structure, not the code, and rename as you go.

Show one solution
One solution Next.js · 10 files
import Link from "next/link"; import "./globals.css"; export const metadata = { title: { template: "%s · Recipe Box", default: "Recipe Box" }, }; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Recipes</Link> <Link href="/new">Add a recipe</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { getRecipes, TAGS } from "@/lib/recipes.js"; export default async function RecipesPage({ searchParams }) { const { tag } = await searchParams; const recipes = await getRecipes(tag); return ( <main> <h1>Recipes</h1> <p className="tags"> <Link href="/">All</Link> {TAGS.map((t) => ( <Link key={t} href={`/?tag=${t}`}> {t} </Link> ))} </p> {recipes.length === 0 && <p className="muted">No recipes here yet.</p>} <ul> {recipes.map((recipe) => ( <li key={recipe.id}> <Link href={`/recipes/${recipe.id}`}>{recipe.name}</Link> <span className="muted">· {recipe.minutes} min</span> </li> ))} </ul> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { createRecipe, deleteRecipe, TAGS } from "@/lib/recipes.js"; export async function addRecipe(previous, formData) { const values = { name: String(formData.get("name") ?? "").trim(), minutes: String(formData.get("minutes") ?? "").trim(), tag: String(formData.get("tag") ?? ""), }; const errors = {}; if (values.name === "") errors.name = "Enter a name."; const minutes = Number(values.minutes); if (!Number.isInteger(minutes) || minutes < 1) errors.minutes = "Enter the minutes as a whole number."; if (!TAGS.includes(values.tag)) values.tag = TAGS[0]; if (Object.keys(errors).length > 0) return { errors, values }; const recipe = await createRecipe({ name: values.name, minutes, tag: values.tag }); revalidatePath("/"); redirect(`/recipes/${recipe.id}`); } export async function removeRecipe(id) { await deleteRecipe(id); revalidatePath("/"); redirect("/"); } 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; } import { TAGS } from "@/lib/recipes.js"; import RecipeForm from "./RecipeForm.jsx"; export const metadata = { title: "Add a recipe" }; export default function NewRecipePage() { return ( <main> <h1>Add a recipe</h1> <RecipeForm tags={TAGS} /> </main> ); } "use client"; import { useActionState } from "react"; import { addRecipe } from "../actions.js"; const empty = { errors: {}, values: { name: "", minutes: "", tag: "breakfast" } }; export default function RecipeForm({ tags }) { const [{ errors, values }, formAction, pending] = useActionState(addRecipe, empty); return ( <form action={formAction}> <p> <label> Name <input name="name" defaultValue={values.name} /> </label>{" "} <span className="error" role="alert">{errors.name}</span> </p> <p> <label> Minutes <input name="minutes" inputMode="numeric" defaultValue={values.minutes} /> </label>{" "} <span className="error" role="alert">{errors.minutes}</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 recipe"}</button> </form> ); } export default function Loading() { return ( <main> <p className="muted">Loading recipe…</p> </main> ); } import Link from "next/link"; export default function RecipeNotFound() { return ( <main> <h1>No such recipe</h1> <p> Back to <Link href="/">all recipes</Link>. </p> </main> ); } import { notFound } from "next/navigation"; import { getRecipe } from "@/lib/recipes.js"; import { removeRecipe } from "../../actions.js"; export async function generateMetadata({ params }) { const { id } = await params; const recipe = await getRecipe(Number(id)); return { title: recipe ? recipe.name : "Not found" }; } export default async function RecipePage({ params }) { const { id } = await params; const recipe = await getRecipe(Number(id)); if (!recipe) notFound(); return ( <main> <h1>{recipe.name}</h1> <p> {recipe.minutes} minutes · {recipe.tag} </p> <form action={removeRecipe.bind(null, recipe.id)}> <button>Delete recipe</button> </form> </main> ); } // A pretend database of recipes, in the server's memory. const recipes = [ { id: 1, name: "Pancakes", minutes: 20, tag: "breakfast" }, { id: 2, name: "Tomato soup", minutes: 35, tag: "dinner" }, { id: 3, name: "Overnight oats", minutes: 5, tag: "breakfast" }, ]; let nextId = 4; export const TAGS = ["breakfast", "dinner", "baking"]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function getRecipes(tag) { await wait(100); return tag ? recipes.filter((recipe) => recipe.tag === tag) : recipes; } export async function getRecipe(id) { await wait(600); return recipes.find((recipe) => recipe.id === id) ?? null; } export async function createRecipe(recipe) { await wait(300); const saved = { id: nextId++, ...recipe }; recipes.push(saved); return saved; } export async function deleteRecipe(id) { await wait(300); const index = recipes.findIndex((recipe) => recipe.id === id); if (index !== -1) recipes.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.

Your structure can differ. What matters is that data is read in server components, changed only through server actions that check their input, and that the acceptance checks pass.

What next

You can now build a Next.js app: pages and layouts from folders, server components that load data, client components for interaction, forms that save with server actions, and an API. From here:

  • Run the Recipe Box for real: download it and use npm run dev and npm run build, as in the second lesson.
  • Add a database. Replace the in-memory list with a real one. The Next.js docs at nextjs.org/docs show several options.
  • Deploy it, for example to Vercel from a GitHub repository.
  • If you haven't yet, React Intermediate in 7 Days goes deeper into the React that every client component uses: reducers, context, custom hooks and testing.

Was this article helpful?

Your response is saved on this device.