Creating a Server Action: The 'use server' Directive
What you'll learn: How to mark functions as server-only code using the 'use server' directive so they never ship to the client bundle.
The Core Idea
Just as 'use client' marks the boundary where JavaScript must ship to the browser, 'use server' marks code that must never leave the server. When you add this directive to an async function or at the top of a file, you're telling React: "This code accesses backend resources and should only execute on the server."
This is how you create a Server Action — a function that clients can call, but that always runs on your server with full backend access.
Two Ways to Use It
Option 1: Top of File
'use server'
// Everything in this file is a Server Action
export async function createUser(formData) {
const db = await connectToDatabase()
await db.users.insert(formData.get('name'))
}
export async function deleteUser(id) {
const db = await connectToDatabase()
await db.users.delete(id)
}
Option 2: Inside a Function
export default function ServerComponent() {
async function handleSubmit(formData) {
'use server'
// Only this function is a Server Action
const db = await connectToDatabase()
await db.save(formData)
}
return <form action={handleSubmit}>...</form>
}
Think of It Like a Security Checkpoint
Imagine 'use server' as a one-way mirror: clients can call these functions (through forms or transitions), but they can never see the code inside. Database credentials, API keys, business logic — all safely hidden on the server.
Key Takeaway: Use 'use server' at the top of async functions or files to create Server Actions that execute only on the server, keeping sensitive code and credentials completely out of your client bundle.