Server Functions
A Server Function is an asynchronous function that runs on the server. You
mark it with the 'use server' directive so Next.js knows it may be called
across the network from the client.
The directive goes at the top of a separate file, which marks every export in that file as a Server Function:
// app/actions.ts
'use server';
export async function createPost(formData: FormData) {
await db.post.create({ data: { title: formData.get('title') } });
}
You can also place it at the top of an async function body to mark just that
one function:
// app/page.tsx
export default function Page() {
async function createPost(formData: FormData) {
'use server';
// runs on the server
}
return <form action={createPost}>{/* ... */}</form>;
}
Because the function runs on the server, it can read secrets, query a database,
and use server-only modules safely — none of that code ships to the browser. You
cannot define a Server Function inside a Client Component, but a Client
Component can import one from a 'use server' file and invoke it.
Behind the scenes, the client invokes a Server Function with a POST request.
When one is used for a mutation or a form submission, it is also called a
Server Action.
You are about to answer a short quiz on 'use server'.