0
0
NextjsDebug / FixBeginner · 4 min read

How to Fix Server Action Error in Next.js Quickly

Server action errors in Next.js usually happen because the server action function is not marked with "use server" directive or is used incorrectly in client components. To fix it, add "use server" at the top of your server action file and call it properly from server or client components using recommended patterns.
🔍

Why This Happens

Next.js server actions must be explicitly marked to run on the server. If you forget to add "use server" at the top of your server action function file, Next.js treats it as a client function, causing errors. Also, calling server actions incorrectly from client components without proper setup leads to runtime errors.

javascript
"use client";

export async function addItem() {
  // This is intended as a server action but missing "use server"
  console.log('Adding item');
  return 'Item added';
}

export default function Page() {
  return <button onClick={() => addItem()}>Add</button>;
}
Output
Error: Server actions must be marked with "use server" directive or cannot be called directly from client components.
🔧

The Fix

Add "use server" at the top of your server action file to mark it as a server function. Then, call the server action properly from your client component using the recommended pattern, such as passing the action as a prop or using form actions.

javascript
"use server";

export async function addItem() {
  console.log('Adding item');
  return 'Item added';
}

// Client component
"use client";
import { addItem } from './actions';

export default function Page() {
  async function handleClick() {
    const result = await addItem();
    alert(result);
  }

  return <button onClick={handleClick}>Add</button>;
}
Output
When clicking the button, an alert shows: "Item added"
🛡️

Prevention

Always start your server action files with "use server" to clearly mark them. Use Next.js recommended patterns to call server actions from client components, such as passing actions as props or using form actions. Enable linting rules that warn if server actions are misused. Test server actions separately to ensure they run only on the server.

⚠️

Related Errors

  • "Server actions cannot be called directly from client components": Fix by using form actions or passing server actions as props.
  • "Missing 'use server' directive": Add "use server" at the top of server action files.
  • "Cannot use hooks inside server actions": Avoid React hooks in server actions; they run only on the server.

Key Takeaways

Always add "use server" at the top of server action files in Next.js.
Call server actions properly from client components using recommended patterns.
Enable linting to catch misuse of server actions early.
Test server actions independently to ensure they run only on the server.
Avoid using React hooks inside server actions.