Next.js từ cơ bản đến nâng cao
Trang chủ / Module 7
⚙️ Module 7 / 18 · 5 ngày 📅 Tuần 5 ●●●○ Khó

Server Actions và mutation an toàn

Server Function/Server Action là gì, dùng với form và từ event handler, validate bằng Zod, trả lỗi theo field, pending và optimistic UI, revalidate sau khi sửa, và vì sao mỗi action là một endpoint công khai cần bảo vệ.

'use server'useActionStateZodSecurity
📌 Vì sao module này quan trọng

Server Actions thay thế phần lớn API nội bộ: viết một hàm, gọi từ form, xong. Sự tiện lợi đó che giấu một sự thật quan trọng: mỗi action là một endpoint POST ai cũng gọi được. Rất nhiều lỗ hổng trong ứng dụng Next.js đến từ action không kiểm tra quyền.

🎯 Mục tiêu học tập

  • Viết Server Action và gọi từ <form action> và từ event handler
  • Validate đầu vào bằng Zod, trả lỗi theo field qua useActionState
  • Hiển thị pending và optimistic UI
  • Làm mới cache và redirect sau mutation
  • Bảo vệ action: xác thực, phân quyền, giới hạn tần suất, idempotency

Action đầu tiên

// app/posts/actions.ts
'use server';
import { z } from 'zod';
import { redirect } from 'next/navigation';
import { updateTag } from 'next/cache';

const PostSchema = z.object({
  title: z.string().trim().min(3, 'Tiêu đề tối thiểu 3 ký tự').max(120),
  body: z.string().min(10, 'Nội dung quá ngắn'),
});

export type FormState = { errors?: Partial<Record<'title' | 'body' | 'form', string[]>>; values?: { title?: string; body?: string } };

export async function createPost(_prev: FormState, formData: FormData): Promise<FormState> {
  const session = await verifySession();                     // 1. xác thực
  if (!session) return { errors: { form: ['Bạn cần đăng nhập'] } };

  const raw = { title: formData.get('title'), body: formData.get('body') };
  const parsed = PostSchema.safeParse(raw);                  // 2. validate
  if (!parsed.success) return { errors: z.flattenError(parsed.error).fieldErrors, values: raw as FormState['values'] };

  const [post] = await db.insert(posts).values({ ...parsed.data, authorId: session.userId }).returning();
  updateTag('posts');                                        // 3. làm mới cache
  redirect(`/posts/${post.id}`);                             // 4. điều hướng (ném lỗi đặc biệt, đặt ngoài try/catch)
}
// app/posts/new/page.tsx -> NewPostForm (Client)
'use client';
import { useActionState } from 'react';
import { createPost } from '../actions';

export function NewPostForm() {
  const [state, action, pending] = useActionState(createPost, {});
  return (
    <form action={action}>
      <input name="title" defaultValue={state.values?.title} aria-invalid={!!state.errors?.title} />
      {state.errors?.title && <p role="alert">{state.errors.title[0]}</p>}
      <textarea name="body" defaultValue={state.values?.body} />
      {state.errors?.body && <p role="alert">{state.errors.body[0]}</p>}
      {state.errors?.form && <p role="alert">{state.errors.form[0]}</p>}
      <button disabled={pending}>{pending ? 'Đang lưu…' : 'Đăng bài'}</button>
    </form>
  );
}

Form dùng Server Action hoạt động cả khi JavaScript chưa tải xong (progressive enhancement) nếu form được render từ Server Component.

Gọi từ event handler và truyền tham số

'use client';
import { useTransition } from 'react';
import { toggleLike, deleteComment } from './actions';

export function LikeButton({ postId, liked }: { postId: string; liked: boolean }) {
  const [pending, startTransition] = useTransition();
  return (
    <button disabled={pending} onClick={() => startTransition(() => toggleLike(postId))}>
      {liked ? '♥' : '♡'}
    </button>
  );
}

// Gắn sẵn tham số bằng bind (giá trị được gửi kèm, client có thể thấy và SỬA được)
<form action={deleteComment.bind(null, comment.id)}><button>Xoá</button></form>

Action gọi tuần tự (một hàng đợi cho mỗi client) — không dùng action để fetch dữ liệu đọc; đọc dữ liệu thuộc về Server Component hoặc Route Handler/Query.

Mỗi action là một endpoint công khai

Next.js tạo cho mỗi action một ID và một endpoint POST. Ai biết ID (có trong bundle client) đều gọi được với bất kỳ tham số nào — kể cả tham số đã bind. Ẩn nút "Xoá" trên giao diện không bảo vệ gì.

'use server';
export async function deleteComment(commentId: string) {
  const session = await verifySession();
  if (!session) throw new Error('Unauthorized');

  const comment = await db.query.comments.findFirst({ where: eq(comments.id, commentId) });
  if (!comment) return;
  const canDelete = comment.authorId === session.userId || session.role === 'admin';   // kiểm tra quyền TRÊN TÀI NGUYÊN
  if (!canDelete) throw new Error('Forbidden');

  await db.delete(comments).where(eq(comments.id, commentId));
  updateTag(`post:${comment.postId}:comments`);
}
Biện phápGhi chú
Xác thực + phân quyền trong mỗi actionKhông dựa vào việc trang chứa form đã kiểm tra, cũng không dựa vào proxy
Validate mọi tham số bằng schemaTypeScript không tồn tại lúc chạy; client gửi gì cũng được
Chống IDORKiểm tra tài nguyên thuộc về người dùng, không chỉ "đã đăng nhập"
Rate limitUpstash Ratelimit/Redis theo userId hoặc IP cho action nhạy cảm (gửi OTP, đăng ký)
IdempotencyThanh toán/đặt hàng: idempotency key, ràng buộc unique trong DB
Giới hạn kích thướcserverActions.bodySizeLimit (mặc định 1MB); upload lớn dùng presigned URL
CSRFNext.js so Origin với Host; khai báo serverActions.allowedOrigins khi đứng sau proxy khác domain

Biến bị closure capture trong action định nghĩa inline được Next.js mã hoá khi gửi xuống client, nhưng đừng coi đó là chỗ để đặt secret. Các action không dùng tới được loại khỏi bundle (dead code elimination) và ID được tạo ngẫu nhiên mỗi build — đó là lớp phòng thủ phụ, không thay cho kiểm tra quyền.

Optimistic UI

'use client';
import { useOptimistic, startTransition } from 'react';

export function TodoList({ todos, toggle }: { todos: Todo[]; toggle: (id: string) => Promise<void> }) {
  const [optimistic, setOptimistic] = useOptimistic(todos, (state, id: string) =>
    state.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
  return optimistic.map(t => (
    <label key={t.id}>
      <input type="checkbox" checked={t.done}
        onChange={() => startTransition(async () => { setOptimistic(t.id); await toggle(t.id); })} />
      {t.title}
    </label>
  ));
}

Xử lý lỗi

  • Lỗi nghiệp vụ dự đoán được (validate, trùng email, hết hàng) → trả về trong state, hiển thị tại form.
  • Lỗi bất ngờ (DB chết) → throw; Error Boundary/error.tsx gần nhất hiển thị; message thật bị ẩn ở production, log ở server.
  • Đừng bọc redirect()/notFound() trong try/catch; nếu cần, dùng unstable_rethrow(error) trong catch.
  • Việc phụ sau khi xong (gửi email, log analytics) dùng after() để không làm người dùng chờ.

🚩 Sai lầm hay gặp

  • Action không kiểm tra quyền vì 'trang đã kiểm tra rồi'.
  • Tin tham số đã bind (client sửa được).
  • Dùng action để đọc dữ liệu (chạy tuần tự, không cache).
  • Quên làm mới cache sau khi sửa.

🏋️ Bài tập thực hành

CRUD bài viết an toàn

Tạo/sửa/xoá bài viết và bình luận bằng Server Actions, lỗi theo field, optimistic like. Viết test (Vitest) gọi trực tiếp action với: chưa đăng nhập, người khác xoá bình luận không phải của mình, dữ liệu sai schema — cả ba đều phải bị từ chối. Thêm rate limit 5 lần/phút cho action gửi bình luận.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Tôi viết được action có validate Zod và lỗi theo field
  • Tôi giải thích được vì sao action là endpoint công khai
  • Tôi kiểm tra quyền trên tài nguyên trong mọi action
  • Tôi làm được optimistic UI với action
  • Tôi phân biệt lỗi trả về và lỗi throw