Topic 26 of 39
Server Actions
Overview
Server Actions are async functions that run on the server but can be called directly from Client Components or forms. They eliminate the need to write separate API endpoints (Route Handlers) for simple data mutations, significantly speeding up development.
Syntax
typescript
// actions.ts (Separate file for Server Actions)
'use server';
import db from '@/lib/db';
import { revalidatePath } from 'next/cache';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
// Direct database mutation!
await db.post.create({ data: { title } });
// Tell Next.js to clear the cache for this route
revalidatePath('/posts');
}Common Pitfalls
- Forgetting to validate input. Server Actions are public API endpoints under the hood, so malicious users can send unexpected data.
- Not adding the
'use server'directive, which causes the function to run on the client and leak sensitive DB logic.
Interview Questions
Q:
How do Server Actions improve security and DX?
A:
They provide a seamless RPC (Remote Procedure Call) experience between client and server with full type safety. They also automatically handle CSRF protection, which traditional API routes require manual configuration for.
Real-World Example
Liking a post directly from a client component button.
example
typescript
// ClientComponent.tsx
'use client';
import { likePost } from './actions';
export default function LikeButton({ postId }) {
return (
<button onClick={() => likePost(postId)}>
❤️ Like
</button>
);
}Check Your Knowledge
Test your understanding of Server Actions with these quick questions.