-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-actions-in-next14.js
More file actions
91 lines (68 loc) · 2.26 KB
/
server-actions-in-next14.js
File metadata and controls
91 lines (68 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// File: server-actions-in-next14.js
/*
📘 Topic: Server Actions in Next.js 14+
Server Actions allow you to mutate data directly in server components or client forms,
without creating separate API routes or using external fetch logic.
🔧 Think of it like built-in API handlers tied directly to your UI.
*/
///////////////////////////
// ⚙️ 1. Enabling Server Actions
///////////////////////////
/*
✅ Works out of the box in Next.js 14+ (App Router only)
✅ Use `"use server"` directive inside a server component or file
✅ Can be passed to client components (like forms) as props
No need for: pages/api, fetch(), useEffect for submit, etc.
*/
'use server'
export async function addTodo(formData) {
const todo = formData.get('todo');
// simulate DB insert or backend call
console.log(`✅ Adding todo: ${todo}`);
// You could use Prisma, SQL, or another API call here
}
///////////////////////////
// 📄 2. Page that uses Server Action
///////////////////////////
/*
Use the server action as the form's `action` prop.
Next.js automatically handles the POST request and re-renders on submit.
*/
import { addTodo } from './server-actions-in-next14';
export default function TodoPage() {
return (
<div>
<h1>📝 Add a Todo (Next.js Server Action)</h1>
<form action={addTodo}>
<input type="text" name="todo" placeholder="Enter a task..." required />
<button type="submit">Add</button>
</form>
</div>
);
}
///////////////////////////
// 💡 3. Use Cases of Server Actions
///////////////////////////
/*
✅ Simple form submissions (e.g. auth, comments, todos)
✅ Reduce client JS bundle (less fetch/useEffect boilerplate)
✅ Automatic revalidation (optional)
✅ Great for team dashboards, admin panels, CRUD apps
You can also:
- Pass server actions to client components
- Trigger server logic without writing an API route
- Chain actions together (update → revalidate path)
*/
///////////////////////////
// ✅ Summary
///////////////////////////
/*
- Server Actions = "form-based" data mutations without APIs
- Great DX for fullstack React
- Removes fetch/post boilerplate
- Secure, fast, and clean
🎯 TL;DR:
- Write logic with `"use server"`
- Call it directly from a form or button
- Next.js handles the rest 🔥
*/