What is Server Action in Next.js: Simple Explanation and Example
server action is a special function that runs only on the server to handle tasks like form submissions or data updates securely. It lets you write server-side logic directly inside your components without separate API routes.How It Works
Think of a server action like a helper who only works behind the scenes in a restaurant kitchen. When you order food (submit a form), the helper prepares it without the customer seeing the process. Similarly, server actions run on the server, hidden from the user’s browser, to handle tasks like saving data or sending emails.
This means you can write functions that do sensitive work safely, without exposing your code or secrets to the internet. Next.js automatically runs these functions on the server when triggered, so you don’t need to create separate API endpoints.
Example
This example shows a simple form that uses a server action to save a message. When the user submits the form, the server action runs on the server and logs the message.
import { experimental_useServerAction as useServerAction } from 'next/server'; export default function MessageForm() { const saveMessage = useServerAction(async (formData) => { const message = formData.get('message'); console.log('Message saved:', message); // Here you could save to a database }); return ( <form action={saveMessage}> <label htmlFor="message">Message:</label> <input id="message" name="message" type="text" required /> <button type="submit">Send</button> </form> ); }
When to Use
Use server actions when you want to handle form submissions, update data, or perform secure operations without exposing API routes. They are great for simple server-side tasks that happen after user interaction.
For example, saving user comments, processing payments, or sending confirmation emails can be done with server actions. This keeps your app secure and your code clean by avoiding extra API files.
Key Points
- Server actions run only on the server, hidden from the browser.
- They simplify handling form data and server tasks without separate API routes.
- Use them for secure, server-only logic triggered by user actions.
- They help keep your code organized and secure.