Server Actions for Data Mutations
Define 'use server' functions to handle form mutations and invalidate cache with revalidatePath.
Server Actions for Data Mutations is a free React Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Are Server Actions?
Server Actions are async functions marked with 'use server' that run exclusively on the server. They enable form submissions and data mutations without writing API route handlers.
Defining a Server Action
Add 'use server' at the top of the function (or the file) to create a Server Action. It can only be defined in Server Components or in dedicated actions.ts files.
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
await db.post.create({ data: { title } });
revalidatePath('/blog');
redirect('/blog');
}Using Actions in Forms
Pass the action function to a form's action prop. No onSubmit, no event handler — Next.js serializes the form and calls the action server-side.
import { createPost } from './actions';
export default function NewPostForm() {
return (
<form action={createPost}>
<input name="title" placeholder="Post title" required />
<button type="submit">Create</button>
</form>
);
}useActionState Hook
useActionState (React 19) wraps an action to track pending state and receive the action's return value in the component.
'use client';
import { useActionState } from 'react';
import { createPost } from './actions';
const initialState = { error: null };
export function PostForm() {
const [state, action, isPending] = useActionState(createPost, initialState);
return (
<form action={action}>
{state.error && <p className="error">{state.error}</p>}
<input name="title" />
<button disabled={isPending}>{isPending ? 'Creating...' : 'Create'}</button>
</form>
);
}Returning Validation Errors
Return an object from the action instead of throwing to pass validation errors back to the form via useActionState.
export async function createPost(prevState: any, formData: FormData) {
'use server';
const title = formData.get('title') as string;
if (!title || title.length < 3) {
return { error: 'Title must be at least 3 characters' };
}
await db.post.create({ data: { title } });
revalidatePath('/blog');
redirect('/blog');
}Server Actions in Event Handlers
Call Server Actions from Client Component event handlers (not just form actions) by importing and calling them directly.
'use client';
import { deletePost } from './actions';
export function DeleteButton({ id }: { id: string }) {
return (
<button onClick={() => deletePost(id)}>
Delete
</button>
);
}Inline Server Actions
Define Server Actions inline in a Server Component using a function with 'use server' inside it — useful for co-located mutation logic.
export default function PostPage({ post }) {
async function updatePost(formData: FormData) {
'use server';
await db.post.update({ where: { id: post.id }, data: { title: formData.get('title') as string } });
revalidatePath(`/blog/${post.id}`);
}
return (
<form action={updatePost}>
<input name="title" defaultValue={post.title} />
<button type="submit">Save</button>
</form>
);
}useOptimistic with Server Actions
Pair useOptimistic with Server Actions to update the UI instantly while the action runs in the background.
'use client';
import { useOptimistic } from 'react';
import { addItem } from './actions';
export function TodoList({ items }) {
const [optimisticItems, addOptimistic] = useOptimistic(items, (state, newItem) => [...state, newItem]);
return (
<form action={async (formData) => {
addOptimistic({ id: 'temp', text: formData.get('text') });
await addItem(formData);
}}>
<ul>{optimisticItems.map(i => <li key={i.id}>{i.text}</li>)}</ul>
<input name="text" /><button>Add</button>
</form>
);
}Security Considerations
Server Actions are POST endpoints under the hood. Always validate and sanitize inputs server-side, check authentication, and use CSRF protection (Next.js handles this automatically for same-origin).
Revalidating After Mutations
Call revalidatePath() or revalidateTag() after a mutation to clear the relevant caches so the next page load reflects the change.
Quick Check
How do you pass a Server Action to a form in Next.js App Router?
Recap
Server Actions are 'use server' async functions that handle mutations server-side. Connect them to forms via the action prop, track state with useActionState, return errors instead of throwing for validation, and revalidate caches after mutations.
Frequently asked questions
Is the “Server Actions for Data Mutations” lesson free?
Yes — the full text of “Server Actions for Data Mutations” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Server Actions for Data Mutations”?
Define 'use server' functions to handle form mutations and invalidate cache with revalidatePath. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Server Actions for Data Mutations” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- fetch() with Cache Options in Next.js
- unstable_cache & React cache()
- Incremental Static Regeneration (ISR)
- Server Actions for Data Mutations