CodePark/ questions / Server Actions
START PRACTICINGPRACTICE
Frontend question · Next.js › Server Actions

What are Server Actions and how do they work under the hood?

Server Actions are async functions marked with "use server". They run on the server, but you can call them from the client. Their main job is mutations, such as saving a form.

Under the hood:

  • At build time, Next.js replaces each action with a reference ID.
  • When the client calls the action, Next.js sends a POST request to the current route. The request carries the ID and the serialized arguments (turned into data that can travel over the network).
  • The server runs the function and returns its serializable result.
  • If the action calls revalidatePath, revalidateTag or redirect, the updated UI comes back in the same round trip.

You can call actions from:

  • a form's action prop
  • a button's formAction prop
  • event handlers and effects in Client Components

They remove the need to write an API route plus a fetch call for every mutation.

  • Server Actions are defined with "use server" and run only on the server.
  • The client calls them through a POST request with an action ID.
  • Arguments and return values must be serializable.
  • Revalidation and redirect results come back in one round trip.
  • You can call them from forms, buttons and event handlers.