Skip to main content

Web frameworks · Intermediate · 26 min

Add and edit books with server actions and Zod validation

By Padding · Updated 18 Nov 2026
Next.js 16.4.6 · React 19.3 · Zod 4.6.7 · Drizzle ORM 0.45 · Node.js 26 · node:26 image

You will give the library app an add-a-book page and an edit page whose forms post to Next.js 16 server actions, are checked by a Zod 4 schema on the server, show each mistake next to its field and redirect to the saved book.

On this page

Up to now the catalogue only reads. In this part librarians get two forms: one to add a book and one to change a book that is already there. Both forms send their fields to a server action, an async function that runs on the server and that React calls for you when the form is submitted. The action checks the fields with a Zod schema, writes to SQLite through Drizzle, and either sends field errors back to the form or redirects to the saved book.

One point shapes everything here. A server action looks like a function you call from your own form, but Next.js exposes it as an HTTP endpoint that answers POST requests. Anyone who can reach your site can call it with any data, without using your form at all. So the action, not the form, is where the rules live: it checks every field itself, and from part 5 it also checks that the caller is a signed-in librarian. The required attributes in the form are there to help honest users, nothing more, and step 8 proves it.

You reuse one form component for adding and editing, so a validation rule or a label changes in one place. If useActionState and form actions are new to you, Build forms in React 19 with actions and useActionState covers them in a plain React app first.

Step 1 · Pick up the app and add Zod

Work in the project folder from part 3. Zod is the only new package. Install it at the version this tutorial uses:

Bash
cd ~/community-library-demo
npm install zod@4.6.7
npm ls next zod drizzle-orm

Zod is small and has no dependencies of its own, so this is a quick download even on prepaid mobile data.

Check it worked

npm ls prints a tree with next@16.4.6, drizzle-orm@0.45 (any patch release) and zod@4.6.7. Zod may also appear a second time under eslint-config-next, which uses it internally; that copy is separate from yours. If drizzle-orm is missing, finish part 2 first.

Step 2 · Describe a valid book with a Zod schema

A form sends everything as text, and people type spaces, hyphens and years in words. The schema turns that text into a clean book or a list of problems, one list per field. Put it in its own module so the server action and the form component can share the types:

Bash
cat > src/lib/book-form.ts <<'TS'
import { z } from "zod";

const thisYear = new Date().getFullYear();

// What a valid book looks like once the form's text has been cleaned up.
export const bookInput = z.object({
  title: z.string().trim().min(1, "Enter the title.").max(200, "Keep the title under 200 characters."),
  author: z.string().trim().min(1, "Enter the author.").max(120, "Keep the author under 120 characters."),
  year: z
    .string()
    .trim()
    .min(1, "Enter the year.")
    .pipe(
      z.coerce
        .number<string>("Enter the year as a number, such as 1958.")
        .int("Enter a whole year, such as 1958.")
        .min(1450, "Enter a year after 1450.")
        .max(thisYear, `Enter a year no later than ${thisYear}.`),
    ),
  isbn: z
    .string()
    .transform((value) => value.replace(/[\s-]/g, "").toUpperCase())
    .refine((value) => value === "" || /^(\d{9}[\dX]|\d{13})$/.test(value), {
      error: "An ISBN has 10 or 13 characters. Leave it empty if the book has none.",
    })
    .transform((value) => (value === "" ? null : value)),
});

export type BookFields = { title: string; author: string; year: string; isbn: string };

// What a server action sends back to the form when it does not redirect.
export type BookFormState = {
  message?: string;
  errors?: Partial<Record<keyof BookFields, string[]>>;
  values?: BookFields;
};

// Read the four fields as text. A missing field becomes "", which the schema rejects.
export function readBookFields(formData: FormData): BookFields {
  const text = (name: string) => {
    const value = formData.get(name);
    return typeof value === "string" ? value : "";
  };
  return { title: text("title"), author: text("author"), year: text("year"), isbn: text("isbn") };
}
TS

How each field is handled:

  • trim() runs before min(1), so a title of only spaces counts as empty.
  • The year is checked in two stages. First the text is trimmed and an empty box fails with "Enter the year.". Only then does .pipe() hand it to z.coerce.number<string>(), which turns the text "1958" into the number 1958; text that is not a number fails with the message you pass, and the <string> tells TypeScript the input is text. Without the first stage, an empty box would be coerced to 0 and the librarian would be told "Enter a year after 1450.", which does not explain what went wrong.
  • The ISBN loses its hyphens and spaces, then must be 10 characters (the last may be X) or 13 digits. An empty box becomes null, which is what the optional isbn column stores.
  • BookFormState is the shape the action returns: field errors, a message for the whole form, and the text the librarian typed so the form can show it again.

