Skip to content

Server Actions

The Course
•
20 min study

Changing data

So far, pages have only read data. To change it, such as adding a note, the browser has to ask the server. In a React app that meant writing an API and calling it with fetch. Next.js has a shorter way: a server action.

Add a note Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Notes</header> {children} </body> </html> ); } import { getNotes } from "@/lib/notes.js"; import { addNote } from "./actions.js"; // Read the notes fresh on every request. export const dynamic = "force-dynamic"; export default async function HomePage() { const notes = await getNotes(); return ( <main> <h1>Notes</h1> <ul> {notes.map((note) => <li key={note.id}>{note.text}</li>)} </ul> <form action={addNote}> <input name="text" aria-label="New note" /> <button>Add</button> </form> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { createNote } from "@/lib/notes.js"; // A server action: a function the browser can call, that runs on the server. export async function addNote(formData) { const text = formData.get("text"); console.log("Adding note:", text); await createNote(text); revalidatePath("/"); } 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; } // A pretend database, kept in the server's memory. A real app would use a // database; memory is emptied whenever the server restarts (here, every Run). const notes = [{ id: 1, text: "Read about server actions", done: false }]; let nextId = 2; const wait = () => new Promise((resolve) => setTimeout(resolve, 400)); export async function getNotes() { return notes; } export async function createNote(text) { await wait(); notes.push({ id: nextId++, text, done: false }); } export async function deleteNote(id) { await wait(); const index = notes.findIndex((note) => note.id === id); if (index !== -1) notes.splice(index, 1); } export async function toggleNote(id) { await wait(); const note = notes.find((note) => note.id === id); if (note) note.done = !note.done; }
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.

Add a couple of notes. Watch the console.

A function the form calls

JavaScript
"use server";

export async function addNote(formData) {
  const text = formData.get("text");
  await createNote(text);
  revalidatePath("/");
}

"use server" at the top of actions.js marks every function in the file as a Server Function: an exported async function that runs on the server but can be called through a network request. When used as the form's action, it's a Server Action. The directive does not mark an arbitrary component as a Server Component, and exports in a "use server" module must be async functions.

The page passes it to a form:

JSX
<form action={addNote}>
  <input name="text" aria-label="New note" />
  <button>Add</button>
</form>

When the form is submitted, the browser sends the form's fields to the server, Next.js calls addNote with them as FormData, and formData.get("text") reads the field named text. No fetch, no API route, no onSubmit. After it succeeds, React clears the form.

In a real app, a Server Function is reachable beyond the visible form. Validate its input, and check the caller's session and permission before changing private data. Binding an id into a button doesn't prove the caller owns that record. These public practice labs have no accounts or private data.

revalidatePath

revalidatePath("/") tells Next.js that the page at / is out of date. Next.js renders it again on the server and sends the new version back with the action's answer, so the list updates.

Predict

Delete the revalidatePath("/"); line, press Run, and add a note. Then press Reload in the address bar.

Check your prediction

The note is saved, but the list doesn't change until you reload. Nothing told Next.js the page was out of date. Real Next.js behaves the same. Put the line back.

Memory isn't a database

lib/notes.js keeps notes in the server's memory, which is emptied when the server restarts, here on every Run. Real apps save to a database; the action looks the same.

Exercise

No blank notes

Right now, submitting an empty box, or only spaces, adds a blank note. Make the action ignore those, and trim spaces from the ends of real notes.

Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Notes</header> {children} </body> </html> ); } import { getNotes } from "@/lib/notes.js"; import { addNote } from "./actions.js"; // Read the notes fresh on every request. export const dynamic = "force-dynamic"; export default async function HomePage() { const notes = await getNotes(); return ( <main> <h1>Notes</h1> <ul> {notes.map((note) => <li key={note.id}>{note.text}</li>)} </ul> <form action={addNote}> <input name="text" aria-label="New note" /> <button>Add</button> </form> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { createNote } from "@/lib/notes.js"; // A server action: a function the browser can call, that runs on the server. export async function addNote(formData) { const text = formData.get("text"); console.log("Adding note:", text); await createNote(text); revalidatePath("/"); } 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; } // A pretend database, kept in the server's memory. A real app would use a // database; memory is emptied whenever the server restarts (here, every Run). const notes = [{ id: 1, text: "Read about server actions", done: false }]; let nextId = 2; const wait = () => new Promise((resolve) => setTimeout(resolve, 400)); export async function getNotes() { return notes; } export async function createNote(text) { await wait(); notes.push({ id: nextId++, text, done: false }); } export async function deleteNote(id) { await wait(); const index = notes.findIndex((note) => note.id === id); if (index !== -1) notes.splice(index, 1); } export async function toggleNote(id) { await wait(); const note = notes.find((note) => note.id === id); if (note) note.done = !note.done; }
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

Validate the field’s type and its trimmed content before changing data. Missing input is different from the text someone typed.

Hint 2: a first step

Read the field and check that it's a string before trimming it. A missing field is null, and FormData can also contain a File. Neither should turn into a note through String(...). Return early when the trimmed text is empty.

Show one solution
JavaScript
export async function addNote(formData) {
  const raw = formData.get("text");
  if (typeof raw !== "string") return;
  const text = raw.trim();
  if (text === "") return;
  console.log("Adding note:", text);
  await createNote(text);
  revalidatePath("/");
}

Was this article helpful?

Your response is saved on this device.