0
0
NextJSframework~5 mins

Why server actions simplify mutations in NextJS

Choose your learning style9 modes available
Introduction

Server actions let you change data easily without extra setup. They keep your app simple and fast.

When you want to update a database after a user clicks a button.
When you need to send form data to the server and update the page.
When you want to avoid writing extra API routes for simple changes.
When you want to keep your code organized by handling mutations close to the UI.
When you want to reduce client-side code and rely on server logic.
Syntax
NextJS
export async function actionName(formData: FormData) {
  // handle mutation here
  // e.g., update database
  return redirect('/some-page')
}

export default function Page() {
  return (
    <form action={actionName} method="post">
      {/* form inputs */}
      <button type="submit">Submit</button>
    </form>
  )
}

Server actions are async functions exported from a component file.

They receive form data automatically when the form is submitted.

Examples
This example shows a server action that adds an item from a form input.
NextJS
export async function addItem(formData: FormData) {
  const item = formData.get('item')?.toString() || '';
  // save item to database
  return null;
}

export default function AddItem() {
  return (
    <form action={addItem} method="post">
      <input name="item" required />
      <button type="submit">Add</button>
    </form>
  )
}
This example shows a server action that deletes a user and redirects after.
NextJS
export async function deleteUser(formData: FormData) {
  const userId = formData.get('id')?.toString() || '';
  // delete user from database
  return redirect('/users');
}

export default function DeleteUser() {
  return (
    <form action={deleteUser} method="post">
      <input type="hidden" name="id" value="123" />
      <button type="submit">Delete User</button>
    </form>
  )
}
Sample Program

This component shows a form to send a message. When submitted, the server action addMessage runs, saving the message and redirecting to '/messages'. This keeps mutation logic on the server and the UI simple.

NextJS
import { redirect } from 'next/navigation';

export async function addMessage(formData: FormData) {
  const message = formData.get('message')?.toString() || '';
  // Imagine saving message to a database here
  console.log('Message saved:', message);
  return redirect('/messages');
}

export default function MessageForm() {
  return (
    <main>
      <h1>Send a Message</h1>
      <form action={addMessage} method="post">
        <label htmlFor="message">Message:</label>
        <textarea id="message" name="message" required rows={4} cols={30} />
        <button type="submit">Send</button>
      </form>
    </main>
  );
}
OutputSuccess
Important Notes

Server actions run only on the server, so they keep secrets safe.

You don't need extra API routes or client-side fetch calls for simple mutations.

Use redirect() to send users to another page after mutation.

Summary

Server actions let you handle data changes directly on the server.

They simplify your code by removing the need for separate API endpoints.

This makes your app easier to write and maintain.