What are Server Actions in Next.js?
Answer
Server Actions are async functions that run on the server but can be called from Client Components (and Server Components). They eliminate the need for manual API routes for form submissions and data mutations. Defining a Server Action: add "use server" directive: // In a Server Component or separate file async function createUser(formData: FormData) { "use server"; const name = formData.get("name") as string; await db.users.create({ name }); revalidatePath("/users"); } // Use directly in a form: <form action={createUser}> <input name="name" /> <button type="submit">Create</button> </form>. In a Client Component: "use client"; import { createUser } from "./actions"; export function Form() { return <form action={createUser}>...</form>; }. Calling programmatically: const result = await createUser(data) from a Client Component. Benefits: (1) No manual API route needed; (2) Progressive enhancement — forms work without JavaScript (POST request); (3) Automatic CSRF protection; (4) Co-locate data mutations with components; (5) TypeScript end-to-end type safety. With useFormState and useFormStatus (React hooks): manage form state and pending state in Client Components. Revalidation in Server Actions: call revalidatePath() or revalidateTag() to refresh cached data after mutation. Error handling: use try/catch and return objects; or let errors propagate to the nearest error boundary.