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.
RPC-Style Invocation:
Call server logic as if it were a local function from your client component.
Encapsulation of API Details:
The real API endpoints remain hidden from the client, increasing security.
Internal Use Only:
Server Actions are designed to work within your Next.js project and are not meant to be public REST endpoints.
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>
);
}
Secure Form Submissions:
Use Server Actions to process form data securely on the server without exposing external API URLs to the client.
Simplifying Server Logic:
They allow you to encapsulate server-side logic in a function-like call, which reduces the boilerplate code compared to traditional API routes.
Internal Workflows:
Best suited for interactions that remain within the Next.js ecosystem, rather than for creating public-facing APIs.
Hides API Details:
The actual API endpoints remain concealed from the client, enhancing security.
Simplified Code:
Invoking a server action is as simple as calling a function, making the codebase cleaner and easier to maintain.