What are Server Functions?
A Server Function is an asynchronous function that runs on the server and can be called from the client through a network request. In an action or mutation context, they are also called Server Actions. By convention, a Server Action is an async function used withstartTransition. This happens automatically when the function is:
- Passed to a
<form>using theactionprop. - Passed to a
<button>using theformActionprop.
POST HTTP method.
Creating Server Functions
Use the'use server' directive to create a Server Function. Place the directive at the top of an async function body, or at the top of a separate file to mark all exports.
In Server Components
Server Functions can be inlined directly in Server Components:Server Components support progressive enhancement by default. Forms that call Server Actions will be submitted even if JavaScript has not loaded yet or is disabled.
In Client Components
You cannot define Server Functions inside a Client Component, but you can import and invoke them from a file that has'use server' at the top:
Passing actions as props
You can also pass a Server Action to a Client Component as a prop:Invoking Server Functions
Forms
React extends the HTML<form> element to allow a Server Function to be invoked with the action prop. The function automatically receives the FormData object:
Event handlers
Invoke a Server Function from a Client Component using event handlers such asonClick:
Examples
Showing a pending state
Use React’suseActionState hook to show a loading indicator while a Server Function is executing. It returns a pending boolean:
Refreshing data
After a mutation, refresh the current page to show the latest data by callingrefresh from next/cache:
refresh() refreshes the client router so the UI reflects the latest state. To also revalidate tagged cached data, use revalidateTag instead.
Revalidating the cache
After a mutation, revalidate Next.js cache entries to show updated data by callingrevalidatePath or revalidateTag:
Redirecting after a mutation
Redirect the user to a different page after a mutation by callingredirect from next/navigation:
redirect throws a framework-handled exception. Any code after it will not execute. Call revalidatePath or revalidateTag before calling redirect if you need fresh data on the destination page.Managing cookies
Get, set, and delete cookies inside a Server Action using thecookies API:
Using useEffect
Use the useEffect hook to invoke a Server Action when a component mounts or a dependency changes. This is useful for mutations that need to be triggered automatically, such as updating a view count:
