Server actions let your client components talk to the server easily. This helps you run secure code on the server while keeping your app fast and simple.
Server action in client components in NextJS
// actions.js 'use server'; export const myServerAction = async (data) => { // server-side logic here return result; }; // In client component 'use client'; import { myServerAction } from './actions'; function MyComponent() { async function handleClick() { const result = await myServerAction(someData); // use result } return <button onClick={handleClick}>Click me</button>; }
Server actions are async functions that run only on the server.
Client components can call server actions directly without fetch or API routes.
'use server'; export const addUser = async (user) => { // save user to database return { success: true }; };
'use client'; import { addUser } from './actions'; function Form() { async function onSubmit() { const response = await addUser({ name: 'Anna' }); console.log(response.success); // true } return <button onClick={onSubmit}>Add User</button>; }
This example shows a server action that creates a greeting message. The client component calls it when the button is clicked and shows the message in an alert.
// actions.js 'use server'; export const greetUser = async (name) => { return `Hello, ${name}!`; }; // Greeting.jsx 'use client'; import { greetUser } from './actions'; export default function Greeting() { async function sayHello() { const message = await greetUser('Friend'); alert(message); } return <button onClick={sayHello} aria-label="Greet user">Say Hello</button>; }
Server actions run only on the server, so they can safely access secrets like database credentials.
Use 'use client' at the top of your client components to enable client-side interactivity.
Server actions return promises, so always use async/await when calling them.
Server actions let client components run server code easily and securely.
They simplify data handling by removing the need for separate API routes.
Use async functions and 'use client' to connect client UI with server logic.