Try the schema on its own, without Next.js. Node.js 26 runs TypeScript files directly by removing the types:

Bash
cat > try-book-form.ts <<'TS'
import { z } from "zod";
import { bookInput } from "./src/lib/book-form.ts";

const good = bookInput.safeParse({ title: "  Purple Hibiscus ", author: "Chimamanda Ngozi Adichie", year: "2003", isbn: "978-1-61620-241-6" });
console.log(good.success ? good.data : z.flattenError(good.error).fieldErrors);

const bad = bookInput.safeParse({ title: "", author: "Wole Soyinka", year: "nineteen", isbn: "12345" });
console.log(bad.success ? bad.data : z.flattenError(bad.error).fieldErrors);
TS
node try-book-form.ts
rm try-book-form.ts

Check it worked

Node may first print a MODULE_TYPELESS_PACKAGE_JSON warning about the module type; it is harmless here. Then you see two objects. The first is the cleaned book: title: 'Purple Hibiscus' without the spaces, year: 2003 as a number and isbn: '9781616202416' without hyphens. The second lists three problems: title: [ 'Enter the title.' ], year: [ 'Enter the year as a number, such as 1958.' ] and the ISBN message. author is not listed because it was valid. That second object is exactly what the form will display.

Step 3 · Write the add and edit server actions

A file that starts with "use server" turns every exported async function in it into a server action. Only put functions there that you are happy for anyone to call. Create the actions next to the book pages:

Bash
cat > src/app/books/actions.ts <<'TS'
"use server";

import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import { db } from "@/db";
import { books } from "@/db/schema";
import { bookInput, readBookFields, type BookFormState } from "@/lib/book-form";

// SQLite refuses a second book with the same ISBN because the column is UNIQUE.
function isDuplicateIsbn(error: unknown): boolean {
  return error instanceof Error && "code" in error && error.code === "SQLITE_CONSTRAINT_UNIQUE";
}

const duplicateIsbn = ["Another book in the catalogue already has this ISBN."];

export async function createBook(
  _previous: BookFormState,
  formData: FormData,
): Promise<BookFormState> {
  // Part 5 adds the first check here: is the caller a signed-in librarian?
  const values = readBookFields(formData);
  const parsed = bookInput.safeParse(values);
  if (!parsed.success) {
    return { errors: z.flattenError(parsed.error).fieldErrors, values };
  }

  let id: number;
  try {
    const [row] = await db.insert(books).values(parsed.data).returning({ id: books.id });
    id = row.id;
  } catch (error) {
    if (isDuplicateIsbn(error)) return { errors: { isbn: duplicateIsbn }, values };
    throw error;
  }

  revalidatePath("/books");
  redirect(`/books/${id}`);
}

export async function updateBook(
  bookId: number,
  _previous: BookFormState,
  formData: FormData,
): Promise<BookFormState> {
  // Part 5 adds the first check here: is the caller a signed-in librarian?
  const values = readBookFields(formData);
  const id = z.number().int().positive().safeParse(bookId);
  if (!id.success) return { message: "That book does not exist.", values };

  const parsed = bookInput.safeParse(values);
  if (!parsed.success) {
    return { errors: z.flattenError(parsed.error).fieldErrors, values };
  }

  let changed: { id: number }[];
  try {
    changed = await db
      .update(books)
      .set(parsed.data)
      .where(eq(books.id, id.data))
      .returning({ id: books.id });
  } catch (error) {
    if (isDuplicateIsbn(error)) return { errors: { isbn: duplicateIsbn }, values };
    throw error;
  }
  if (changed.length === 0) return { message: "That book is no longer in the catalogue.", values };

  revalidatePath("/books");
  revalidatePath(`/books/${id.data}`);
  redirect(`/books/${id.data}`);
}
TS

