Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 72 ยท Mutations and Forms

Server Actions

Learn Next.js Server Actions: the use server directive, file-level and inline actions, form actions, progressive enhancement and how a call becomes a POST.

So far this tutorial has been about reading: routing, rendering, fetching and caching. Real apps also change things. A visitor posts a comment, adds a product to a cart, updates a profile. In classic web development that meant writing an API endpoint, then writing browser code that calls it with fetch, then wiring the two together by hand.

A Server Action removes most of that wiring. It is an async function that runs on the server, marked with the 'use server' directive, which you can call from your components almost as if it were a local function. Next.js turns the call into a network request for you. This lesson explains the directive, the two ways to place it, how an action plugs into a <form>, and what really happens on the wire. The next lesson, Building Forms with Server Actions, covers the form UI in depth.

Real or stand-in? The tsx blocks in this lesson are real Next.js code, shown read-only. The live examples are stand-ins written in plain Node.js. They imitate the idea of "call a server function by name through a POST request", but Next.js uses its own internal wire format, which you should never depend on. The stand-ins say where they simplify.

Two ways to write an action

The 'use server' directive tells the bundler that a function belongs to the server and may be called from the client. You can put it in two places.

File level. Put the directive on the first line of a file. Every exported function in that file becomes a Server Action, and Client Components can import them:

TypeScript
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';

export async function addComment(formData: FormData) {
  const text = String(formData.get('text') ?? '').trim();
  if (text.length === 0) {
    return;
  }
  await db.comment.create({ data: { text } });
  revalidatePath('/guestbook');
}

Inline. Put the directive at the top of a function body inside a Server Component:

TSX
// app/guestbook/page.tsx  (a Server Component)
import { db } from '@/lib/db';

export default async function Guestbook() {
  async function addComment(formData: FormData) {
    'use server';
    await db.comment.create({ data: { text: String(formData.get('text')) } });
  }

  return (
    <form action={addComment}>
      <input name="text" />
      <button type="submit">Post</button>
    </form>
  );
}

Inline actions are handy for small cases, and they can read variables from the surrounding component. Next.js encrypts those captured values before sending them to the browser, so they do not leak. Even so, a separate file is easier to review, to reuse from Client Components and to test, so most teams keep actions in actions.ts files.

An inline 'use server' function is only allowed inside a Server Component. A file that starts with 'use client' cannot define one inline. Put the actions in a 'use server' file and import them instead.

Calling an action from a form

React 19 lets you pass a function to a form's action prop. When the form is submitted, React calls the function with the form's data as a FormData object:

TSX
import { addComment } from '@/app/actions';

export default function CommentForm() {
  return (
    <form action={addComment}>
      <textarea name="text" required />
      <button type="submit">Post comment</button>
    </form>
  );
}

There is no onSubmit, no preventDefault, no fetch and no JSON. The name attributes of the fields become the keys in formData. This is the same action prop you met in Form Actions in React 19; the only new thing is that the function now lives on the server.

You can also call an action from an event handler or an effect in a Client Component, passing ordinary arguments:

TSX
'use client';

import { deletePost } from '@/app/actions';

export function DeleteButton({ id }: { id: string }) {
  return <button onClick={() => deletePost(id)}>Delete</button>;
}

Arguments and return values must be serializable: strings, numbers, booleans, null, undefined, plain objects and arrays, Date, Map, Set, FormData and a few more. Functions and class instances cannot cross the boundary.

What really happens: a function call becomes a POST

An action looks like a function call, but there is a network between the two sides. At build time Next.js gives each action an ID and keeps a table of IDs on the server. In the browser the imported addComment is not your function at all. It is a small stub that knows the ID.

One call, five steps

Submit or call The browser stub receives your arguments.
Serialize Arguments are packed into a request body.
POST The ID travels in a request header.
Run The server looks up the ID and runs your function.

The result is sent back, and the UI updates.

1 / 2

Concretely, the stub sends a POST request to the URL of the current page, with a Next-Action header holding the ID. The server finds the matching function, runs it, and replies. The exact encoding of arguments and results is an internal detail that changes between versions, so treat it as a black box. What matters is the shape of the idea: a name lookup, a POST and a response.

sequenceDiagram
    participant B as Browser
    participant S as Next.js server
    B->>S: POST /guestbook<br/>Next-Action: id, body: arguments
    S->>S: Look up id, run your function
    S-->>B: Result (and fresh UI if data changed)

A Server Action call is an ordinary POST request with an action ID in a header.

This stand-in builds that idea in plain Node.js. A registry maps IDs to functions, a "client stub" turns a call into a request, and a "server" dispatches by ID. Note what it does and does not copy: the real IDs are generated at build time and the real body is not plain JSON.

Node.js A stand-in for how a call becomes a POST

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last call shows why IDs matter: a request with an unknown ID gets a 404. But notice the reverse: any valid ID can be called by anyone who can send a POST, with any arguments. That is why every action must treat its input as untrusted and check who is calling. We cover this properly in Validating Input and Authorization and Data Security.

Progressive enhancement

A form that uses a Server Action can work before any JavaScript has loaded. When the action is passed to <form action> in a Server Component, Next.js renders the form with a hidden field containing the action ID and a plain HTML method="POST". If JavaScript has not arrived yet, the browser submits the form the old-fashioned way, as a full page request, the server runs the action and the page reloads with the result. (Forms inside Client Components that use an action behave a little differently: the submission is queued until the page has hydrated.) Once JavaScript is ready, React takes over: the submit becomes a background request and the page updates without a reload.

This is called progressive enhancement, and it makes forms resilient on slow connections. It only holds when the action receives FormData and the form does not depend on client-side state to work. An action called from onClick with custom arguments needs JavaScript, because only a form can submit natively.

This second stand-in shows the no-JavaScript path: a browser sends a URL-encoded body, the server turns it into a FormData-like object, runs the action and answers with a redirect.

Node.js The no-JavaScript path: a form is just a POST

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The real hidden field name and body format are different, but the principle is exactly this: with progressive enhancement the server accepts a normal form post, runs your function, and the browser follows a redirect.

Updating the page after an action

An action usually changes data that some page shows. Next.js lets the action say what is now stale, with functions like revalidatePath and revalidateTag from next/cache, or redirect from next/navigation. When an action finishes, the response can include the updated UI for the current page, so the browser shows fresh data without a manual refetch. Cache invalidation gets its own lessons (Revalidating Data and Optimistic UI and Refreshing After Mutations). For now remember the rule: an action changes data, then tells Next.js which cached pages are out of date.

Server Actions or Route Handlers?

Actions are meant for mutations triggered by your own UI. They are not the right tool for a public API that other programs call, for webhooks, or for reading data: they are POST-only, their wire format is private, and Next.js queues them. For those jobs use Route Handlers, which are ordinary HTTP endpoints.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the 'use server' directive at the top of a file do?

    At file level, 'use server' marks all exported functions as Server Actions. Inline, it marks a single function inside a Server Component.
  2. 2. What does a Server Action called from a form receive as its argument?

    React 19 calls a function passed to form action with the form's FormData, keyed by the fields' name attributes.
  3. 3. Why must a Server Action check permissions even if only an admin page uses it?

    Hiding the button does not protect the function. Treat every action like a public endpoint and verify the caller and the input inside it.
  4. 4. What is progressive enhancement for forms?

    A form using a Server Action carries enough information to submit natively, so it works without JavaScript and becomes smoother once React is running.
  5. 5. Which values can NOT be passed to a Server Action as arguments?

    Arguments must be serializable to travel over the network. Functions and class instances cannot be serialized.

Summary

  • A Server Action is an async function marked with 'use server', either at the top of a file (all exports) or at the top of a function inside a Server Component.
  • Pass an action to <form action={...}> and it receives FormData; you can also call it from handlers with serializable arguments.
  • Under the hood a call becomes a POST carrying an action ID; the wire format is private and may change.
  • Every action is a public endpoint: validate input and check permissions inside it.
  • Forms using actions work without JavaScript and upgrade once it loads.
  • Use Route Handlers, not actions, for public APIs, webhooks and reads.

Next: Building Forms with Server Actions