Instruction file imported from AhmadBahlwan/Hotel-Management-system (
.github/instructions/nymor-server-actions-mutations.instructions.md). Copyright stays with the author.
Rule
When implementing mutations (POST, PUT, DELETE, PATCH operations) in Next.js applications, use Server Actions instead of API routes. Server Actions provide better type safety, reduced client-server boilerplate, and improved developer experience.
Why
Server Actions offer several advantages over API routes for mutations:
- Type Safety: Server Actions maintain end-to-end type safety from client to server
- Less Boilerplate: No need to manually define fetch calls, handle responses, or manage loading states
- Better Performance: Server Actions can be called directly without HTTP overhead
- Improved DX: Automatic form handling, progressive enhancement, and built-in error handling
- Security: Built-in CSRF protection and validation
Example
Instead of:
// app/api/users/route.ts
export async function POST(request: Request) {
const data = await request.json();
// ... mutation logic
return Response.json({ success: true });
}
// components/UserForm.tsx
const handleSubmit = async (data: FormData) => {
const res = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify(data),
});
const result = await res.json();
};
Use:
// app/actions.ts
'use server'
export async function createUser(data: FormData) {
// ... mutation logic
return { success: true };
}
// components/UserForm.tsx
<form action={createUser}>
{/* form fields */}
</form>