What to notice:

  • The first two arguments. Used with useActionState, an action receives the previous state first and the FormData second. Neither action needs the previous state, hence _previous.
  • Validation before the database. If Zod fails, the action returns the field errors and the typed values and never touches SQLite. The schema also decides what reaches the table: a caller who adds an extra field such as id or addedAt to the request gets nothing, because only the four parsed fields are written.
  • The duplicate ISBN. Two books with the same ISBN can only be caught reliably by the database, since another librarian could add one between your check and your insert. The UNIQUE rule refuses the insert, and the action turns that one error into a message on the ISBN field. Any other error is re-thrown, so real faults are not hidden. The better-sqlite3 driver used here throws the SQLite error itself, so code sits on the error; other Drizzle drivers, such as the asynchronous ones, wrap it in a DrizzleQueryError, and there you would read error.cause.code instead.
  • updateBook takes the id first. The edit page fixes it with bind, so the form does not need a hidden id field. The id is still input from the caller: anyone can call updateBook with any id, so the action checks it is a positive whole number and treats "no row changed" as a missing book.
  • revalidatePath then redirect. revalidatePath tells Next.js that the list and the book page are out of date, so the next visit renders them from the database. redirect sends the browser to the saved book. It works by throwing a special error, which is why it sits after the try/catch blocks, not inside them, where catch would swallow it.

Now generate the route types Next.js derives from your folders and check the whole project compiles:

Bash
npx next typegen
npx tsc --noEmit

Check it worked

next typegen finishes with a short message saying the types were generated (something like Types generated successfully) and tsc --noEmit prints nothing, which means no type errors. If tsc complains that isbn does not exist on the books table, your part 2 schema names the column differently: use your name in book-form.ts and in the actions.

Step 4 · Build one form for adding and editing

The form is a Client Component, because useActionState is a React hook and hooks only run in the browser. It receives the action as a prop, so the same component serves both pages. Give it a CSS Module first:

Bash
cat > src/components/book-form.module.css <<'CSS'
.form {
  display: grid;
  gap: 1rem;
  max-width: 32rem;
}

.field {
  display: grid;
  gap: 0.25rem;
}

.field label {
  font-weight: 600;
}

.field input {
  font: inherit;
  padding: 0.5rem 0.625rem;
  border: 1px solid var(--line);
  border-radius: 0.375rem;
}

.field input[aria-invalid="true"] {
  border-color: #b3261e;
}

.hint {
  color: var(--muted);
  font-size: 0.875rem;
  margin: 0;
}

.error {
  color: #b3261e;
  font-size: 0.875rem;
  margin: 0;
}

.button {
  justify-self: start;
  font: inherit;
  background: var(--accent);
  color: var(--paper);
  border: 0;
  border-radius: 0.375rem;
  padding: 0.625rem 1rem;
  cursor: pointer;
}

.button:disabled {
  opacity: 0.6;
  cursor: progress;
}
CSS

Then the component:

Bash
cat > src/components/book-form.tsx <<'TSX'
"use client";

import { useActionState, type ComponentProps } from "react";
import type { BookFields, BookFormState } from "@/lib/book-form";
import styles from "./book-form.module.css";

type Props = {
  action: (state: BookFormState, formData: FormData) => Promise<BookFormState>;
  initial?: BookFields;
  submitLabel: string;
};

const empty: BookFields = { title: "", author: "", year: "", isbn: "" };

export default function BookForm({ action, initial = empty, submitLabel }: Props) {
  const [state, formAction, pending] = useActionState(action, {});
  // After a failed submit, show what the librarian typed, not the starting values.
  const values = state.values ?? initial;
  const errors = state.errors ?? {};

  function field(name: keyof BookFields, label: string, input: ComponentProps<"input">, hint?: string) {
    const messages = errors[name];
    const describedBy = [hint && `${name}-hint`, messages && `${name}-error`].filter(Boolean).join(" ");
    return (
      <div className={styles.field}>
        <label htmlFor={name}>{label}</label>
        {hint && (
          <p id={`${name}-hint`} className={styles.hint}>
            {hint}
          </p>
        )}
        <input
          id={name}
          name={name}
          defaultValue={values[name]}
          aria-invalid={messages ? true : undefined}
          aria-describedby={describedBy || undefined}
          {...input}
        />
        {messages && (
          <p id={`${name}-error`} className={styles.error}>
            {messages[0]}
          </p>
        )}
      </div>
    );
  }

  return (
    <form action={formAction} className={styles.form}>
      {state.message && (
        <p role="alert" className={styles.error}>
          {state.message}
        </p>
      )}
      {field("title", "Title", { required: true, maxLength: 200 })}
      {field("author", "Author", { required: true, maxLength: 120 })}
      {field("year", "Year first published", { required: true, inputMode: "numeric" })}
      {field("isbn", "ISBN", {}, "Optional. Hyphens and spaces are fine.")}
      <button type="submit" className={styles.button} disabled={pending}>
        {pending ? "Saving…" : submitLabel}
      </button>
    </form>
  );
}
TSX

