Lesson 3 of 10
Server Actions & Mutations
Server Actions let you call server-side functions directly from client components - with built-in form integration. They replace API routes for most mutation patterns, providing automatic CSRF protection, TypeScript end-to-end types, and progressive enhancement (forms work without JavaScript).
Server Actions - Complete Patterns
// ---- Simple Server Action - form submission ----
// app/posts/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';
const createPostSchema = z.object({
title: z.string().min(1, 'Title required').max(100),
content: z.string().min(10, 'Content too short'),
});
// Return type for client to handle success/error
export interface ActionResult {
success: boolean;
message: string;
errors?: Record<string, string[]>;
}
export async function createPost(formData: FormData): Promise<ActionResult> {
// 1. Parse & validate
const parsed = createPostSchema.safeParse({
title: formData.get('title'),
content: formData.get('content'),
});
if (!parsed.success) {
return {
success: false,
message: 'Validation failed',
errors: parsed.error.flatten().fieldErrors,
};
}
// 2. Auth check
const session = await getServerSession();
if (!session) redirect('/login');
// 3. Database operation
try {
await db.posts.create({ data: { ...parsed.data, authorId: session.userId } });
revalidatePath('/posts'); // invalidate posts page cache
return { success: true, message: 'Post created successfully' };
} catch {
return { success: false, message: 'Failed to create post' };
}
}
// ---- Client component using Server Action ----
// app/posts/CreatePostForm.tsx
'use client';
import { useActionState, useFormStatus } from 'react';
import { createPost } from './actions';
// useFormStatus - gives pending state within a form
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Creating...' : 'Create Post'}
</button>
);
}
export function CreatePostForm() {
const [result, dispatch] = useActionState(createPost, null);
return (
<form action={dispatch}>
<div>
<label htmlFor="title">Title</label>
<input id="title" name="title" required />
{result?.errors?.title && <p>{result.errors.title[0]}</p>}
</div>
<div>
<label htmlFor="content">Content</label>
<textarea id="content" name="content" required rows={5} />
{result?.errors?.content && <p>{result.errors.content[0]}</p>}
</div>
{result && !result.success && <p style={{ color: 'red' }}>{result.message}</p>}
{result?.success && <p style={{ color: 'green' }}>{result.message}</p>}
<SubmitButton />
</form>
);
}
// ---- Server Action from non-form (onClick) ----
'use client';
import { deletePost } from './actions';
import { useTransition } from 'react';
function DeleteButton({ postId }: { postId: string }) {
const [isPending, startTransition] = useTransition();
return (
<button
onClick={() => startTransition(() => deletePost(postId))}
disabled={isPending}
>
{isPending ? 'Deleting...' : 'Delete'}
</button>
);
}Tip
Tip
Practice Server Actions Mutations in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Server Actions & Mutations
Practice Task
Note
Practice Task - (1) Write a working example of Server Actions Mutations from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Server Actions Mutations is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?