How to Fix Server Action Error in Next.js Quickly
"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.
"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>; }
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.
"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>; }
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.