Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 72 ยท Projects

Project: A Todo App with Server Actions

Build a todo app with Server Actions: a form with validation, optimistic updates, revalidation and a small database layer, plus runnable stand-ins.

A todo list looks trivial, and that is exactly why it is the best project for learning mutations. It has every moving part of a real data-driven app in a tiny package: a form, input validation, a database, buttons that change data, and the need for the screen to reflect the result quickly. In this project we build it the Next.js way, with Server Actions and no API routes.

You will see the full real code (a Prisma database layer, actions with validation, a Server Component page and a Client Component list with optimistic updates) and you will run two stand-ins: a React 19 version of the interface with a fake server, and a Node.js version of the actions as plain, testable functions. The lesson combines Server Actions, Building Forms with Server Actions, Validating Input and Optimistic UI and Refreshing After Mutations.

Real or stand-in? The Next.js, Prisma and Zod code is real but read-only, because this site cannot run a Next.js server or a database. The React stand-in uses the real React 19 hooks useActionState and useOptimistic. The "server" is a function with a delay in the same page. The Node.js stand-in uses the real FormData class and hand-written validation instead of Zod.

The architecture

Four layers, one direction

Database A Todo table with a unique title.
Actions Validate, write, then revalidate.
Page A Server Component reads the list.
List A Client Component adds optimistic UI.

Data flows down as props. Changes flow up as actions.

1 / 2
sequenceDiagram
    participant B as Browser
    participant A as Server Action
    participant D as Database
    B->>B: Optimistic item appears
    B->>A: POST with form data
    A->>A: Validate input
    A->>D: INSERT
    A->>A: revalidatePath("/")
    A-->>B: New state + fresh page
    B->>B: Real list replaces optimistic one

The browser shows the result first. The server confirms it, or rejects it and the guess disappears.

Step 1: the database layer

We use Prisma here, but any database or ORM follows the same shape (see Data Access Layers and ORMs). The schema describes one table. The @unique on title matters: it makes the database the final judge of duplicates, which no amount of checking in code can match, because two requests can arrive at the same moment.

PRISMA
// prisma/schema.prisma
model Todo {
  id        Int      @id @default(autoincrement())
  title     String   @unique
  done      Boolean  @default(false)
  createdAt DateTime @default(now())
}

A tiny module shares one client instance, so development reloads do not open a new database connection every time:

TypeScript
// lib/prisma.ts
import 'server-only';
import { PrismaClient } from '@prisma/client';

const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== 'production') {
  globalForPrisma.prisma = prisma;
}
TypeScript
// lib/todos.ts
import 'server-only';
import { prisma } from './prisma';

export type Todo = { id: number; title: string; done: boolean };

export async function getTodos(): Promise<Todo[]> {
  return prisma.todo.findMany({
    orderBy: { createdAt: 'asc' },
    select: { id: true, title: true, done: true },
  });
}

select returns only the three fields the UI needs. That is a small DTO (data transfer object) and it keeps columns like createdAt out of what you pass to the browser.

Step 2: the actions

Every action does the same four things in the same order: validate the input, check that the caller may do this, write to the database, and revalidate the page. Here is the add action, with Zod for the schema (see Validating Input):

TypeScript
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { Prisma } from '@prisma/client';
import { z } from 'zod';
import { prisma } from '@/lib/prisma';

const TitleSchema = z
  .string()
  .trim()
  .min(1, 'Please enter a title.')
  .max(60, 'Keep it under 60 characters.');

export type FormState = { error: string | null; title: string };

export async function addTodo(previous: FormState, formData: FormData): Promise<FormState> {
  const raw = String(formData.get('title') ?? '');
  const parsed = TitleSchema.safeParse(raw);

  if (!parsed.success) {
    return { error: parsed.error.issues[0].message, title: raw };
  }

  try {
    await prisma.todo.create({ data: { title: parsed.data } });
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
      return { error: 'You already have that todo.', title: raw };
    }
    throw error;
  }

  revalidatePath('/');
  return { error: null, title: '' };
}

