Skip to content
Data & CachingChapter 17 / 34Intermediate5 min read

Server Actions

What Next.js server actions are and how the use server directive runs forms and mutations on the server, with auth checks and revalidation.

On this page

1. What are Server Actions?

Before, to save data you would create an API route and then call fetch("/api/...") from the client. With Server Actions you just write a function, and Next.js creates a secure POST endpoint for it automatically.

In React's terms these are called Server Functions. When they are used for a form action or a mutation, Next.js calls them Server Actions.

2. Why does it matter?

API route + client fetchServer Action
A separate API file and separate client codeOne function, called straight from the form
Build and parse a JSON bodyFormData arrives automatically
Loading state by handuseActionState gives you pending
The form does not work before JavaScript loadsProgressive enhancement, it submits even without JS
Cache refresh is separateupdateTag or revalidatePath in the same function

3. Where is it used?

Use caseWhat the action does
Create postInserts a row in the database, then redirects
Like buttonUpdates the count, then calls updateTag
Profile settingsValidates and saves the form data
Delete itemChecks auth, deletes, refreshes the list
LogoutDeletes the session cookie

4. How does it work?

Server Action flow
The user submits the form
The browser sends a POST request
Next.js finds the right Server Action
The action runs on the server
Database update + cache invalidation
The updated UI comes back in a single round trip

You can write "use server" in two places:

PlaceEffect
The first line of a fileAll exports of the file become Server Actions, and Client Components can import them
The first line of an async function bodyOnly that function is a Server Action, inline inside a Server Component

5. Code example

Example 1: the actions file

ts
"use server";

import { updateTag } from "next/cache";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { verifySession } from "@/lib/dal";

export async function createTodo(formData: FormData) {
  const session = await verifySession();
  const title = String(formData.get("title") ?? "").trim();

  if (!title) {
    return;
  }

  await db.todo.create({ data: { title, userId: session.userId } });
  updateTag("todos");
  redirect("/todos");
}

export async function deleteTodo(id: string) {
  const session = await verifySession();
  await db.todo.delete({ where: { id, userId: session.userId } });
  updateTag("todos");
}

Example 2: calling it from a form and a button

tsx
import { createTodo, deleteTodo } from "./actions";

export default function TodoPage() {
  return (
    <main>
      <form action={createTodo}>
        <input name="title" placeholder="New task" required />
        <button type="submit">Add</button>
      </form>

      <form action={deleteTodo.bind(null, "todo_123")}>
        <button type="submit">Delete</button>
      </form>
    </main>
  );
}

How does the code work?

PartMeaning
"use server" at the top of the fileAll exported functions are Server Actions
verifySession()Identifies the user first in every action
formData.get("title")Gets the value using the input's name attribute
updateTag("todos")The user immediately sees the new list
redirect("/todos")Sends the user to another page after the work is done
deleteTodo.bind(null, id)A way to pass an extra argument

To show the pending state and validation errors, you use useActionState. The details are in the Forms & Validation chapter.

Interview tip

The right answer to "Why are Server Actions secure?" is: they are not secure by themselves. Every action is a POST endpoint, so authentication, authorization and input validation are needed inside it.

6. Common mistakes

Mistake: Not checking auth inside the action

Why? Even if the button is hidden in the UI, anyone can build a request and call the action.

Better: Verify the session at the start of every action and check ownership.

Mistake: Putting FormData in the database without validation

Why? The user can send anything, so wrong or dangerous data gets saved.

Better: Build a schema with a library like Zod and use safeParse.

Mistake: Using a Server Action to read data

Why? Actions are for mutations, they run one after another and are not cached.

Better: Read data in Server Components and use actions only for writing.

Mistake: Putting redirect inside try catch

Why? redirect throws a special error, the catch block swallows it and the redirect does not happen.

Better: Call redirect outside try catch, after the work is complete.

7. What to learn before and after

Final quick revision

PointDetail
Directive"use server" at file or function level
How to call<form action={fn}> or from an event handler
InputFormData
SecurityAuth + validation in every action
Follow-up workupdateTag, revalidatePath, redirect