1. Apa itu Next.js Server Actions ('use server')?
Server Actions adalah fungsi asynchronous yang didefinisikan dengan direktif `'use server'`. Fungsi ini dieksekusi **langsung di server**, dan dapat dipanggil langsung dari elemen `<form action={myAction}>` atau event handler di Client Component tanpa perlu membuat endpoint API terpisah.
example.js
javascript
| 1 | // app/actions/user.js |
| 2 | 'use server'; |
| 3 | import { sql } from '@/lib/db'; |
| 4 | import { revalidatePath } from 'next/cache'; |
| 5 | |
| 6 | export async function updateUsername(formData) { |
| 7 | const newName = formData.get('fullName'); |
| 8 | const userId = formData.get('userId'); |
| 9 | |
| 10 | // Mutasi database langsung di server |
| 11 | await sql`UPDATE users SET full_name = ${newName} WHERE id = ${userId}`; |
| 12 | |
| 13 | // Hapus cache halaman agar UI langsung ter-refresh dengan data terbaru |
| 14 | revalidatePath('/profile'); |
| 15 | return { success: true }; |
| 16 | } |
2. Menggunakan Server Action di Form Component
example.js
javascript
| 1 | import { updateUsername } from '@/app/actions/user'; |
| 2 | |
| 3 | export default function ProfileEditForm({ user }) { |
| 4 | return ( |
| 5 | <form action={updateUsername}> |
| 6 | <input type="hidden" name="userId" value={user.id} /> |
| 7 | <input type="text" name="fullName" defaultValue={user.fullName} required /> |
| 8 | <button type="submit">Simpan Perubahan</button> |
| 9 | </form> |
| 10 | ); |
| 11 | } |
Progressive Enhancement: Berfungsi Bahkan Tanpa JavaScript!
Karena menggunakan form action standar HTML, form Server Actions dapat bekerja bahkan ketika koneksi internet lambat atau saat JavaScript browser belum selesai di-download!