Server Actions basics
Define a Server Action with use server, call it from a form, pass extra arguments with bind, and treat it as a public POST endpoint that needs auth checks.
Client-side data fetchingComposing Server and Client Components
Server Actions basics
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A Server Action is an async function marked with use server that runs on the server and can be called from the browser, so a form can mutate data without you writing an API endpoint.
- Pass the function to a form's action prop and it receives the form's FormData; forms in Server Components work even before JavaScript loads.
- Server Actions cannot be defined inside Client Components, but a Client Component can import them from a file that begins with use server.
- Actions run as POST requests that anyone can send, so authenticate and authorize inside every action; hiding the form is not a security boundary.
- One round trip carries both the action's result and the re-rendered page when the action invalidates cache with updateTag, revalidatePath, refresh, sets a cookie, or redirects.
The problem Server Actions solve
To save a form, the old recipe has four moving parts: an event handler that collects the fields, a fetch that posts them, an API route that receives them, and state to show what happened. The handler and the route are two ends of the same wire, and keeping them in sync is boilerplate.
A Server Action collapses the two ends into one function. You write the function, mark it as server code, and hand it to a form. Next.js generates the wire for you.
The shape of an action
An action is an async function with the use server directive. The docs call the broader concept a Server Function, and a Server Action is one used for forms and mutations.
// app/page.tsx
export default function Page() {
async function createPost(formData: FormData) {
'use server'
const title = formData.get('title')
const content = formData.get('content')
// mutate data, then invalidate cache
}
return (
<form action={createPost}>
<input type="text" name="title" />
<textarea name="content" />
<button type="submit">Create</button>
</form>
)
}
React extends <form action> so that passing a function runs it on submit, and the function receives a FormData object. In a Server Component, the form works without JavaScript, because the browser submits it natively and the server runs the action. The docs call this progressive enhancement.
You can also put the directive at the top of a separate file to mark every export. That is how Client Components use actions:
// app/actions.ts
'use server'
export async function createPost(formData: FormData) { /* ... */ }
// app/ui/button.tsx
'use client'
import { createPost } from '@/app/actions'
export function Button() {
return <button formAction={createPost}>Create</button>
}
You cannot define an action inside a Client Component; you import one. In a Client Component, the docs note that submissions queue until JavaScript loads and are prioritized for hydration.
Extra arguments
If a value is not a form field, such as the id of the record being edited, use bind:
'use client'
import { updateUser } from './actions'
export function UserProfile({ userId }: { userId: string }) {
const updateUserWithId = updateUser.bind(null, userId)
return (
<form action={updateUserWithId}>
<input type="text" name="name" />
<button type="submit">Update</button>
</form>
)
}
'use server'
export async function updateUser(userId: string, formData: FormData) {}
The docs’ alternative is a hidden input, with the caveat that the value is then part of the rendered HTML.
The action is a public endpoint
This is the part to take seriously. Behind the scenes an action is a POST request to the page that uses it. The implementation stays on the server, but the endpoint is reachable by anyone who can send the same request. The docs’ warning is blunt: verify authentication and authorization inside every Server Function.
'use server'
import { auth } from '@/lib/auth'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) throw new Error('Unauthorized')
// also check this user may delete this post, then delete it
}
Next.js adds protections: an Origin against Host check to block cross-site requests, a 1 MB default body limit, and encrypted action ids. They are not a substitute for your checks. Treat FormData as untrusted input, and send an id plus the user’s change, not a whole record the client could have tampered with.
What an action can do after the mutation
A single request can run the action and re-render the current route. The response carries both the action’s return value and, if the action did any of these, a fresh render: call updateTag, call revalidatePath, call refresh, set or delete a cookie, or redirect. redirect throws, so call your invalidation first. Actions are also dispatched one at a time from a given client, so do not rely on Promise.all to run them in parallel.
What the video covers
Codevolution’s Next.js 15 video builds a form that adds a product to a database with an action. Its chapters: introduction, project setup, creating the form component, defining the action, connecting it to the form, handling form data, database interaction, testing, benefits of Server Actions, and progressive enhancement. It does not cover validation, revalidation, or authorization, so this lesson adds them and the next lessons build on them.
Where this fits
You can now send data to the server. A bare form gives no feedback, so the next step is making it communicate. Next: forms and pending states. The React side of actions is in server actions and mutations.
Check yourself
What does the use server directive do at the top of a function or file?
It marks async functions as Server Functions, so the compiler replaces their code in client bundles with a reference that sends a POST request back to the server where the real function runs.
Why is checking the user inside a Server Action not redundant when the form only appears on a signed-in page?
Actions are reachable by direct POST requests that never pass through the UI, so rendering the form only for signed-in users does not stop someone else from calling the action.
How do you give an action an extra argument such as a user id that is not a form field?
Use bind on the function, for example updateUser.bind(null, userId), and the action receives the id as its first argument followed by the FormData.
What happens to the page after a Server Action calls updateTag or revalidatePath?
Next.js re-renders the current route on the server and returns the new RSC payload in the same response as the action result, so the page updates in one round trip.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.