πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Server Actions: Forms and Mutations in Next.js

Next.js Data🟒 Free Lesson

Server Actions: Forms and Mutations in Next.js

For years, every form in a React app meant the same ceremony: write an API route, call it with fetch, manage pending state by hand, and revalidate data when the response lands. Server Actions collapse that into a function marked 'use server', called directly from a form's action prop or from a client event handler. The function always runs on the server β€” even when invoked from client code β€” and Next.js generates the network plumbing for you.

The feature is more than convenience. Because the submission is a normal form post under the hood, it works before JavaScript hydrates, carries anti-forgery protections, and integrates with the caching system through revalidatePath. This lesson covers authoring actions, validating input with structured errors, wiring pending and error UI with useActionState, and the patterns that keep mutations safe under concurrent submissions.

Prerequisites

  • !App Router pages and Server Components
  • !HTML forms: name attributes, FormData, and POST semantics
  • !Data fetching lesson covering revalidation

What You'll Learn

  • 1Define Server Actions in shared modules or colocated files
  • 2Validate FormData and return typed error state
  • 3Use useActionState for pending, error, and success UI
  • 4Revalidate cached routes after successful mutations

The smallest honest action

An action is an async function with the 'use server' directive at the top of the file. It receives the raw FormData object and returns whatever you want the client to see β€” a plain object works well. Calling it from a form needs no fetch, no JSON, and no manual method handling.

// app/newsletter/actions.js
'use server';

import { z } from 'zod';

const Subscribe = z.object({
  email: z.string().email('Enter a valid email address'),
});

export async function subscribe(prevState, formData) {
  const email = formData.get('email');

  const parsed = Subscribe.safeParse({ email });
  if (!parsed.success) {
    return { status: 'error', message: parsed.error.issues[0].message };
  }

  try {
    await db.subscriber.create({ data: { email: parsed.data.email } });
    return { status: 'success', message: 'Subscribed. Check your inbox.' };
  } catch (err) {
    if (err.code === 'P2002') {
      return { status: 'error', message: 'That email is already subscribed.' };
    }
    console.error('subscribe failed', err);
    return { status: 'error', message: 'Something went wrong. Try again.' };
  }
}
// app/newsletter/page.js β€” a Server Component form with client pending state
'use client';

import { useActionState } from 'react';
import { subscribe } from './actions';

export default function NewsletterForm() {
  const [state, formAction, pending] = useActionState(subscribe, null);

  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" required />
      <button type="submit" disabled={pending}>
        {pending ? 'Subscribing…' : 'Subscribe'}
      </button>
      {state?.message && (
        <p role="status" className={state.status === 'error' ? 'text-red-600' : 'text-green-600'}>
          {state.message}
        </p>
      )}
    </form>
  );
}

The signature prevState, formData is the useActionState contract: the previous return value on every re-invocation, so error messages survive re-renders. Return shapes stay plain JSON-serializable objects β€” no Dates, no class instances, no database rows with circular references.

Validation belongs on the server

Client-side required attributes improve feedback speed but are not a security boundary; anyone can submit a raw POST. The action is the boundary. Parse with a schema, collect field-level errors, and return them in a map so the form can highlight inputs individually.

// app/contact/actions.js
'use server';

import { z } from 'zod';

const Contact = z.object({
  name: z.string().min(2, 'Name is too short'),
  message: z.string().min(20, 'Message must be at least 20 characters'),
});

export async function sendMessage(prevState, formData) {
  const fields = {
    name: formData.get('name') ?? '',
    message: formData.get('message') ?? '',
  };

  const result = Contact.safeParse(fields);
  if (!result.success) {
    const fieldErrors = {};
    for (const issue of result.error.issues) {
      fieldErrors[issue.path[0]] = issue.message;
    }
    return { fieldErrors, values: fields };
  }

  await sendContactEmail(result.data);
  return { fieldErrors: {}, values: {}, success: true };
}

Returning values alongside errors lets you re-render the form with what the user already typed. Losing a long message because one field failed validation is the fastest way to lose a customer's trust.

Revalidate after the write

A successful mutation changes what cached pages should show. The action runs on the server, so it can call revalidatePath or revalidateTag directly β€” no separate API route needed to keep caches honest.

// app/posts/new/actions.js
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { auth } from '@/auth';
import { db } from '@/lib/db';

export async function createPost(prevState, formData) {
  const session = await auth();
  if (!session?.user) {
    redirect('/login');
  }

  const title = formData.get('title');
  const content = formData.get('content');

  if (!title || title.length < 3) {
    return { error: 'Title must be at least 3 characters' };
  }

  const post = await db.post.create({
    data: { title, content, authorId: session.user.id },
  });

  revalidatePath('/posts');
  redirect(`/posts/${post.id}`);
}

Order matters here. Call revalidatePath before redirect, and remember that a redirect throws internally β€” putting it before your final logic skips the lines after it, a bug that looks like "my revalidation never runs". Checking authentication inside the action, not only on the page that renders the form, keeps direct POSTs from bypassing your gate entirely.

Optimistic UI for responsive interfaces

Server Actions already feel fast because the request starts immediately, but visible state changes β€” a new item appearing in a list β€” can be optimistic. React's useOptimistic shows the expected state while the action is in flight and reconciles when the server responds. Combine it with useFormStatus inside a submit button component to show pending UI without prop drilling.

