What are Server Actions?
Server Actions let you handle form submissions directly on the server — no API endpoint needed, no client-side JavaScript required.
Basic Server Action
// app/contact/page.tsx
export default function ContactForm() {
async function submitForm(formData: FormData) {
"use server";
const name = formData.get("name") as string;
const message = formData.get("message") as string;
// Runs on the server — DB, email, etc.
await sendEmail({ name, message });
}
return (
<form action={submitForm}>
<input name="name" placeholder="Your name" required />
<textarea name="message" placeholder="Your message" required />
<button type="submit">Send</button>
</form>
);
}
useActionState for Status Management
"use client";
import { useActionState } from "react";
async function loginAction(prevState: any, formData: FormData) {
"use server";
const email = formData.get("email") as string;
const password = formData.get("password") as string;
if (password.length < 8) {
return { error: "Password must be at least 8 characters" };
}
// Login logic...
return { success: true };
}
export default function LoginForm() {
const [state, action, isPending] = useActionState(loginAction, null);
return (
<form action={action}>
{state?.error && <p className="text-red-500">{state.error}</p>}
{state?.success && <p className="text-green-500">Login successful!</p>}
<input name="email" type="email" required />
<input name="password" type="password" required />
<button disabled={isPending}>
{isPending ? "Logging in..." : "Log In"}
</button>
</form>
);
}
revalidatePath: Refreshing Cached Data
// app/actions.ts
"use server";
import { revalidatePath } from "next/cache";
export async function addProduct(formData: FormData) {
const name = formData.get("name") as string;
await saveToDatabase({ name });
revalidatePath("/products"); // Purge cache, trigger page refresh
}
Önemli Noktalar
- "use server" marks a Server Action
- Server Actions are passed to form action — no API endpoint needed
- useActionState manages form state (error/success/pending)
- revalidatePath purges cache and refreshes the page