Next.js Server Actions
A Server Action is a function that runs on the server. A form calls it straight from the page.
The add-book action
The action reads the title and the author and saves the book. The check and the refresh line arrive in the next two lessons.
'use server';
import { addBookToStore } from "@/lib/books";
export async function addBook(
_prevState: AddBookState,
formData: FormData
): Promise<AddBookState> {
const title = String(formData.get("title") ?? "").trim();
const author = String(formData.get("author") ?? "").trim();
const saved = await addBookToStore({ title, author, read: false });
return { ok: true, message: `Saved "${saved.title}" by ${saved.author}.` };
}The form posts to the action
The check reads the form tag. The form posts its fields as form data.
curl -s http://localhost:3112/add-book | grep -o '<form[^>]*>'Example
curl -s http://localhost:3112/add-book | grep -oE 'Add book|name="title"|name="author"' | sort -uKey points
- Server Action: a server function that a form can call, with no API route in between
- "use server": the line at the top of the file that marks its functions as actions
- The form passes its fields to the action. The action reads them from the form data.
- The action saves the book, then answers with a result. The page shows that result.
- The action below saves the book with no check and no refresh. The check arrives in the lesson after next, and the refresh line in the lesson after that.
In this example, the check reads the add-book page and lists the form fields. The form has a title field and an author field, and it posts to the action. The submit itself could not be driven from curl on this machine: every curl submit answered 500 with the error Connection closed, in both dev and production, so a browser submit is still unverified. The save is proven in the route-handler lessons, where the same store answers a POST with 201 and the new book appears in the list.
Note
A form submit from curl failed on this machine, so the browser submit is still unverified. The save itself is proven in the route-handler lessons.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What does a form call when it uses a Server Action?