The function takes previous state as its first argument because it will be used with useActionState. It returns a plain object instead of throwing for expected problems, so the form can show the message. Unexpected errors are rethrown and reach the nearest error.tsx. The code P2002 is Prisma's "unique constraint failed", which we turn into a friendly message. Remember the order rule from Optimistic UI and Refreshing After Mutations: revalidatePath runs before the function ends, and nothing important may come after a redirect.

Toggling and deleting take an id. An action argument is client input, even when it comes from your own button, because anyone can call the action's endpoint with any value. So validate it too:

TypeScript
const IdSchema = z.number().int().positive();

export async function toggleTodo(id: number) {
  const todoId = IdSchema.parse(id);
  const todo = await prisma.todo.findUnique({ where: { id: todoId } });
  if (!todo) return;

  await prisma.todo.update({ where: { id: todoId }, data: { done: !todo.done } });
  revalidatePath('/');
}

export async function deleteTodo(id: number) {
  const todoId = IdSchema.parse(id);
  await prisma.todo.deleteMany({ where: { id: todoId } });
  revalidatePath('/');
}

deleteMany is used on purpose: unlike delete, it does not throw when the row is already gone, so a double click is harmless. In an app with accounts, every one of these functions would also check the session and add userId to its where clause (see Authorization and Data Security and Project: Login and Protected Pages). Without that, any signed-in user could change any todo by guessing ids.

Step 3: the page and the list

The page is a Server Component. It reads the todos and hands them to a Client Component, because only the client part needs hooks:

TSX
// app/page.tsx
import { getTodos } from '@/lib/todos';
import { TodoList } from './todo-list';

export default async function Home() {
  const todos = await getTodos();
  return (
    <main>
      <h1>Todos</h1>
      <TodoList todos={todos} />
    </main>
  );
}
TSX
// app/todo-list.tsx
'use client';

import { useActionState, useOptimistic, useTransition } from 'react';
import { addTodo, toggleTodo, deleteTodo, type FormState } from './actions';
import type { Todo } from '@/lib/todos';

type Change =
  | { type: 'add'; title: string }
  | { type: 'toggle'; id: number }
  | { type: 'delete'; id: number };

function applyChange(current: (Todo & { pending?: boolean })[], change: Change) {
  switch (change.type) {
    case 'add':
      return [...current, { id: -current.length - 1, title: change.title, done: false, pending: true }];
    case 'toggle':
      return current.map((t) => (t.id === change.id ? { ...t, done: !t.done, pending: true } : t));
    case 'delete':
      return current.filter((t) => t.id !== change.id);
  }
}

const initialState: FormState = { error: null, title: '' };

export function TodoList({ todos }: { todos: Todo[] }) {
  const [shown, change] = useOptimistic(todos, applyChange);
  const [, startTransition] = useTransition();

  const [state, formAction, isPending] = useActionState(
    async (previous: FormState, formData: FormData) => {
      const title = String(formData.get('title') ?? '').trim();
      if (title) change({ type: 'add', title });
      return addTodo(previous, formData);
    },
    initialState,
  );

  return (
    <>
      <form action={formAction}>
        <input name="title" defaultValue={state.title} placeholder="What needs doing?" aria-invalid={!!state.error} />
        <button disabled={isPending}>Add</button>
        {state.error && <p role="alert">{state.error}</p>}
      </form>

      <ul>
        {shown.map((todo) => (
          <li key={todo.id} style={{ opacity: todo.pending ? 0.5 : 1 }}>
            <label>
              <input
                type="checkbox"
                checked={todo.done}
                onChange={() => startTransition(async () => {
                  change({ type: 'toggle', id: todo.id });
                  await toggleTodo(todo.id);
                })}
              />
              <span style={{ textDecoration: todo.done ? 'line-through' : 'none' }}>{todo.title}</span>
            </label>
            <button
              onClick={() => startTransition(async () => {
                change({ type: 'delete', id: todo.id });
                await deleteTodo(todo.id);
              })}
              aria-label={'Delete ' + todo.title}
            >
              Delete
            </button>
          </li>
        ))}
      </ul>
    </>
  );
}

