Back to roadmaps nextjs Course

Server Actions Basics

Historically, updating database records from a React frontend required setting up a API route, initiating a fetch request from a client event listener, managing loading states, and parsing the JSON response. Next.js Server Actions simplify this flow.


1. What are Server Actions?

Server Actions are asynchronous functions that run on the server. You can bind them directly to HTML form element action properties, or call them from standard buttons.

  • Security: Server Actions execute only on the server, allowing you to run SQL queries, modify database items, or perform authorization checks safely.
  • Progressive Enhancement: In many scenarios, forms can submit even if JavaScript is disabled in the browser.

2. Setting Up Server Actions

To declare a Server Action, add the "use server" directive at the top of the async function body, or place the directive at the top of a dedicated file:

// src/app/actions.ts
"use server";

import { revalidatePath } from "next/cache";

// A server action receives standard FormData
export async function createFeedback(formData: FormData) {
  const message = formData.get("message");
  const email = formData.get("email");

  if (!message || !email) {
    throw new Error("Missing required parameters");
  }

  // Perform secure database operations here
  console.log(`Saving feedback: ${message} from ${email}`);

  // Purge page cache to display new feedback records
  revalidatePath("/feedback");
}

3. Invoking Actions in Client Forms

Once declared, import and bind the action directly to the HTML form action property:

// src/app/feedback/page.tsx
import { createFeedback } from "../actions";

export default function FeedbackForm() {
  return (
    <div className="max-w-md mx-auto mt-8 p-6 border rounded">
      <h1 className="text-xl font-bold">Submit Feedback</h1>
      <form action={createFeedback} className="mt-4 space-y-4">
        <div>
          <label className="block text-sm">Email Address</label>
          <input name="email" type="email" required className="w-full border p-2 rounded" />
        </div>
        <div>
          <label className="block text-sm">Your Message</label>
          <textarea name="message" required className="w-full border p-2 rounded" />
        </div>
        <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded">
          Send Feedback
        </button>
      </form>
    </div>
  );
}

No API routes or client fetch logic are required. Next.js handles the network serialization under the hood automatically.

Published on Last updated: