0
0
NextJSframework~5 mins

Server action in client components in NextJS

Choose your learning style9 modes available
Introduction

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.

When you want to save form data to a database from a button click.
When you need to fetch or update data securely without exposing secrets to the browser.
When you want to run backend logic like sending emails triggered by user actions.
When you want to keep your client code clean and move heavy work to the server.
When you want to avoid writing separate API routes for simple server tasks.
Syntax
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.

Examples
This server action saves a user and returns success.
NextJS
'use server';

export const addUser = async (user) => {
  // save user to database
  return { success: true };
};
Client component calls the server action on button click.
NextJS
'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>;
}
Sample Program

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.

NextJS
// 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>;
}
OutputSuccess
Important Notes

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.

Summary

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.