Skip to lesson content

PROJECT 4 · LESSON 11 OF 18

Create tasks with a Server Action

Connect a form to a validated database write and refresh the list.

  • use server
  • FormData
  • useActionState
  • revalidatePath

Your workspace: task-app

Continue from lesson 10: Read tasks from a database. Keep existing files; create or replace the complete files listed below.

Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.

1. Understand the problem and the concepts

Why we need this feature

Reading a database is only half of a task app. We now connect an HTML form to a server-side operation, and follow its input, validation, database write and refreshed output. This is the core pattern reused by later edit and admin forms.

A form action invokes a server function over a network request. use server marks the action module, while useActionState connects its result and pending status to the form.

HTML required helps the user, but server validation decides what is acceptable. After insertion, revalidatePath refreshes the visible route. Reading tasks remains the Server Component’s job.

How the form reaches server code

NewTask is a Client Component because it displays pending and result state through useActionState. Its form action is the action function returned by that hook. When submitted, the named controls are collected into FormData and the framework invokes createTask on the server.

The imported function looks like an ordinary function reference, but crossing from client to server requires a network request. Next.js handles that transport for a Server Action. use server marks the action module’s server functions; it does not mean the function is private or callable only through your visible form.

With useActionState, the action receives the previous result first and FormData second. _previous is unused in this example. The returned object becomes state, and pending tracks an in-flight submission. That explains the function signature rather than treating its arguments as boilerplate.

Validate before writing

data.get("title") reads the control whose name is title. An input’s label or id alone does not make it a submitted field. The code converts the value to a string, trims whitespace and rejects an empty or overlong title before contacting MongoDB.

The browser’s required and maxLength attributes help normal users, but a direct request can bypass them. The server repeats the real rule. For example, three spaces satisfy a simple nonempty HTML input but become an empty string after trim. That request should not insert a task.

insertOne stores the normalized title, completed false, and a server-created date. The caller does not decide the initial completion flag or timestamp in this feature. We accept a small input contract rather than blindly copying every incoming field into a document.

Refresh the view and explain failures

After insertion, revalidatePath("/") tells Next.js that the task route needs fresh output. The updated server render queries the list again. This keeps MongoDB as the source of truth instead of manually appending a guessed record to a client list.

Expected validation failures return a message without throwing. A database failure returns a safe retry message, while detailed diagnostics belong in server logs. The pending button prevents ordinary repeated clicks, but it does not provide database-level deduplication; the order lesson introduces that separate concern.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The user submits a named title control.

  2. The Server Action normalizes and validates FormData.

  3. A valid title is inserted into MongoDB; invalid input returns feedback without a write.

  4. revalidatePath refreshes the task route, and the action result updates the form message.

Trace a valid and an invalid submission

  1. Input: " Practice forms ". trim produces Practice forms, which passes the length rule.
  2. MongoDB stores the trimmed title with completed=false and a server timestamp. The refreshed list shows it.
  3. Input: " ". trim produces an empty string, so the action returns the validation message immediately.
  4. No insert happens in that branch. Check the database or refreshed list rather than relying only on the message.

3. Build it, one file at a time

  1. Add app/actions.ts and components/new-task.tsx. Replace the page with the version below.
  2. Submit a task. Watch the pending button and the result message.
  3. Refresh and restart the server to verify database persistence.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

app/actions.ts

This module owns the task mutations and their server-side validation.

app/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { tasks } from "@/lib/tasks";
export type Result = { message: string };
export async function createTask(
  _previous: Result,
  data: FormData,
): Promise<Result> {
  const title = String(data.get("title") ?? "").trim();
  if (!title || title.length > 120)
    return { message: "Enter a title between 1 and 120 characters." };
  try {
    await tasks.insertOne({ title, completed: false, createdAt: new Date() });
  } catch {
    return { message: "Could not save. Please try again." };
  }
  revalidatePath("/");
  return { message: "Task added." };
}

Read the code

  1. use server marks its exported async operations as Server Functions. Through useActionState they receive the previous result and submitted FormData.
  2. createTask trims the title, checks length, inserts normalized data and then revalidates the list route. Expected failures return message objects instead of exposing raw exceptions.
  3. This checkpoint is an unauthenticated shared-data lab for local practice. Do not present it as private until lesson 15 adds session and ownership checks.

components/new-task.tsx

This connects the create action’s feedback and pending state to a form.

components/new-task.tsx
"use client";
import { useActionState } from "react";
import { createTask } from "@/app/actions";
export default function NewTask() {
  const [state, action, pending] = useActionState(createTask, { message: "" });
  return (
    <form action={action}>
      <label>
        New task <input name="title" required maxLength={120} />
      </label>
      <button disabled={pending}>{pending ? "Saving…" : "Add task"}</button>
      <p role="status">{state.message}</p>
    </form>
  );
}

Read the code

  1. useActionState returns [state, action, pending]. state contains the latest result object, action is passed to the form, and pending disables the button while submitting.
  2. name="title" is what makes the input appear under the title key in FormData. required and maxLength help the user but do not replace server validation.
  3. role=status announces the returned message. The server action remains responsible for deciding whether a write happens.

app/page.tsx

This Server Component reads the task list and composes the appropriate task controls.

app/page.tsx
import { tasks } from "@/lib/tasks";
import NewTask from "@/components/new-task";
export const dynamic = "force-dynamic";
export default async function TasksPage() {
  const rows = await tasks
    .find({})
    .sort({ createdAt: -1 })
    .limit(100)
    .toArray();
  return (
    <>
      <h1>Tasks</h1>
      <NewTask />
      {rows.map((task) => (
        <article key={task._id.toString()}>
          {task.title} — {task.completed ? "Done" : "Open"}
        </article>
      ))}
      {!rows.length && <p>No tasks yet.</p>}
    </>
  );
}

Read the code

  1. The async page awaits a database cursor converted to an array. sort requests newest first and limit bounds the teaching example.
  2. force-dynamic keeps the task read request-rendered. An empty array renders the empty message rather than an exception.
  3. MongoDB ObjectIds are converted to strings before becoming component keys or client editor props.
  4. NewTask owns form feedback. The page still owns the database read; the mutation revalidates this route to obtain updated rows.

4. Run it and check your result

  • A valid title appears immediately and survives refresh.
  • A title containing only spaces is rejected by the server.

5. Predict, change and observe

Remove the input’s name temporarily and submit a title. Restore it afterward.

Compare your prediction with the expected result

What you should observe

The action receives no title value and returns its validation message.

Why it happens

FormData is built from successful named form controls. Visible text in an unnamed input is not enough to populate data.get("title").

6. Troubleshoot with evidence

A common mistake

Return expected validation failures as data. Do not show raw database exceptions to learners or users.

The action receives the wrong argument.

Likely cause: It was written as a one-argument FormData action while being used through useActionState.

Check and correct: Use the previous-result, FormData signature shown in this lesson.

The task exists in MongoDB but the screen stays stale.

Likely cause: The mutation succeeded without refreshing the affected route.

Check and correct: Call revalidatePath for the list route after the successful write and before returning success.

7. Practice and explain it back

Your independent task

Add a minimum title length of three and update the feedback.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why is the page read not another Server Action?

Rendering reads the data in a Server Component. Server Actions here represent user-triggered mutations, not a replacement for every server-side function.

Does use server authorize the caller?

No. It controls execution placement. Authentication and authorization must be explicitly checked when the application introduces private data.