Server Actions and Mutations

Handle form submissions and data changes with server actions, with validation, authorization and revalidation on every call.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Data Fetching and Caching in Next.js, Forms and User Input

Server Actions are async functions marked with "use server" that run on the server but can be called from forms and client components. They remove a lot of API boilerplate for mutations inside a Next.js app.

How they work

  • Pass an action to a form's action prop; the form works even before JavaScript loads (progressive enhancement).
  • Read FormData, validate with Zod, write to the database, then revalidatePath or redirect.
  • Use useActionState to return validation errors to the form, and useFormStatus for pending states.

Treat every action as a public endpoint

An action is reachable by anyone who can send an HTTP request. On every call:

  • Authenticate: who is calling?
  • Authorize: may this user change this record?
  • Validate: never trust FormData or arguments.

When to use a route handler instead

Use actions for mutations triggered by your own UI. Use API routes for webhooks (Razorpay, GitHub), mobile apps, third-party clients and anything that needs a stable public URL.

Pitfalls

  • Skipping auth checks because "the button is only shown to admins".
  • Returning full database objects to the client.
  • Forgetting to revalidate, so the UI shows stale data after a successful change.

You are ready to move on when your application form submits through a server action that validates input, checks the user's session, writes data, revalidates the dashboard and shows field errors without a page reload.

Key concepts

  • "use server" functions
  • Forms and progressive enhancement
  • useActionState and useFormStatus
  • Validation inside actions
  • Auth checks in every action
  • Revalidate and redirect
  • Actions vs route handlers

Mini project

Implement create, edit and withdraw for internship applications using server actions, with Zod validation, pending states, field-level errors and dashboard revalidation.

Check yourself

Why must a server action check authorization even if the button that calls it is hidden from unauthorised users?

Free resources