Next.jsMedium

How do you use use server directive?

"use server" marks functions as Server Functions that the client can call over the network. Put it at the top of a file to mark every export, or as the first line inside an async function to mark just that function. It does not mark a component as a Server Component.

Two placements

  • File level (actions.ts starting with "use server"): every exported function becomes a Server Function and must be async. Client Components can import these.
  • Inline (first statement in an async function inside a Server Component): defines a Server Function inline. It can close over variables from the component; Next.js encrypts captured values before sending them to the client.

Rules

  • Functions must be async.
  • Arguments and return values must be React-serializable (FormData, plain objects, primitives, Dates, Maps, Sets).
  • A Client Component cannot define an inline Server Function; it must import one from a "use server" file or receive one as a prop.
  • "use server" files should export only async functions. Do not export constants or objects from them.

Common misconception

Components are Server Components by default in the App Router; you never need "use server" for that. "use server" is only for functions exposed to the client. To keep a module off the client, use the server-only package instead.

Security

Each Server Function is reachable by anyone who has its ID. Check the session and permissions inside the function, validate input, and avoid passing sensitive values through closures even though they are encrypted.

Where they run

In Server Components, forms, event handlers, useEffect, and passed as props. Proxy does not apply directive transforms, so "use server" has no effect there.

Code example

tsx
1// app/lib/actions.ts - file-level: every export is a Server Function
2"use server";
3
4import { revalidatePath } from "next/cache";
5import { verifySession } from "@/lib/auth";
6import { db } from "@/lib/db";
7
8export async function deletePost(id: string) {
9 const user = await verifySession();
10 await db.post.delete({ where: { id, authorId: user.id } });
11 revalidatePath("/posts");
12}
13
14// app/posts/[id]/page.tsx - inline Server Function inside a Server Component
15// export default async function Page({ params }: PageProps<"/posts/[id]">) {
16// const { id } = await params;
17//
18// async function publish() {
19// "use server"; // captures `id` (encrypted when sent to the client)
20// const user = await verifySession();
21// await db.post.update({ where: { id, authorId: user.id }, data: { published: true } });
22// }
23//
24// return <form action={publish}><button>Publish</button></form>;
25// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app