0
0
NextJSframework~5 mins

Server action database mutations in NextJS

Choose your learning style9 modes available
Introduction

Server action database mutations let you change data on the server safely and easily. They help keep your app data updated without extra setup.

When you want to add new data to your database from a form.
When you need to update existing data after user input.
When you want to delete data securely from the server.
When you want to keep your UI and database in sync automatically.
When you want to avoid writing separate API routes for simple data changes.
Syntax
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.

Examples
This server action adds a new user with the name from a form.
NextJS
'use server'

export async function addUser(formData: FormData) {
  const name = formData.get('name')?.toString() || ''
  await db.user.create({ data: { name } })
}
This server action deletes a post by its ID.
NextJS
'use server'

export async function deletePost(postId: string) {
  await db.post.delete({ where: { id: postId } })
}
Sample Program

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.

NextJS
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>
  )
}
OutputSuccess
Important Notes

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.

Summary

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.