Next.js
Exploring Server Actions in Next.js 14
• 6 min read
Exploring Server Actions in Next.js 14
Server Actions are an alpha feature in Next.js 13.4 that are now stable in Next.js 14. They build on React Actions to allow you to define functions that run on the server, which can be called directly from your components.
Why Server Actions?
Traditionally, you would need to create an API route to handle form submissions or data mutations.
// Old way: pages/api/submit.ts
export default async function handler(req, res) {
const data = req.body;
await saveToDb(data);
res.status(200).json({ success: true });
}
With Server Actions, you can colocate your server logic with your UI.
// New way: component.tsx
export default function Form() {
async function submit(formData: FormData) {
"use server";
const name = formData.get("name");
await saveToDb({ name });
}
return <form action={submit}>...</form>;
}
This simplifies the mental model and reduces the amount of boilerplate code needed.