How it fits together:

  • useActionState(action, {}) wraps the server action. formAction goes on the form, state is whatever the action last returned (an empty object at first), and pending is true from the moment the form is sent until the answer arrives.
  • The button is disabled and reads "Saving…" while pending is true, so a second tap cannot send the book twice.
  • React resets a form after its action finishes. The inputs use defaultValue from state.values, so after a failed submit the reset puts back what the librarian typed instead of clearing it.
  • Each error is linked to its input with aria-describedby, and the input is marked aria-invalid, so a screen reader announces the problem when the librarian returns to the field.
  • inputMode="numeric" brings up the number keypad on phones without the quirks of type="number", such as the value changing when someone scrolls over it.

Check it worked

Bash
npx tsc --noEmit

It prints nothing. The component is not on any page yet; the next step puts it on one.

Step 5 · Add the page for a new book

The page itself is a Server Component that passes createBook to the form. Next.js sends the browser a reference to the action, never its code:

Bash
mkdir -p src/app/books/new
cat > src/app/books/new/page.tsx <<'TSX'
import type { Metadata } from "next";
import Link from "next/link";
import BookForm from "@/components/book-form";
import { createBook } from "../actions";

export const metadata: Metadata = { title: "Add a book" };

export default function NewBookPage() {
  return (
    <main>
      <p>
        <Link href="/books">Back to all books</Link>
      </p>
      <h1>Add a book</h1>
      <BookForm action={createBook} submitLabel="Add book" />
    </main>
  );
}
TSX

Add a link to it in the header from part 1. This is the whole file, with one new line in the nav:

Bash
cat > src/components/site-header.tsx <<'TSX'
import Link from "next/link";
import styles from "./site-header.module.css";

export default function SiteHeader() {
  return (
    <header className={styles.header}>
      <div className={styles.inner}>
        <Link href="/" className={styles.name}>
          Community Library
        </Link>
        <nav aria-label="Main" className={styles.nav}>
          <Link href="/">Home</Link>
          <Link href="/books">Books</Link>
          <Link href="/books/new">Add a book</Link>
        </nav>
      </div>
    </header>
  );
}
TSX

Everyone sees this link for now. Part 5 shows it only to signed-in librarians.

Start the dev server in your second terminal, inside ~/community-library-demo:

Bash
npm run dev

Check it worked

Open http://localhost:3000/books/new. You see "Add a book" as the heading, four labelled fields with the ISBN hint under its label, and a green "Add book" button. From the first terminal:

Bash
curl -s http://localhost:3000/books/new | grep -o '<h1>[^<]*</h1>\|name="[a-z]*"'

The output is <h1>Add a book</h1> followed by name="title", name="author", name="year" and name="isbn". The page also holds hidden inputs with names starting $ACTION; React adds them so the form can be sent even before the page's JavaScript has loaded.

Step 6 · Add the edit page

The edit page reads the book, binds its id to updateBook and hands the form the current values. Its folder sits inside the book's folder, so the address is /books/<id>/edit:

Bash
mkdir -p "src/app/books/[id]/edit"
cat > "src/app/books/[id]/edit/page.tsx" <<'TSX'
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { connection } from "next/server";
import { Suspense } from "react";
import { eq } from "drizzle-orm";
import BookForm from "@/components/book-form";
import { db } from "@/db";
import { books } from "@/db/schema";
import { updateBook } from "../../actions";

export const metadata: Metadata = { title: "Edit book" };

async function EditBook({ params }: { params: Promise<{ id: string }> }) {
  // Read the row when the request arrives, never at build time:
  // the form must start from what is in the database now.
  await connection();
  const { id } = await params;
  if (!/^\d+$/.test(id)) notFound();
  const book = db.select().from(books).where(eq(books.id, Number(id))).get();
  if (!book) notFound();

  // The id travels with the form, so updateBook receives it as its first argument.
  const saveChanges = updateBook.bind(null, book.id);

  return (
    <>
      <p>
        <Link href={`/books/${book.id}`}>Back to the book</Link>
      </p>
      <h1>Edit “{book.title}”</h1>
      <BookForm
        action={saveChanges}
        submitLabel="Save changes"
        initial={{
          title: book.title,
          author: book.author,
          year: String(book.year),
          isbn: book.isbn ?? "",
        }}
      />
    </>
  );
}

export default function EditBookPage({ params }: PageProps<"/books/[id]/edit">) {
  return (
    <main>
      <Suspense fallback={<p>Loading the book…</p>}>
        <EditBook params={params} />
      </Suspense>
    </main>
  );
}
TSX