// components/submit-button.js
'use client';

import { useFormStatus } from 'react-dom';

export default function SubmitButton({ children }) {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} aria-busy={pending}>
      {pending ? 'Saving…' : children}
    </button>
  );
}

Because useFormStatus reads the nearest parent form's status, the button stays reusable across every form in the app without passing a pending prop from each page. Combining it with useActionState at the form level and useOptimistic for list updates gives the three pieces of responsive mutation UI β€” disabled affordance, error display, and immediate visual feedback β€” each owned by exactly one hook rather than a tangle of local booleans.

Security checklist for actions

Actions are endpoints. Treat them with the same discipline. Authenticate and authorize inside the action, not only in the page that renders the form. Validate every field with schemas. Rate-limit expensive actions such as password reset or file upload at the edge. Next.js includes origin tracing for same-origin checks on server actions, which blocks most cross-site form posts, but a determined attacker with a same-site scripting foothold bypasses origin checks β€” so keep validation and authorization close to the data. Logging each action invocation with the acting user id and a result code also turns support questions into a single query rather than a log dive.

Production pitfalls

The recurring bugs: returning non-serializable values from an action and watching the production build fail with an opaque serialization error; forgetting use server on a shared actions file so the function executes in the browser; calling redirect before writing data and silently losing the submission; and mutating without revalidation, leaving the list page stale until the next TTL. Also avoid putting secrets in returned state β€” anything an action returns is visible to the browser, including to anyone who inspects the network tab.

File uploads and non-standard bodies

FormData is not limited to text fields. A form with encType set to multipart form data can carry files, and the action reads them with the same formData.get call it uses for strings. Streaming uploads to object storage from inside an action works, but size limits apply β€” serverless platforms cap request bodies, so large files belong in a direct-to-storage upload with a short-lived signed URL, confirmed back to the server by a lightweight action that records the metadata. The pattern keeps your compute tier out of the byte-shuffling business while still letting the confirmation step run your validation and authorization logic.

// app/uploads/actions.js
'use server';

import { z } from 'zod';

const UploadedFile = z.object({
  name: z.string().min(1),
  size: z.number().positive().max(10 * 1024 * 1024),
});

export async function confirmUpload(prevState, formData) {
  const file = formData.get('file');
  if (!file || typeof file === 'string') {
    return { error: 'No file provided' };
  }

  const parsed = UploadedFile.safeParse({
    name: file.name,
    size: file.size,
  });
  if (!parsed.success) {
    return { error: 'File must be under 10 MB and have a name' };
  }

  const record = await db.upload.create({
    data: { name: parsed.data.name, size: parsed.data.size },
  });
  return { uploadId: record.id };
}

Concurrency, locking, and double submits

Two clicks of a fast submit button can produce two records even with a disabled button, because the first click's disabled state renders on the next frame at best. Server-side guards are the real protection. A unique constraint in the database turns a duplicate insert into a catchable error; an idempotency key returns the first result on replay; and for operations that read-then-write β€” reserving the last seat in a class, transferring a balance β€” a transaction with an appropriate isolation level prevents the lost update that optimistic guards miss. Treat the client's disabled state as courtesy and the server check as the contract. This mindset also clarifies what to do when a mutation fails halfway: return a field-level error the form can display, never leave the user staring at a silent no-op, and log enough context to reproduce the race if it recurs.

Common Mistakes

Validating only with HTML attributes on the inputs

Fix: Repeat every rule inside the action with a schema; the form attributes are a convenience, not a boundary.

Returning database entities directly from an action

Fix: Return plain, minimal objects; ORM entities often contain circular references or fields the client must never see.

Calling redirect before the final write

Fix: Perform the mutation and revalidation first; redirect throws and skips anything after it.

Forgetting revalidatePath after a create or delete

Fix: Purge the affected routes in the action so Server Components re-render with fresh data.

Best Practices

  • Keep action files colocated with their route and import them from both server and client callers
  • Standardize a return shape such as { status, fieldErrors, values } across the app
  • Extract reusable submit buttons that read useFormStatus instead of threading pending props
  • Log failures with request context inside the action so mutations are traceable

Interview Questions

Q1: Does a Server Action run on the client at any point?

No. Even when called from a client component, Next.js serializes the arguments and invokes the function on the server. The 'use server' file is never shipped as executable client logic.

Q2: How do Server Actions work without JavaScript?

Forms that only use the action prop compile to a progressive enhancement POST, so submission and navigation work before hydration; interactive state like pending indicators waits for the client bundle.

Q3: What is the role of useActionState?

It wires a form action to React state, giving you the previous action's return value, a wrapped action to pass to the form, and a pending flag for the duration of each invocation.

Key Takeaways

  • Server Actions replace hand-rolled API routes for mutations called from your own React tree.
  • Validate inside the action with a schema and return field-level errors plus the submitted values.
  • useActionState and useFormStatus provide pending and error UI with almost no boilerplate.
  • Revalidate paths or tags inside the action after writing, and redirect only at the very end.
  • Treat every action like a public endpoint: authenticate, authorize, rate-limit, and return minimal serializable data.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement