ရိုးရိုးလေး ရှင်းပြမယ်
Server Action ကို ရိုးရိုးလေး ပြောရရင်
Server Action ဆိုတာ server ရဲ့ တံခါးပေါ်က စာထည့်ပေါက်လေး တစ်ခုလိုပါပဲ။ Form က စာအိတ်ကို ထည့်လိုက်ပြီး server က ဖွင့်ဖတ်ပါတယ်။ Endpoint ဖန်တီးတာ၊ fetch ရေးတာ စတဲ့ ပေါက်ဖောက်တဲ့ အလုပ်ကို Next.js က လုပ်ပေးပါတယ်၊ ဒါကြောင့် သင်က form ရဲ့ action prop ထဲ function ကို ထည့်ရုံပါပဲ။
ဒါပေမဲ့ ဘယ်သူမဆို ဘယ်စာအိတ်ကိုမဆို အဲဒီ ပေါက်ထဲ ထိုးထည့်နိုင်ပါတယ်။ ဒါကြောင့် server က စာအိတ်ပေါ်က label ကို မယုံဘဲ စာကို ဖတ်ပြီး ပို့သူကို စစ်ရပါတယ်။
Problem → Why → Solution
ပြဿနာ: browser ကို ယုံလိုက်တဲ့ action
Developer တစ်ယောက်က title input မှာ required minLength={3} ထည့်ပြီး Delete button ကို note ပိုင်ရှင်ကိုပဲ ပြထားလို့ လုံခြုံပြီလို့ ထင်ပါတယ်။ ဒါပေမဲ့ devtools နဲ့ attribute တွေကို ဖျက်လို့ ရပါတယ်၊ Server Action ကလည်း browser က POST request နဲ့ ခေါ်တဲ့ public endpoint တစ်ခုပါ။ Login ဝင်ထားတဲ့ member တစ်ယောက်က တခြားသူရဲ့ note id ကို ထည့်ပြီး action ကို ခေါ်လိုက်ရင် အောက်က code က ဘာမှ မစစ်ဘဲ ဖျက်ပစ်ပါတယ်။
"use server";
export async function deleteNote(formData: FormData) {
const id = formData.get("id") as string; // whatever the browser sent
await db.note.delete({ where: { id } }); // no login check, no owner check
revalidatePath("/notes");
}Function လို ရေးရပေမဲ့ endpoint လို ကာကွယ်ရတယ်
Server Action ကို import လုပ်ပြီး ခေါ်တဲ့အတွက် ရိုးရိုး function လို ခံစားရပါတယ်။ တကယ်တော့ argument တွေက network ကနေ ရောက်လာပြီး TypeScript type တွေက runtime မှာ ဘာမှ မစစ်ပါဘူး။ Browser validation က user အတွက် အဆင်ပြေစေဖို့ပဲ ဖြစ်ပြီး လုံခြုံရေးက action ထဲမှာပဲ ရှိပါတယ်။
Core concept: public endpoint တစ်ခုလို ရေးရတဲ့ function
Server Action က "use server" directive ပါတဲ့ async function ပါ။ File ရဲ့ ထိပ်ဆုံးမှာ ရေးရင် export လုပ်ထားတဲ့ function အားလုံး Server Action ဖြစ်ပြီး Server Component ထဲက function body ထဲမှာ ရေးလည်း ရပါတယ်။ <form action={fn}> ထဲ ထည့်လိုက်ရင် React က form data ကို POST နဲ့ server ဆီ ပို့ပါတယ်။ Server Component ထဲက form ဖြစ်ရင် JavaScript မရောက်သေးခင်ကတည်းက submit လုပ်လို့ ရပါတယ် (progressive enhancement)။
အရေးကြီးဆုံးကတော့ action ကို public HTTP endpoint လို ဆက်ဆံဖို့ပါ။ FormData ထဲက value တွေက string, File ဒါမှမဟုတ် null ဖြစ်ပြီး client က ဘာမဆို ပို့နိုင်ပါတယ်။ Data ကို ပြောင်းတဲ့ action တိုင်းက ဒီ အစီအစဉ်အတိုင်း သွားသင့်ပါတယ်: (1) session ကနေ user ကို authenticate လုပ်၊ (2) schema နဲ့ field တွေကို parse လုပ်၊ (3) ဒီ user က ဒီ record ကို ပြောင်းခွင့်ရှိလား authorize လုပ်၊ (4) data layer နဲ့ save လုပ်၊ (5) cache ကို revalidate လုပ်၊ (6) state ပြန်ပေး ဒါမှမဟုတ် redirect လုပ်ပါ။
Client Component ထဲမှာ useActionState(action, initialState) က [state, formAction, isPending] ကို ပြန်ပေးပါတယ်။ ဒီလို သုံးတဲ့အခါ action က (prevState, formData) ဆိုတဲ့ argument နှစ်ခုကို လက်ခံပါတယ်။ စာလုံးတိုလွန်းတာ လို မျှော်လင့်ထားတဲ့ error တွေကို state value အဖြစ် ပြန်ပေးပြီး form ဘေးမှာ ပြပါ၊ database ကျသွားတာ လို မမျှော်လင့်တဲ့ error တွေကတော့ throw လုပ်ပြီး error boundary က ကိုင်တွယ်ပါစေ။
Next.js က ပေးတဲ့ အကာအကွယ်နဲ့ မပေးတဲ့ အကာအကွယ်
Server Action တွေကို POST နဲ့ပဲ ခေါ်လို့ ရပြီး Next.js က Origin header ကို Host header နဲ့ နှိုင်းယှဉ်လို့ အခြား site ကနေ ခေါ်တာကို ကာကွယ်ပါတယ်။ Body size ကိုလည်း default 1 MB နဲ့ ကန့်သတ်ပါတယ် (serverActions.bodySizeLimit)။ ဒါတွေက ခေါ်သူ ဘယ်သူလဲ၊ ခွင့်ရှိလားဆိုတာကို မစစ်ပေးပါဘူး၊ အဲဒါက သင့်အလုပ်ပါ။
- Form က FormData ကို action ဆီ ပို့
- ဘယ်သူလဲ? session ကို စစ်
- Field တွေကို schema နဲ့ parse
- ဒီ record ကို ပြောင်းခွင့်ရှိလား?
- Save, revalidate, state ပြန်ပေး
UI မှာ button ဖျောက်ထားတာ ဒါမှမဟုတ် required ထည့်ထားတာက ဒီ အဆင့်တစ်ခုခုကို အစားမထိုးနိုင်ပါဘူး။
အထွေထွေ ပုံစံ
"use server";
export async function actionName(prev: State, formData: FormData): Promise<State> {
const user = await requireUser(); // 1. authenticate
const parsed = Schema.safeParse(Object.fromEntries(formData)); // 2. validate
if (!parsed.success) return { error: firstMessage(parsed.error) };
if (!(await canChange(user, parsed.data))) return { error: "Not allowed" }; // 3.
await saveThing(parsed.data); // 4. mutate
revalidatePath("/things"); // 5. refresh caches
return { ok: true }; // 6. report back
}Authenticate, validate, authorize, mutate, revalidate, report ဆိုတဲ့ အစီအစဉ်က action တိုင်းမှာ တူပါတယ်၊ ပြောင်းတာက schema နဲ့ permission rule ပဲ ဖြစ်ပါတယ်။
Worked example: login ဝင်ထားသူအတွက် note ဖန်တီးခြင်း
Input ကို validate လုပ်ရုံနဲ့ မလုံလောက်ပါဘူး။ Server Action က public endpoint ဖြစ်လို့ ခေါ်သူ ဘယ်သူလဲဆိုတာကိုလည်း စစ်ရပါမယ်။ ဒီ action က session ကို အရင်စစ်ပြီး zod နဲ့ validate လုပ်ကာ ownerId ကို form ကနေ မဟုတ်ဘဲ session ကနေ ယူပါတယ်။ Next.js version အားလုံးမှာ အလုပ်လုပ်တဲ့ revalidatePath ကို သုံးထားပြီး (updateTag က Next.js 16 မှာပဲ ရှိပါတယ်) form ကတော့ useActionState နဲ့ error နဲ့ pending state ကို ပြပါတယ်။
// app/notes/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { getCurrentUser } from "@/lib/auth";
import { createNote } from "@/lib/data/notes";
export type FormState = { error?: string; ok?: boolean };
const NoteInput = z.object({
title: z.string().trim().min(3, "Enter a title with at least 3 characters").max(120),
});
export async function createNoteAction(
_prev: FormState,
formData: FormData,
): Promise<FormState> {
const user = await getCurrentUser();
if (!user) return { error: "Please sign in first" };
const parsed = NoteInput.safeParse({ title: formData.get("title") ?? "" });
if (!parsed.success) return { error: parsed.error.issues[0].message };
await createNote({ title: parsed.data.title, ownerId: user.id });
revalidatePath("/notes");
return { ok: true };
}
// app/notes/new/note-form.tsx
"use client";
import { useActionState } from "react";
import { createNoteAction } from "../actions";
export function NoteForm() {
const [state, formAction, pending] = useActionState(createNoteAction, {});
return (
<form action={formAction}>
<label htmlFor="title">Title</label>
<input id="title" name="title" required minLength={3} />
<button type="submit" disabled={pending}>
{pending ? "Saving..." : "Save"}
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.ok && <p>Saved.</p>}
</form>
);
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Authenticate first
if (!user) return { error: "Please sign in first" };Form ကို ဘယ်သူ submit လုပ်လုပ် session မရှိရင် ဘာမှ မလုပ်ခင် ရပ်ပါတယ်။
- Validate on the server
const parsed = NoteInput.safeParse({ title: formData.get("title") ?? "" });formData.get() က null ဖြစ်နိုင်လို့ string အလွတ် ပြောင်းပြီး schema က trim, အနည်းဆုံး 3 စာလုံး, အများဆုံး 120 စာလုံးကို စစ်ပါတယ်။ Browser ရဲ့ minLength ကို ကျော်လာတဲ့ request တွေကိုလည်း ဒီမှာ ဖမ်းပါတယ်။
- Owner from the session
await createNote({ title: parsed.data.title, ownerId: user.id });ownerId ကို hidden input ကနေ မယူပါဘူး၊ ဒါမှ တခြားသူ့ နာမည်နဲ့ note ဖန်တီးလို့ မရမှာပါ။
- Refresh the list
revalidatePath("/notes");Save ပြီးမှ /notes cache ကို ဟောင်းပြီလို့ မှတ်လို့ list က note အသစ်ကို ပြပါတယ်။
- State and pending in the form
const [state, formAction, pending] = useActionState(createNoteAction, {});state က action ပြန်ပေးတဲ့ နောက်ဆုံး object ဖြစ်ပြီး pending က submit လုပ်နေစဉ် true ဖြစ်လို့ button ကို disable လုပ်ကာ နှစ်ခါ submit မဖြစ်အောင် ကာကွယ်ပါတယ်။
"Hi" ကို submit လုပ်ရင် form အောက်မှာ "Enter a title with at least 3 characters" ပေါ်ပါတယ်။ Login မဝင်ထားသူက "Please sign in first" ကို မြင်ပါတယ်။ မှန်ကန်တဲ့ title ကိုတော့ login ဝင်ထားသူကို owner အဖြစ် save လုပ်ပြီး Saved. ပေါ်ကာ /notes list မှာ note အသစ် ပါလာပါတယ်။redirect, try/catch နဲ့ argument ပိုပေးခြင်း
redirect() က special error တစ်ခု throw လုပ်ပြီး အလုပ်လုပ်ပါတယ်။ ဒါကြောင့် try/catch အတွင်းမှာ ခေါ်ရင် catch က ဖမ်းသွားပြီး redirect မဖြစ်တော့ပါဘူး။ Save ကို try ထဲမှာ ထားပြီး revalidate နဲ့ redirect ကို try/catch အပြင်ဘက် နောက်ဆုံးမှာ ခေါ်ပါ။ Note id လို argument ပိုပေးဖို့ action.bind(null, id) ကို သုံးနိုင်ပေမဲ့ အဲဒီ id ကလည်း client ကနေ ပြန်ရောက်လာတာမို့ authorization ကို ဆက်စစ်ရပါတယ်။
export async function publishNote(noteId: string) {
const user = await requireUser();
try {
await markPublished({ noteId, userId: user.id }); // checks ownership inside
} catch {
return { error: "Could not publish. Please try again." };
}
revalidatePath("/notes");
redirect(`/notes/${noteId}`); // outside try/catch: redirect works by throwing
}
// in a Server Component: <form action={publishNote.bind(null, note.id)}>လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
သင့် UI ထဲက form အများစုအတွက် Server Action က API endpoint ကို ကိုယ်တိုင် ရေးတာထက် code နည်းပါတယ်။ ဒါပေမဲ့ action တွေကို production မှာ လုံခြုံအောင် team တွေက ပုံစံ တူတူ တစ်ခုကို လိုက်နာကြပါတယ်။
- Settings page: profile ကို update လုပ်တဲ့ action က user id ကို session ကနေ ယူတဲ့အတွက် form ထဲမှာ id field မပါပါဘူး။
- Admin publish button: editor role ကို action ထဲမှာ စစ်ပြီး publish ပြီးရင် blog list tag ကို revalidate လုပ်ပါတယ်။
- Comment form: zod နဲ့ စာလုံးအရေအတွက်ကို စစ်ပြီး user တစ်ယောက်ကို တစ်မိနစ် ဘယ်နှခါ post လုပ်ခွင့်ရှိလဲ rate limit ထားပါတယ်။
- requireUser, requireRole လို helper တွေကို lib/auth.ts မှာ တစ်ခါ ရေးပြီး action တိုင်းရဲ့ ပထမ line မှာ ခေါ်ပါတယ်။
အမှားများ
Server Action နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ
Browser validation ရှိလို့ server validation မလိုဘူး ထင်ခြင်း
required, minLength, type="email" တွေကို devtools နဲ့ ဖျက်လို့ရပြီး script တစ်ခုက FormData ကို တိုက်ရိုက် ပို့နိုင်ပါတယ်။ HTML validation ကို UX အတွက်ပဲ ထားပြီး schema validation ကို action ထဲမှာ အမြဲ လုပ်ပါ။
Update/delete action ထဲမှာ authorization မစစ်ခြင်း
Page က login ကို စစ်ပြီးသား ဖြစ်ပေမဲ့ action ကို သီးခြား ခေါ်လို့ ရပါတယ်။ Action တိုင်းက session ကို ပြန်ဖတ်ပြီး record ရဲ့ owner ဒါမှမဟုတ် role ကို ကိုယ်တိုင် စစ်ရပါမယ်။
ownerId, role, price ကို FormData ကနေ ယူခြင်း
Hidden input ဆိုတာလည်း user input ပါပဲ။ ဒီလို တန်ဖိုးတွေကို session ဒါမှမဟုတ် database ကနေ server ပေါ်မှာ ယူပါ။
redirect ကို try/catch ထဲမှာ ခေါ်ခြင်း
catch က redirect error ကို ဖမ်းသွားလို့ user က page မှာပဲ ကျန်ပြီး error message ကို မြင်ရပါတယ်။ redirect ကို try/catch အပြင်မှာ ခေါ်ပါ။
Best Practices
Best practices
- Action တွေကို actions.ts လို "use server" file သီးသန့်ထဲမှာ ထားပါ၊ ဒါမှ Client Component တွေက import လုပ်ရ လွယ်ပြီး server code နဲ့ ရောမနေပါဘူး။
- Schema တစ်ခုကို form နဲ့ action နှစ်ခုလုံးက မျှသုံးပါ၊ ဒါပေမဲ့ server ဘက်က parse ကိုပဲ အမှန်တကယ် ယုံပါ။
- Action က ပြန်ပေးတဲ့ state ကို { ok, message } ဒါမှမဟုတ် field error တွေလို shape တစ်မျိုးတည်း ထားပါ။
- Database error message ဒါမှမဟုတ် stack trace ကို state ထဲ ထည့်မပေးပါနဲ့၊ server log မှာ မှတ်ပြီး user ကို ယေဘုယျ message ပဲ ပြပါ။
- Action တစ်ခုစီအတွက် လုံခြုံရေး test တစ်ခု ရေးပါ: login မဝင်ထားသူ၊ owner မဟုတ်သူနဲ့ ခေါ်ရင် ငြင်းရမယ်။
Mini challenge
Mini challenge: လုံခြုံတဲ့ updateNoteAction
Next.js မလိုဘဲ run လို့ရအောင် session နဲ့ database အတုကို သုံးပြီး updateNoteAction(prevState, formData) ကို ရေးပါ။ Action က authenticate, validate, လိုအပ်ရင် not found, authorize, save ဆိုတဲ့ အစီအစဉ်အတိုင်း သွားရပါမယ်။
- Session မရှိရင် { ok: false, message: "Sign in first" }
- id, title (3-80), body (10-2000) ကို zod နဲ့ trim ပြီး validate လုပ်ကာ ပထမ error message ကို ပြန်ပေး
- Note မရှိရင် "Note not found"၊ owner လည်းမဟုတ် editor လည်းမဟုတ်ရင် "Not allowed"
- အောင်မြင်ရင် save ပြီး { ok: true, message: "Saved" } ပြန်ပေး
- User အမျိုးမျိုးနဲ့ ခေါ်ပြီး ရလဒ်တိုင်းကို print ထုတ်ပါ
import { z } from "zod";
type User = { id: string; role: "member" | "editor" };
type Note = { id: string; ownerId: string; title: string; body: string };
type State = { ok: boolean; message: string };
// Fake session and database so the action runs outside Next.js.
let session: { user: User } | null = null;
const notes = new Map<string, Note>(/* TODO: one note owned by "u1" */);
const UpdateInput = z.object({
// TODO: id, title (3-80) and body (10-2000), all trimmed, with messages
});
async function updateNoteAction(_prev: State, formData: FormData): Promise<State> {
// TODO 1: authenticate
// TODO 2: validate Object.fromEntries(formData)
// TODO 3: not found
// TODO 4: authorize (owner or editor)
// TODO 5: save and report
}
// TODO: build FormData objects and call the action as different usersရလဒ်: Login မဝင်ထားသူက Sign in first၊ title တိုလွန်းရင် Title must be 3-80 characters၊ owner နဲ့ editor က Saved၊ တခြား member က Not allowed၊ မရှိတဲ့ id က Note not found ရပြီး နောက်ဆုံး title က Polished by editor ဖြစ်ပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
new FormData() ကို Node 22 မှာ global အနေနဲ့ သုံးလို့ရပါတယ်။ Validation fail ဖြစ်ရင် parsed.error.issues[0].message က schema ထဲမှာ ရေးထားတဲ့ message ကို ပေးပါတယ်။ session variable ကို ခေါ်ချိန်တိုင်း ပြောင်းပြီး user မတူတာကို simulate လုပ်ပါ။
အဖြေ ကြည့်ရန်
import { z } from "zod";
type User = { id: string; role: "member" | "editor" };
type Note = { id: string; ownerId: string; title: string; body: string };
type State = { ok: boolean; message: string };
let session: { user: User } | null = null;
const notes = new Map<string, Note>([
["n1", { id: "n1", ownerId: "u1", title: "Draft", body: "First version of the note" }],
]);
const TITLE = "Title must be 3-80 characters";
const BODY = "Body must be 10-2000 characters";
const UpdateInput = z.object({
id: z.string().trim().min(1, "Missing note id"),
title: z.string().trim().min(3, TITLE).max(80, TITLE),
body: z.string().trim().min(10, BODY).max(2000, BODY),
});
async function updateNoteAction(_prev: State, formData: FormData): Promise<State> {
const user = session?.user;
if (!user) return { ok: false, message: "Sign in first" };
const parsed = UpdateInput.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { ok: false, message: parsed.error.issues[0].message };
const note = notes.get(parsed.data.id);
if (!note) return { ok: false, message: "Note not found" };
if (note.ownerId !== user.id && user.role !== "editor") {
return { ok: false, message: "Not allowed" };
}
notes.set(note.id, { ...note, title: parsed.data.title, body: parsed.data.body });
return { ok: true, message: "Saved" };
}
function form(id: string, title: string, body = "A long enough body text") {
const data = new FormData();
data.set("id", id);
data.set("title", title);
data.set("body", body);
return data;
}
const initial: State = { ok: false, message: "" };
const owner: User = { id: "u1", role: "member" };
const other: User = { id: "u2", role: "member" };
const editor: User = { id: "u3", role: "editor" };
const cases: [string, User | null, FormData][] = [
["signed out", null, form("n1", "New title")],
["owner, short title", owner, form("n1", "Hi")],
["owner, valid", owner, form("n1", " Owner edit ")],
["other member", other, form("n1", "Hijacked title")],
["editor, valid", editor, form("n1", "Polished by editor")],
["missing note", owner, form("n404", "Valid title")],
];
async function main() {
for (const [label, user, data] of cases) {
session = user ? { user } : null;
const state = await updateNoteAction(initial, data);
console.log(`${label.padEnd(19)} -> ${state.ok} ${state.message}`);
}
console.log("final title:", notes.get("n1")?.title);
}
main();Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Server Action က "use server" ပါတဲ့ async function ဖြစ်ပြီး browser က POST နဲ့ ခေါ်တဲ့ public endpoint လို ဆက်ဆံရပါတယ်။
- Action တိုင်းမှာ authenticate, validate, authorize, save, revalidate, report ဆိုတဲ့ အစီအစဉ်ကို လိုက်ပါ။
- ownerId လို တန်ဖိုးတွေကို FormData ကနေ မယူဘဲ session ကနေ ယူပါ။
- useActionState က error state နဲ့ pending ကို ပေးပြီး redirect ကို try/catch အပြင်မှာ ခေါ်ရပါတယ်။
Next.js — Mutating Data — Next.js
Next.js — Mutating Data — Next.js