Doc 1
What are Server Functions?
A Server Function is an asynchronous function that runs on the server. They can be called from the client through a network request, which is why they must be asynchronous.
In an action or mutation context, they are also called Server Actions.
Good to know: A Server Action is a Server Function used in a specific way (for handling form submissions and mutations). Server Function is the broader term.
By convention, a Server Action is an async function used with startTransition. This happens automatically when the function is:
- Passed to a
<form>using theactionprop. - Passed to a
<button>using theformActionprop.
In Next.js, Server Actions integrate with the framework's caching architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip.
Behind the scenes, actions use the POST method, and only this HTTP method can invoke them.
Creating Server Functions
A Server Function can be defined by using the use server directive. You can place the directive at the top of an asynchronous function to mark the function as a Server Function, or at the top of a separate file to mark all exports of that file.
app/lib/actions.ts
TypeScript
JavaScriptTypeScript
export async function createPost(formData: FormData) { 'use server' const title = formData.get('title') const content = formData.get('content') // Update data // Revalidate cache} export async function deletePost(formData: FormData) { 'use server' const id = formData.get('id') // Update data // Revalidate cache}
Server Components
Server Functions can be inlined in Server Components by adding the "use server" directive to the top of the function body:
app/page.tsx
TypeScript
JavaScriptTypeScript
export default function Page() { // Server Action async function createPost(formData: FormData) { 'use server' // ... } return <></>}
Good to know: Server Components support progressive enhancement by default, meaning forms that call Server Actions will be submitted even if JavaScript hasn't loaded yet or is disabled.
Client Components
It's not possible to define Server Functions in Client Components. However, you can invoke them in Client Components by importing them from a file that has the "use server" directive at the top of it: