Overview

Server Actions allow you to define server-side logic that can be invoked directly from client code—much like calling a function—without manually writing a fetch to an API route. This approach hides the underlying API details from the client and simplifies your front-end code.

Core Concepts

Example

Server Action Function

Define your server-side logic in a separate module.

// app/actions.ts
export async function submitForm(data: { name: string }) {
  // Process or store data on the server
  const res = await fetch("<https://api.example.com/submit>", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  return res.json();
}

Client-side Usage

Call the server action directly from your Client Component, such as in a form submission handler.

"use client";

import { useState } from "react";
import { submitForm } from "../actions";

export default function FormPage() {
  const [name, setName] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const result = await submitForm({ name });
    console.log(result);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter Name"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

When to Use

Notes