Server Actions and mutations

Advanced · 20 min

'use server' functions, calling one from a form action, and how mutating data this way changes the client/server round trip versus REST.

Before thisServer Components vs. Client ComponentsForms and controlled inputs

Theo - t3.gg · 20 min

Server Actions and mutations

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Theo - t3.ggReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A Server Action is an async function marked with `'use server'` that runs only on the server, but can be called directly from client code as if it were a normal function — React handles turning that call into a network request.
  • Passing a Server Action straight to a form's `action` prop, as in `<form action={createPost}>`, lets the browser submit the form and run that server function without you writing a fetch call or an API route by hand.
  • A Server Action can mutate data — write to a database, call another service — directly from inside the component tree it's defined near, collapsing the usual gap between the component that shows a form and the API route that handles its submission.
  • Compared to a traditional REST or fetch-based mutation, a Server Action removes the step of hand-defining a URL, an HTTP method, and a request/response shape; the function signature itself is the contract between client and server.
  • Server Actions still cross the network — calling one is not free, and it still needs the same validation and authorization checks a REST endpoint would need, because the function is reachable from any client, not just the form you wrote.
  • `'use server'` is a React primitive for marking a function as server-callable, available to any framework that implements the RSC contract; it is not unique to Next.js even though most current demonstrations use it.

A function you can call across the network

The previous lesson drew a hard line: Server Components run only on the server, and a Client Component can’t reach across that line to call server-side code directly. Server Actions are the one sanctioned way to cross it in the other direction — from the client, into a function that only runs on the server.

A Server Action is just an async function with 'use server' at the top, either as the file’s first line (every export in the file becomes an action) or as the function’s first line:

// actions.js
"use server";

import { db } from "./db";

export async function createPost(formData) {
  const title = formData.get("title");
  const body = formData.get("body");

  if (!title || title.length < 3) {
    throw new Error("Title must be at least 3 characters");
  }

  await db.posts.create({ title, body });
}

Nothing about this function looks special — it’s an ordinary async function that touches a database. The directive is what tells the build tooling: generate a reference to this function that a Client Component can import and call, and route that call to the server when it happens.

Calling it from a form

The most direct use of a Server Action is wiring it straight into a form’s action prop:

// NewPostForm.jsx — a Server Component
import { createPost } from "./actions";

export default function NewPostForm() {
  return (
    <form action={createPost}>
      <input name="title" placeholder="Title" />
      <textarea name="body" placeholder="Write something…" />
      <button type="submit">Publish</button>
    </form>
  );
}

This is plain HTML form behavior extended by React: when the form submits, React collects the form’s fields into a FormData object and calls createPost(formData) on the server, then re-renders whatever on the page depends on the result. Compare this to the fetch-based version you’d write without Server Actions:

"use client";
import { useState } from "react";

export default function NewPostForm() {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

  async function handleSubmit(e) {
    e.preventDefault();
    await fetch("/api/posts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title, body }),
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={title} onChange={(e) => setTitle(e.target.value)} />
      <textarea value={body} onChange={(e) => setBody(e.target.value)} />
      <button type="submit">Publish</button>
    </form>
  );
}

The fetch version needs a Client Component (for useState and onSubmit), a hand-written /api/posts route somewhere else in the codebase that parses the JSON body, and manual control over every field’s value. The Server Action version needs none of that plumbing: the form stays an uncontrolled, server-rendered component, and createPost is the endpoint — there’s no separate route file to keep in sync with it.

Mutating from inside the component tree

Because a Server Action can live in the same module as the Server Component that renders the form, the mutation logic sits physically close to the UI that triggers it, rather than in a separate routes folder:

// PostList.jsx — a Server Component
import { db } from "./db";
import { createPost } from "./actions";

export default async function PostList() {
  const posts = await db.posts.findAll();

  return (
    <div>
      <form action={createPost}>
        <input name="title" placeholder="Title" />
        <button type="submit">Add post</button>
      </form>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

After createPost runs, the framework re-fetches and re-renders the Server Components affected by the change — in a properly wired setup this is typically paired with a cache-invalidation call inside the action itself, so PostList picks up the new post on the next render rather than showing stale data.

The round trip, compared to REST

A traditional REST mutation involves several things you design by hand: a URL (POST /api/posts), a request body shape, a response shape, a client-side function that calls fetch with the right method and headers, and code on the server that parses the request and sends back a matching response. Keeping all of those in sync as the API evolves is a real, ongoing cost.

A Server Action collapses most of that into one function signature. The “endpoint” is the function itself; calling it from the client looks exactly like calling any other async function, and the framework handles serializing the call and its arguments into a network request behind the scenes. This doesn’t mean the network round trip disappears — the function still executes on a server, still takes the same time a REST call would, and still needs the same defenses, since it’s just as reachable from a malicious or buggy client as any public API route. What changes is how much hand-written plumbing sits between the UI and the mutation, not whether a mutation still has to cross the network and be validated when it gets there.

What the video covers

Theo’s video tackles 'use server' and Server Actions as a React primitive rather than a Next.js-only feature, and walks through several implementation patterns including calling a server function directly from a form, which lines up with this lesson’s core examples. It leans opinionated in its second half, critiquing the pattern’s ergonomics and suggesting an alternative data-access-layer approach rather than fully endorsing Server Actions as shown — that critique is a legitimate opinion, but this lesson’s prose above sticks to the straightforward “how it works and how to use it” framing rather than the video’s more skeptical take. It’s demoed inside Next.js, as most current Server Action content is, but the directive and the calling convention it describes belong to React’s own RSC model.

Where this fits

This closes out the server-side React group. From here the roadmap moves into shipping a real app day to day, starting with styling approaches for React.

Check yourself

  1. 01What does the `'use server'` directive mark?

    It marks a specific async function (or every export in a file) as a Server Action — code that runs only on the server but can be invoked directly from client-side code or a form, without you building a separate API route for it.

  2. 02How does `<form action={createPost}>` differ from a traditional `<form onSubmit={...}>` that calls `fetch`?

    Passing a Server Action to `action` lets the browser submit the form natively, including before JavaScript has finished loading in some setups, and React serializes the form data into a call to that server function directly; `onSubmit` with `fetch` requires you to manually prevent the default submission, read form values, and call an endpoint yourself.

  3. 03Does using a Server Action remove the need for validation and authorization on the server?

    No. A Server Action is reachable over the network by any client, exactly like a REST endpoint, so it still needs to validate its input and check that the caller is allowed to perform the mutation, the same way a traditional API route would.

  4. 04Is 'use server' a Next.js-only feature?

    No. It is part of the React Server Components model itself, meaning any framework that implements RSCs can support Server Actions; Next.js is simply the framework most current tutorials happen to demonstrate it in.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark