</>
⌕
Mid #server-actions#security#revalidatePath#forms

Server Actions hoạt động thế nào và cần lưu ý gì về bảo mật?

⚡ Trả lời nhanh

Server Action là hàm async 'use server' mà Next biến thành endpoint POST công khai. Phải coi như API public: validate input (zod), kiểm tra authn/authz trong chính action, không tin dữ liệu client. Sau khi mutate gọi revalidatePath/revalidateTag để làm mới cache.

// app/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";

const Schema = z.object({ title: z.string().min(1).max(100) });

export async function createPost(formData: FormData) {
  const session = await getSession();
  if (!session) throw new Error("Unauthorized");
  const data = Schema.parse({ title: formData.get("title") });
  await db.post.create({ data: { ...data, authorId: session.userId } });
  revalidatePath("/posts");
}
<form action={createPost}><input name="title" /><button>Tạo</button></form>
  • Gọi được từ form (hoạt động cả khi chưa hydrate: progressive enhancement) hoặc từ Client Component.
  • Chỉ dùng POST; Next so sánh header Origin với Host để chống CSRF, có thể cấu hình serverActions.allowedOrigins.
  • Biến closure được mã hóa khi gửi xuống client, nhưng đừng dựa vào đó để giữ secret.
  • Mọi hàm export từ file 'use server' đều là endpoint public, kể cả khi không dùng trong UI.
🃏 Ôn bằng flashcard