Next.js 31: Server Actions Basics
easy⏱ 5 mincoursenextjs
The "use server" directive
Add 'use server' at the top of a function (or the top of a file) to mark every exported function in it as a Server Action. Next.js turns each one into a secure network endpoint automatically — no /api route to write. You import the action into a Client Component and call it like a normal function; Next.js serializes the call, runs it on the server, and returns the result.
// app/actions.ts
'use server';
export async function addComment(formData: FormData) {
const text = formData.get('comment');
await db.comment.create({ data: { text } });
return { id: Date.now(), text };
}
Rules for Server Actions
A Server Action must be async — that's how Next.js recognizes it. Its arguments and return value must be serializable (plain objects, strings, numbers, FormData — no functions or class instances). The function body only ever runs on the server, so it's safe to access a database, secrets, or the filesystem directly inside it.
Simulate your first Server Action
Write an addCommentAction function that awaits a fake delay (setTimeout wrapped in a Promise) and returns a new comment object — comment it as simulating a Server Action, since this sandbox has no real server. Call it from a form's submit handler, show a posting… state on the button while it runs, and append the result to a list. Keep export default App.