Things worth noticing:

  • One reducer, three kinds of change. useOptimistic(todos, applyChange) gives a list that is the real one with temporary changes laid on top. When the transition ends, the layer disappears and the new todos prop (from the revalidated page) takes over.
  • Optimistic IDs are temporary. A new item gets a negative id that cannot collide with a database id. It is replaced as soon as the server data arrives.
  • useActionState provides the last returned state (the error and the typed title), plus a pending flag. Using defaultValue={state.title} keeps what the user typed after a failed submit, because React resets uncontrolled form fields when an action finishes.
  • The form works without JavaScript in the usual way when you pass a Server Action directly to action. Our wrapper adds optimism, which does need the client. That is a reasonable trade for a todo list, and you can keep the plain version for forms that must work without scripts.

The next stand-in is this interface with real React 19 hooks. The functions at the top play the server: they wait, validate, and keep the list in a variable. Try three things: add a normal todo (it appears grey at once, then solid), add the same todo again (it appears, then vanishes with an error, because the duplicate check only happens on the "server"), and submit an empty form.

Todo app with useActionState and useOptimistic

Watch the last line, "The server holds N todos". It changes only after the delay, while the list changed at once. Adding a duplicate shows the rollback path from the other direction: the optimistic copy shows up, the server says no, and because the real list never contained it, it disappears without any cleanup code. The message stays and the text you typed is put back in the input.

Testing the actions as plain functions

A Server Action is an ordinary function that takes FormData and returns a value. You can test it without a browser, a server or a framework. All the logic that matters (what is valid, what the error message says, what is written) can be checked with a few calls. The Node.js stand-in does exactly that: it implements the same validation and store as plain functions, uses the real FormData class, and checks the results.

Node.js Actions as plain, testable functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Every check is one line, and none needs a running app. This is the payoff of keeping actions thin and putting the rules in plain functions: you can run them in milliseconds, in a test runner such as Vitest or node:test (see Testing Next.js Apps). In the real app you would mock prisma or use a test database, and mock revalidatePath from next/cache, which only works inside a Next.js request.

Ideas to extend the project

  • Accounts. Add a userId column and filter every query by the signed-in user.
  • Filters. Show All, Active and Done using a ?filter= search param, as in Project: An Admin Dashboard.
  • Editing. Add an inline edit form with its own action and validation.
  • Reordering. Store a position column and update it in a single transaction.
  • Rate limiting. Limit how fast one visitor can add todos (see Observability and Scaling).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the Todo model mark title as @unique even though the action also validates input?

    A check-then-insert in code has a race window. A unique constraint is enforced atomically by the database, and the action turns its error into a friendly message.
  2. 2. Why does the toggleTodo action validate its id argument even though only your own button calls it?

    Server Action arguments are untrusted input. Anyone can send a request to the action endpoint with arbitrary values.
  3. 3. A user adds a duplicate todo in the optimistic list. What happens to the temporary item?

    useOptimistic's layer is discarded when the transition ends. The server rejected the todo, so the real list is unchanged and the item vanishes.
  4. 4. What is the main benefit of returning an error object from an action instead of throwing?

    Expected problems such as invalid input belong in the returned state. Unexpected failures should throw and reach the error boundary.
  5. 5. Why is deleteMany used instead of delete in the delete action?

    delete throws if the record is missing. deleteMany simply deletes zero rows, which suits an idempotent action.

Summary

  • A todo app exercises the whole mutation loop: form, validation, database write, revalidation and instant feedback.
  • Put reads in a server-only data layer, and write actions that validate, authorize, write and revalidate, in that order.
  • Return expected errors as state for useActionState, and let unexpected errors reach error.tsx.
  • Treat every action argument as untrusted, including ids from your own buttons. Let a database constraint decide uniqueness.
  • useOptimistic layers temporary changes over the real list, and rolls back by itself when the server says no.
  • Keep actions thin so the rules live in plain functions that you can test without a browser.

Next: Project: A Storefront with Cart