Advertisement
Beginner Next.js, Server Actions & Mutations

What is a server action in Next.js, and what problem does it solve?

Short answer

A server action is a function marked with a use server directive that runs only on the server but can be called directly from a client component or a form, letting you update data, such as saving a form submission, without needing to manually create a separate API route just to…

Save Next.js mock interview
Advertisement
AModel answer
A server action is a function marked with a use server directive that runs only on the server but can be called directly from a client component or a form, letting you update data, such as saving a form submission, without needing to manually create a separate API route just to handle that one operation.
'use server';

export async function addTodo(formData) {
  const text = formData.get('text');
  await db.todo.create({ data: { text } });
}
Real-world example
A simple todo application lets users add new tasks by submitting a form directly to a server action, without the developer needing to build and maintain a separate API endpoint just for creating todos.
Likely follow-ups
  • Where should the use server directive be placed in a file?
  • Can a server action be called from a regular button click as well as a form submission?
Related topics