Skip to content
codmaker

Next.js Server Actions: A Practical Guide

What Next.js Server Actions are, how to use them with forms, how to validate and secure them, and when an API route is still the better choice for the job.

CodmakerUpdated 10 min read
Share

What are Server Actions in Next.js?

Server Actions are async functions that run on the server but can be called from your components, including Client Components. You mark them with the 'use server' directive, either at the top of a file or at the top of the function body. Then you pass them to a form or call them like any other async function.

They let you handle mutations without writing API routes. Creating a post, updating a profile, deleting a record: each can be one function that lives next to the UI that uses it.

In React's own docs, the broader feature is called Server Functions. When one is passed to a form action or called inside a transition, it's referred to as a Server Action. Next.js docs and most developers still say Server Actions, so that's what this guide uses.

How Server Actions work: closures over the network

Server Actions feel like calling a function on the backend from the frontend. Because they are. Next.js creates a hidden endpoint for each action, but to you as the developer it's just an async function import. Under the hood the client sends a POST request with the arguments, the server runs the function, and the result comes back serialized.

This co-location of data logic and UI is powerful. You stop maintaining a separate layer of fetch calls, request types and route files for every small mutation. The function signature is the contract.

It's still a network call, though, and that shapes how you write them. Arguments and return values must be serializable, so pass plain data, not class instances or functions. Each call has latency. And because there's an endpoint behind the function, anyone who can reach your app can call it with any input they want. Keep that last point in mind, it's the most important one in this guide.

How to use Server Actions with forms

The simplest use is a form. Write an async function that takes FormData, mark it with 'use server', and pass it as the form's action prop: form action={createPost}. When the form submits, the function runs on the server with the submitted fields.

After the mutation, refresh the data on screen. Call revalidatePath or revalidateTag so cached pages and data show the change, or call redirect to send the user to the new record. Both come from Next.js and work inside actions.

For pending and error states in Client Components, React gives you hooks built for this. useActionState wraps an action and gives you its last returned state plus a pending flag, which is how you show validation errors next to fields. useFormStatus, used in a child component of the form, tells a submit button whether the form is submitting so it can disable itself. For instant feedback on things like likes or todo toggles, useOptimistic shows the expected result before the server confirms it.

Progressive enhancement: forms that work without JavaScript

Used with form action={save} in a Server Component, Server Actions work even before JavaScript has loaded, or with JavaScript disabled. The browser submits the form the old-fashioned way, the server runs the action, and the user gets a response.

This takes us back to the web's roots: HTML forms that just work. Then, when JavaScript loads, you get the extras on top: client-side validation, pending states, optimistic updates and no full page reload. Users on a slow connection can submit before your bundle finishes downloading.

You keep this benefit only if you design for it. Pass the action directly to the form, keep required data in form fields or hidden inputs, and don't make the form depend on client-only state to submit.

How to secure Server Actions

Treat every Server Action like a public API endpoint, because that's what it is. Hiding a button in the UI doesn't stop someone from calling the action directly. Next.js adds some protection, like comparing the request origin to the host and making action IDs hard to guess, but none of that replaces your own checks.

Every action that touches data should do these things inside the function itself:

  • Check authentication: read the session and reject the call if there's no user
  • Check authorization: confirm this user is allowed to change this specific record
  • Validate input with a schema library such as Zod instead of trusting FormData or arguments
  • Return safe error messages and keep stack traces and internal details on the server
  • Rate limit sensitive actions like sign-up, login and anything that sends email

Server Actions vs API routes: when to use which

Server Actions are built for mutations triggered from your own UI. That's where they shine: forms, buttons, settings pages, admin tools.

They're not a general replacement for route handlers. Use a route handler when something outside your Next.js app needs to call you: webhooks from Stripe or GitHub, a React Native app, a public API, or an n8n workflow posting data in. Those clients need a stable URL and an explicit contract, and an action's generated endpoint isn't meant for that.

Avoid Server Actions for reading data, too. Fetch data in Server Components instead. Actions use POST, aren't cached like normal data fetching, and calls from the client are processed one after another, so using them as a query layer makes your app slower and harder to cache.

Common Server Actions mistakes

Most problems with Server Actions come from forgetting that they cross a network boundary. Watch for these:

  • Skipping auth checks because the button is only visible to admins
  • Passing non-serializable values like class instances or arbitrary functions
  • Forgetting revalidatePath or revalidateTag, so the UI shows stale data after a successful save
  • Calling redirect inside a try/catch block, which catches the redirect signal Next.js uses internally
  • Uploading large files through an action and hitting the default body size limit, which you can raise in next.config
  • Using actions to fetch data instead of loading it in Server Components

Frequently Asked Questions

Are Server Actions secure?

They are as secure as the code inside them. Each action is reachable through a POST request, so you must check authentication, authorization and input inside every action. Next.js adds origin checks and hard-to-guess action IDs, but those don't replace your own validation.

Can I use Server Actions in Client Components?

Yes. Define the action in a separate file with 'use server' at the top, then import it into the Client Component. You can pass it to a form, call it from an event handler, or wrap it with useActionState.

Should I use Server Actions or API routes?

Use Server Actions for mutations triggered from your own Next.js UI. Use route handlers for webhooks, mobile apps, third-party integrations and any client that needs a stable public URL.

Can Server Actions be used to fetch data?

They can, but they shouldn't be your default. Fetch data in Server Components. Actions use POST, aren't cached like regular data fetching, and client calls run one at a time.

Do Server Actions work without JavaScript?

Yes, when you pass the action to a form's action prop from a Server Component. The form submits as plain HTML before JavaScript loads, then gains pending states and client-side validation once it does.

Written by Codmaker

An independent product lab. We build and run our own React Native and Next.js apps, and write up what we learn along the way.

See our apps
All guides →
React8 min read

React Compiler: Do You Still Need useMemo?

What the React Compiler does, how to turn it on in Next.js, when useMemo and useCallback still matter, and the mistakes that stop it from optimizing your code.