Server action database mutations let you change data on the server safely and easily. They help keep your app data updated without extra setup.
Server action database mutations in NextJS
'use server' export async function actionName(formData: FormData) { // perform database mutation here await db.model.create({ data: { /* your data here */ } }) // optionally return data or redirect }
Use the 'use server' directive at the top of the function to mark it as a server action.
The function receives form data or parameters and performs database changes directly.
'use server' export async function addUser(formData: FormData) { const name = formData.get('name')?.toString() || '' await db.user.create({ data: { name } }) }
'use server' export async function deletePost(postId: string) { await db.post.delete({ where: { id: postId } }) }
This example shows a simple todo form. When submitted, it calls the addTodo server action to add a new todo item to the database. The form uses semantic HTML and accessibility labels.
import { db } from '@/lib/db' 'use server' export async function addTodo(formData: FormData) { const title = formData.get('title')?.toString() || '' if (title.trim() === '') return await db.todo.create({ data: { title } }) } export default function TodoForm() { return ( <form action={addTodo}> <label htmlFor="title">New Todo:</label> <input id="title" name="title" type="text" required aria-label="Todo title" /> <button type="submit">Add</button> </form> ) }
Server actions run only on the server, so they keep your database credentials safe.
Use FormData to get form inputs easily inside the action.
Server actions simplify data mutations without needing separate API routes.
Server action database mutations let you change data on the server directly.
They use the 'use server' directive and receive form data or parameters.
This approach keeps your app secure and your code simple.