Two details matter here. connection() comes before the query because better-sqlite3 reads synchronously, and without it Next.js could run the read once while building and keep serving that old copy. The read sits inside Suspense, as part 3's pages do, so the page shell is sent at once and the form streams in when the row is ready.

The page reads the database directly rather than through a function in actions.ts. Every export of a "use server" file can be called from outside, so a read helper placed there would let anyone fetch any row. Keep reads in Server Components or in your server-only data module.

Now link to the edit page from each book. Open src/app/books/[id]/page.tsx and add this straight after the book's <h1>. Link is already imported in that file:

TSX
<p>
  <Link href={`/books/${book.id}/edit`}>Edit this book</Link>
</p>

Check it worked

Open any book from the list. Under its title there is an "Edit this book" link, and following it shows "Edit" and the title in quotes, with the four fields already filled in and a "Save changes" button. From the terminal:

Bash
curl -s http://localhost:3000/books/1 | grep -o 'href="/books/1/edit"'
curl -s http://localhost:3000/books/1/edit | grep -o 'Save changes' | head -n 1

The output is href="/books/1/edit" and Save changes. Stop the dev server with Ctrl+C in its terminal.

Step 7 · Add and edit a book in the production build

Build and start the production version, which is closest to what members will use:

Bash
npm run build
Bash
npm run start

The build ends with a route table. Because create-next-app 16 turned on cacheComponents in next.config.ts in part 1 (see Build a Next.js 16 App Router site), you should see something like /books/new marked ○, a static page made ahead of time because it holds no data, and /books/[id]/edit marked ◐, a partial prerender: a shell made ahead of time with the form streamed in for each request. The legend under the table explains the symbols.

Now use the forms as a librarian would:

  1. Click "Add a book". Type The Fishermen, Chigozie Obioma, 2015 and the ISBN 12345, then click "Add book". The ISBN field turns red and says an ISBN has 10 or 13 characters. The other three fields keep what you typed.
  2. Change the ISBN to 978-0-316-33837-0 and click "Add book" again. The browser moves to the new book's page.
  3. Click "Edit this book". The form shows the ISBN as 9780316338370, without the hyphens. Change the year to 2016 and click "Save changes". You are back on the book's page and it shows 2016.
  4. Click Books in the header and search for fishermen. "The Fishermen" is in the results without a manual refresh, because the action called revalidatePath("/books").

To see the pending state, open your browser's developer tools, choose a slow network profile such as "Slow 4G" in the Network panel, and save the book again. The button reads "Saving…" and cannot be clicked until the server answers. That is the experience of a librarian on a weak mobile signal, and it is why the button is disabled: impatient second taps send nothing.

Check it worked

From the terminal, ask the production server for the list:

Bash
curl -s --get --data-urlencode 'q=fishermen' http://localhost:3000/books | grep -o 'The Fishermen' | head -n 1

It prints The Fishermen, the book you added through the form, now read from SQLite. Leave the server running for the last step.

Step 8 · Get past the browser's checks and watch the server refuse

The required attributes stop an honest librarian from sending an empty form, but they live in the browser, and the browser belongs to whoever is using it. Remove them and see what happens:

  1. Open http://localhost:3000/books/new.
  2. In the developer tools Elements panel, find the <form> and add the attribute novalidate to it (or delete the required attribute from each input).
  3. Leave every field empty and click "Add book".

The browser sends the form this time. The server action runs Zod, finds three problems and returns them: "Enter the title.", "Enter the author." and "Enter the year." appear under their fields, and nothing is written. Try two more things the browser cannot stop:

  • Add a second copy of the book you just added, The Fishermen (second copy) by Chigozie Obioma, 2015, with the same ISBN, 978-0-316-33837-0. The ISBN field says another book already has it, and you stay on the form.
  • Open /books/999/edit, an id that does not exist. You get the "Not on our shelves" page instead of an empty form.

Someone who skips the browser altogether and sends POST requests from a script meets the same checks, because they all run inside the action. What the action cannot check yet is who is calling: right now anyone can add and edit books. Part 5 adds that check at the top of both actions.

Check it worked

The empty form showed three error messages and the duplicate ISBN was refused. Confirm from the terminal that neither attempt reached the database, by counting the books whose title starts with "The Fishermen":

Bash
node -e 'const db = require("better-sqlite3")("data/library.db"); console.log(db.prepare("SELECT count(*) AS n FROM books WHERE title LIKE ?").get("The Fishermen%").n)'

It prints 1: only the copy you added in the last step is there. Stop the server with Ctrl+C. Keep the ~/community-library-demo folder: part 5 continues in it.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.