0
0
NextjsHow-ToBeginner · 4 min read

How to Create Server Action in Next.js: Simple Guide

In Next.js, create a server action by defining an async function inside a server component or a dedicated server file and export it. Use the "use server" directive to mark the function as a server action, then call it from client components or forms to run backend logic securely.
📐

Syntax

To create a server action in Next.js, define an async function with the "use server" directive at the top. Export this function so it can be imported or used in your components. This function runs only on the server and can handle tasks like database updates or API calls.

  • async function actionName(params): Your server action function.
  • "use server": Directive to mark the function as a server action.
  • export: Makes the function available to other parts of your app.
javascript
"use server";

export async function addData(data) {
  // Server-side logic here
  console.log('Data received:', data);
  return { success: true };
}
💻

Example

This example shows a simple server action that receives form data and logs it on the server. The client component calls this action on form submission.

javascript
/* app/actions.js */
"use server";

export async function submitForm(formData) {
  // Simulate saving data on server
  console.log('Form data:', formData);
  return { message: 'Form submitted successfully' };
}


/* app/page.jsx */
'use client';
import { useState } from 'react';
import { submitForm } from './actions';

export default function Page() {
  const [message, setMessage] = useState('');

  async function handleSubmit(event) {
    event.preventDefault();
    const formData = {
      name: event.target.name.value,
      email: event.target.email.value
    };
    const result = await submitForm(formData);
    setMessage(result.message);
  }

  return (
    <main>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Name:</label>
        <input id="name" name="name" required />

        <label htmlFor="email">Email:</label>
        <input id="email" name="email" type="email" required />

        <button type="submit">Submit</button>
      </form>
      {message && <p>{message}</p>}
    </main>
  );
}
Output
Form submitted successfully
⚠️

Common Pitfalls

Common mistakes when creating server actions in Next.js include:

  • Not using the "use server" directive, so the function runs on the client instead of the server.
  • Trying to call server actions directly from client components without async/await or proper imports.
  • Mixing server actions with client-only hooks or state, which causes errors.
  • Forgetting to export the server action function.

Always keep server actions pure and avoid client-side code inside them.

javascript
// Wrong: Missing 'use server' directive
export async function wrongAction() {
  console.log('This will run on client, which is wrong');
}

// Right: With 'use server' directive
"use server";
export async function rightAction() {
  console.log('Runs only on server');
}
📊

Quick Reference

ConceptDescription
"use server" directiveMarks a function as a server action to run only on the server.
Async functionServer actions must be async to handle async tasks like DB calls.
Export functionExport server actions to use them in components or forms.
Call from clientUse async/await to call server actions from client components.
No client hooksAvoid React client hooks inside server actions.

Key Takeaways

Add the "use server" directive to mark functions as server actions in Next.js.
Server actions run only on the server and handle backend logic securely.
Always export server actions to use them in client components or forms.
Call server actions asynchronously from client components using async/await.
Avoid mixing client-side code or hooks inside server actions.