100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
JavaScript

Server Actions Explained

Learn how Server Actions let you write server-side mutations that are callable directly from forms and Client Components, with progressive enhancement, pending states, and security considerations.

Data FetchingIntermediate10 min readJul 10, 2026
Analogies

What Are Server Actions

A Server Action is an async function marked with the "use server" directive — either at the top of the function body or at the top of a whole file — that can be called directly from a Client or Server Component and executes exclusively on the server, letting you handle form submissions and mutations without manually building a Route Handler and a fetch call to reach it. Because Next.js compiles each Server Action into a secure, unguessable endpoint reference under the hood, the client only ever gets a reference to call it, never the function's actual source code.

🏏

Cricket analogy: Like a captain radioing instructions to the dressing room that only the team can act on, rather than shouting the tactical plan out loud for the opposition to overhear.

ts
// app/actions.ts
'use server';

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string;
  const body = formData.get('body') as string;

  await db.post.create({ data: { title, body } });
}

Invoking Server Actions from Forms and Progressive Enhancement

Passing a Server Action directly to a form's action prop — <form action={createPost}> — makes the form work even before JavaScript has hydrated, because Next.js can process the submission as a real HTML form POST if the client-side bundle hasn't loaded yet, then upgrade to a client-side submission once it has. Inside the action, the first parameter is automatically the submitted FormData object, from which you extract fields with formData.get('title') and can then write to your database directly.

🏏

Cricket analogy: Like a backup generator kicking in the instant floodlights fail mid-match so the game continues under some light, rather than the match being abandoned entirely without power.

Progressive enhancement means a <form action={serverAction}> submits correctly as a real HTML POST even if JavaScript fails to load, then upgrades to a smoother client-side submission once React has hydrated.

Managing Pending and Error States with useActionState

The useActionState hook wraps a Server Action so a component can read its returned state — such as a validation error object — and a pending boolean across the submission lifecycle, while the companion useFormStatus hook lets a nested submit button read pending without prop drilling, so you can disable it and show a spinner exactly while the action is in flight. This pairing is what makes it possible to build a fully accessible, progressively-enhanced form that still shows rich loading and error UI once JavaScript is running, without reinventing state management for every single form.

🏏

Cricket analogy: Like a third umpire's review light turning amber the instant a decision is under review, then flashing red or green once judgment is reached, so everyone in the stadium can see the exact status.

tsx
'use client';
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
import { createPost } from './actions';

function SubmitButton() {
  const { pending } = useFormStatus();
  return <button disabled={pending}>{pending ? 'Posting…' : 'Post'}</button>;
}

export function NewPostForm() {
  const [state, formAction] = useActionState(createPost, { error: null });
  return (
    <form action={formAction}>
      <input name="title" required />
      <textarea name="body" required />
      {state.error && <p role="alert">{state.error}</p>}
      <SubmitButton />
    </form>
  );
}

Security Considerations and Revalidating After Mutations

Because a Server Action's endpoint is technically a public, callable URL under the hood, Next.js does not treat "use server" alone as an authorization check — you must still explicitly verify the current user's session and permissions inside the action itself before performing any mutation, exactly as you would inside a Route Handler. After a successful write, calling revalidatePath or revalidateTag inside the same action is the standard way to ensure the page reflects the change immediately, since a Server Action's return value alone does not automatically refresh any cached data on the page.

🏏

Cricket analogy: Like a stadium's VIP gate still requiring a guard to check your credentials individually, even though the gate itself already looks official and unlocked to anyone walking past.

Never assume a Server Action is protected just because it isn't linked from a visible UI element. Its compiled endpoint can still be called directly, so always re-verify the session and authorization inside the action itself.

  • A Server Action is an async function marked with 'use server' that runs exclusively on the server.
  • Passing a Server Action to a form's action prop enables progressive enhancement, working even before JavaScript hydrates.
  • Inside a form-bound action, the first argument is the submitted FormData object.
  • useActionState exposes a Server Action's returned state and pending status to a component.
  • useFormStatus lets a nested submit button read pending state without prop drilling.
  • Server Actions must independently verify session and authorization — 'use server' is not an auth check.
  • Call revalidatePath or revalidateTag inside the action after a successful mutation to refresh cached UI.

Practice what you learned

Was this page helpful?

Topics covered

#JavaScript#NextJsStudyNotes#WebDevelopment#ServerActionsExplained#Server#Actions#Explained#Invoking#StudyNotes#SkillVeris