What Is a Server Action
Part of the Next.js Essentials section of Coddy's React journey — lesson 29 of 47.
You can read data on the server now. Time for the other half: changing it.
Until recently, saving one line of text took a surprising amount of ceremony. You wrote an endpoint:
// app/api/items/route.js
export async function POST(request) {
const body = await request.json();
saveItem(body.text);
return Response.json({ ok: true });
}…then called it from the browser:
await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});Two files, a URL, a method, headers, and JSON in both directions, to move one string from a form to a database.
A Server Action deletes all of it. Write an async function in a file whose first line is 'use server':
// app/actions.js
'use server';
import { saveItem } from '../lib/db';
export async function addItem(formData) {
saveItem(formData.get('text'));
}…and hand that function to a form:
<form action={addItem}>
<input name="text" />
<button type="submit">Add</button>
</form>That's the whole thing. Three details are worth naming:
'use server'must be the file's first line: the same kind of marker as'use client', pointing the other way. It says: everything exported here runs on the server.- The function body never reaches the browser. Your database credentials are safe inside it: the browser only gets a reference it can call.
- You never wrote a URL. Next.js creates the endpoint for you;
action={addItem}is the wiring.
One contrast with Fundamentals: these form inputs are uncontrolled. No useState, no value, no onChange: the browser keeps the text, and the name attribute is how the action finds it on submit.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing3Layouts & Metadata
The Root LayoutShared NavigationNested LayoutsPage MetadataDynamic MetadataRecap: Layouts6Server Actions
What Is a Server ActionForms That ActReading Form DataRefreshing the PageRecap: Server Actions