nextjsreactserver-actions
Next.js Server Actions Guide
Learn how to use Server Actions in Next.js 14
Learn how to use Server Actions in Next.js 14
Server Actions are a powerful feature in Next.js 14 that allows you to run server-side code directly from your components. Let's explore how to use them effectively!
Here's a simple example of a Server Action:
"use server";
async function addTodo(formData: FormData) {
const todo = formData.get("todo");
await db.todos.create({ data: { text: todo } });
}
You can use Server Actions in your client components:
"use client";
export default function TodoForm() {
return (
<form action={addTodo}>
<input name="todo" type="text" required />
<button type="submit">Add Todo</button>
</form>
);
}
Here's how to handle loading states:
"use client";
import { useFormStatus } from "react-dom";
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Adding..." : "Add Todo"}
</button>
);
}
Proper error handling is crucial:
"use server";
import { revalidatePath } from "next/cache";
async function addTodo(formData: FormData) {
try {
const todo = formData.get("todo");
await db.todos.create({ data: { text: todo } });
revalidatePath("/todos");
} catch (error) {
throw new Error("Failed to create todo");
}
}
'use server'
directive at the top of files containing Server ActionsServer Actions make it easy to build interactive applications while keeping sensitive operations on the server. They're perfect for forms, data mutations, and any operation that needs server-side processing.