Server Actions deep dive: Form handling không cần API route
Phân tích chi tiết Server Actions trong React 19 và Next.js — từ cơ bản đến advanced patterns, thay thế hoàn toàn API routes cho form handling.
Server Actions là một trong những thay đổi lớn nhất trong cách chúng ta xử lý forms và mutations. Không cần tạo API route, không cần fetch từ client, không cần quản lý loading state thủ công. Hãy cùng deep dive.
Server Actions cơ bản
Một Server Action là async function chạy trên server, có thể gọi trực tiếp từ form hoặc event handler:
// actions/article.actions.ts
"use server";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
export async function createArticle(formData: FormData) {
const session = await auth();
if (session?.user?.role !== "ADMIN") {
throw new Error("Unauthorized");
}
const title = formData.get("title") as string;
const content = formData.get("content") as string;
const categoryId = formData.get("categoryId") as string;
const slug = title
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/(^-|-$)/g, "");
const article = await prisma.article.create({
data: {
title,
slug,
content,
categoryId,
authorId: session.user.id,
status: "DRAFT",
},
});
revalidatePath("/admin/articles");
redirect(`/admin/articles/${article.id}`);
}
Dùng trong form cực kỳ đơn giản:
// Trong Server Component — progressive enhancement
<form action={createArticle}>
<input name="title" required />
<textarea name="content" required />
<select name="categoryId">...</select>
<button type="submit">Tạo bài viết</button>
</form>
useActionState — Form state management
React 19 cung cấp useActionState để quản lý form state, validation errors, và pending state:
Hook này handle cả initial state, error state từ server, và pending indicator. Không cần useState + try/catch thủ công.
Advanced: Validation với Zod
Trong production, luôn validate input trên server. Kết hợp Zod với Server Actions:
Pattern này đảm bảo type safety end-to-end: Zod schema validate input, TypeScript enforce return type, và client nhận typed errors.
Khi nào KHÔNG dùng Server Actions
Real-time updates — WebSocket/SSE vẫn cần cho real-time. Server Actions là request/response model.
File streaming — Upload file lớn nên dùng dedicated upload endpoint với progress tracking.
Third-party webhooks — External services cần stable API endpoint, không phải Server Action.
Public API — Nếu bạn cần API cho mobile app hoặc third-party consumers, vẫn cần API routes.
Server Actions vs API Routes
Server Actions thắng khi: Form submissions, CRUD operations, mutations từ UI, progressive enhancement, type-safe client-server communication.
API Routes thắng khi: Public APIs, webhooks, streaming responses, non-form mutations (WebSocket fallback), third-party integrations.
Performance tips
revalidatePath vs revalidateTag — Dùng revalidateTag cho granular cache invalidation. revalidatePath invalidate toàn bộ route segment.
Parallel mutations — Nhiều Server Actions có thể chạy song song. Đừng await tuần tự khi không cần.
Optimistic updates — Kết hợp với useOptimistic cho instant UI feedback.
Kết luận
Server Actions đơn giản hoá đáng kể cách chúng ta handle forms và mutations. Với React 19 + Next.js, phần lớn API routes cho form handling có thể thay bằng Server Actions — ít code hơn, type-safe hơn, và progressive enhancement miễn phí.
Admin
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!