Trung BìnhNext.js iconNext.js

Server Actions trong Next.js là gì?

Server Actions là async functions chạy trên server, được gọi từ Client Components hoặc forms.

  • Khai báo với 'use server' directive.
  • Cho phép mutate data trực tiếp mà không cần tạo API endpoint riêng.
tsx
// actions/post-actions.ts
'use server'
import { revalidatePath } from 'next/cache'

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string
  await db.posts.create({ title })
  revalidatePath('/posts') // làm mới cache trang sau khi mutate
}

// components/new-post-form.tsx
'use client'
import { createPost } from '@/actions/post-actions'

export function NewPostForm() {
  return (
    <form action={createPost}>
      <input name="title" placeholder="Post title" />
      <button type="submit">Create</button>
    </form>
  )
}

Xem toàn bộ Next.js cùng filter theo level & chủ đề con.

Mở danh sách Next.js