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

Next.js Server Actions: Mutations Without API Routes

Next.js Data🟒 Free Lesson

Next.js Server Actions: Mutations Without API Routes

Server Actions blur the line between a function and an endpoint. You mark a function with 'use server', call it from a form or a client component, and Next.js compiles it into an RPC endpoint that accepts a POST with a signed action ID β€” no hand-written route handler, no client fetch boilerplate, no manual serialization. The form works even before JavaScript loads, because the action is attached to the form's action attribute and the browser submits it as a regular POST.

The feature is deceptively deep. Actions interact with caching through revalidation, compose with useActionState for pending and error states, pair with useOptimistic for instant feedback, and raise new questions about authorization that classic API routes answered differently. This lesson covers the full working set.

Prerequisites

  • !Comfort with React Server Components
  • !Experience with forms and event handlers
  • !Familiarity with revalidatePath from the caching lessons

What You'll Learn

  • 1Define and call Server Actions from forms and client components
  • 2Handle validation errors with useActionState without losing input
  • 3Add optimistic updates with useOptimistic
  • 4Authorize every action at the function boundary

Anatomy of an action

An action begins with the use server directive at the top of the file, or inside a single function in a file of Server Components. Everything exported from such a file becomes a callable endpoint, so keep the surface minimal and put shared helpers in a separate module.

javascript
// app/blog/actions.js
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';
import { prisma } from '@/lib/db';
import { getSession } from '@/lib/session';

const PostSchema = z.object({
  title: z.string().min(3).max(120),
  body: z.string().min(20),
});

export async function createPost(prevState, formData) {
  const session = await getSession();
  if (!session) {
    return { error: 'You must be signed in to publish.' };
  }

  const parsed = PostSchema.safeParse({
    title: formData.get('title'),
    body: formData.get('body'),
  });

  if (!parsed.success) {
    return {
      error: parsed.error.issues[0].message,
      fields: { title: formData.get('title'), body: formData.get('body') },
    };
  }

  const post = await prisma.post.create({
    data: {
      title: parsed.data.title,
      body: parsed.data.body,
      authorId: session.userId,
    },
  });

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

Two conventions make this production-ready. First, the action returns a plain object on recoverable failure β€” the form stays mounted with its values and the message renders inline. Second, redirect is called only after the write succeeds; redirect works by throwing internally, so placing it in an error path would mask the real error.

Wiring the form with useActionState

useActionState (the successor to useFormState) gives the component access to the previous return value, a pending flag, and the bound action. The form needs no onSubmit handler at all.

// app/blog/new-post-form.js
'use client';

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

export function NewPostForm() {
  const [state, formAction, pending] = useActionState(createPost, null);

  return (
    <form action={formAction}>
      <label htmlFor="title">Title</label>
      <input
        id="title"
        name="title"
        defaultValue={state?.fields?.title ?? ''}
        required
      />

      <label htmlFor="body">Body</label>
      <textarea
        id="body"
        name="body"
        rows={8}
        defaultValue={state?.fields?.body ?? ''}
        required
      />

      {state?.error && (
        <p role="alert" className="error">
          {state.error}
        </p>
      )}

      <button type="submit" disabled={pending}>
        {pending ? 'Publishing…' : 'Publish'}
      </button>
    </form>
  );
}

Re-populating defaultValue from the returned fields is the detail teams forget; without it a failed submit wipes the author's draft from the screen even though the server already told them what was wrong.

Optimistic updates for instant feedback

Waiting for a round trip before showing a new row feels sluggish on fast networks and broken on slow ones. useOptimistic lets the UI display a speculative state that React reverts automatically if the action fails.

// app/todos/todo-list.js
'use client';

import { useOptimistic, useState, useTransition } from 'react';
import { addTodo } from '../actions';

export function TodoList({ todos }) {
  const [optimisticTodos, addOptimistic] = useOptimistic(
    todos,
    (state, title) => [...state, { id: 'temp', title, pending: true }]
  );
  const [error, setError] = useState(null);
  const [, startTransition] = useTransition();

  async function handleSubmit(formData) {
    const title = formData.get('title');
    setError(null);
    addOptimistic(title);
    startTransition(async () => {
      const result = await addTodo(formData);
      if (result?.error) {
        setError(result.error);
      }
    });
  }

  return (
    <section>
      <form action={handleSubmit}>
        <input name="title" placeholder="New todo" required />
        <button type="submit">Add</button>
      </form>
      {error && <p role="alert">{error}</p>}
      <ul>
        {optimisticTodos.map((todo) => (
          <li key={todo.id} style={{ opacity: todo.pending ? 0.6 : 1 }}>
            {todo.title}
          </li>
        ))}
      </ul>
    </section>
  );
}

React discards the optimistic layer once the action's revalidation brings back the real list. If the action returns an error, the speculative row vanishes and your error message explains why β€” no manual rollback bookkeeping.

Calling actions outside forms

Any client component can import an action and call it in an event handler. This is the right shape for a delete button, a star toggle, or any interaction that is not a form submission. The compiled endpoint still requires a POST and still benefits from the same authorization checks.

// app/admin/user-row.js
'use client';

import { useTransition } from 'react';
import { toggleAdmin } from '../actions';

export function UserRow({ user }) {
  const [pending, startTransition] = useTransition();

  return (
    <tr>
      <td>{user.email}</td>
      <td>
        <button
          type="button"
          disabled={pending}
          onClick={() => startTransition(() => toggleAdmin(user.id))}
        >
          {pending ? 'Saving…' : user.isAdmin ? 'Revoke admin' : 'Grant admin'}
        </button>
      </td>
    </tr>
  );
}

startTransition keeps the previous UI interactive while the mutation runs, which is exactly the behavior you want for rapid toggles.

Testing actions and verifying progressive enhancement

Server actions are ordinary async functions, which makes the validation and authorization logic testable without a browser. Call the exported function directly in a unit test with a constructed FormData or a plain object, mock the session helper, and assert on the returned state object. The parts that need a real browser are narrower than teams expect: form submission without JavaScript, the pending flag during a slow action, and the optimistic row appearing before the network resolves. A single end-to-end test per critical form covers those; the rest belongs at the unit level where failures are cheaper to diagnose.

Progressive enhancement deserves its own verification pass. Disable JavaScript in the browser and submit the login and signup forms. They should post a real request, receive a redirect or an error page, and behave like a classic server-rendered app. If the form dead-loads, the action was not bound correctly β€” usually an action passed as a normal event handler instead of the form's action attribute, or a client component wrapper that prevents the native submit. This check takes five minutes and catches the class of regression that makes the app unusable for anyone on a flaky connection whose bundle has not arrived yet.

One structural note for testability: keep the schema and the session lookup behind small modules rather than inlining them in every action file. Tests then stub two imports instead of reimplementing auth, and the same modules are reused by route handlers that need identical rules, which prevents the slow divergence where the API enforces a stricter password policy than the Server Action.

Revalidation, redirects, and cache interaction

An action that writes to the database must tell every cache layer the old bytes are wrong. revalidateTag purges Data Cache entries by tag; revalidatePath purges the Full Route Cache for a route pattern; router.refresh() from a client component re-runs the Server Components on the current page. A typical create-or-update action uses revalidatePath for both the list and the detail pattern, then redirects when the user should navigate away.

javascript
// Inside an update action
await prisma.post.update({ where: { id }, data: patch });
revalidateTag(`post-${id}`);
revalidatePath('/blog');
revalidatePath('/blog/[slug]', 'page');

Order matters slightly: purge before redirecting so the destination renders with fresh data rather than a just-stale entry. There is a second ordering concern inside complex actions. If an action writes to the database, calls an external service, and then writes again, wrap the database portions in a transaction so a failure in the middle does not leave half an order behind. revalidatePath should be the last server-side step, after every fallible operation has succeeded β€” purging first and then failing means the next visitor pays for a cache rebuild that still shows the old state, and your logs will blame the cache for a bug that lives in the transaction.

Authorization and abuse resistance

Because actions compile to endpoints, every exported action is an attack surface. Verify the session inside the action even if the calling UI already hid the button. Validate every field with a schema; never trust that a hidden input stayed hidden. Check object-level authorization β€” a user may be allowed to edit posts, but only their own. And rate-limit sensitive actions at the middleware or platform layer, since an action endpoint accepts POSTs from anywhere, not just your UI.

ConcernForm-only patternClient-invoked pattern
Entry pointform action attributeImported function in event handler
Pending stateuseActionState pending flaguseTransition or pending boolean
Error feedbackReturned state objectReturned object or thrown error
Progressive enhancementWorks without JavaScriptRequires JavaScript
Typical useCreate, edit, loginDelete, toggle, reorder

Common Mistakes

Exporting helper functions from a 'use server' file

Fix: Only export intended actions; every export becomes a public endpoint. Keep helpers in a separate module.

Skipping session checks because the button was hidden in the UI

Fix: Authorize inside every action; the endpoint is reachable with a crafted POST regardless of what the UI shows.

Calling redirect inside a catch block

Fix: redirect throws internally; call it only on the success path so real errors surface instead of being swallowed.

Forgetting to revalidate after a write

Fix: Purge tags and paths in the action so the Full Route Cache and Data Cache reflect the change immediately.

Best Practices

  • Return plain objects for recoverable errors and reserve redirects for success
  • Validate with a schema shared between client hints and server truth
  • Use useOptimistic for lists and toggles where a reverted row is acceptable
  • Keep the exported action surface in each file as small as the feature allows

Interview Questions

Q1: How do Server Actions work without JavaScript on the page?

The action is compiled to an endpoint and bound to the form's action attribute; the browser submits a normal POST and Next.js hydrates the result when the bundle loads.

Q2: Where must authorization live?

Inside the action itself. The UI may hide controls, but the compiled endpoint accepts direct POSTs, so the function must verify the session and object-level permissions.

Q3: useActionState vs useOptimistic β€” when does each belong?

useActionState manages the async result of a form action including pending and error state; useOptimistic paints a speculative UI that React reverts when the real state arrives.

Key Takeaways

  • Server Actions are compiled endpoints; every export is callable by any client.
  • useActionState wires pending flags and error objects into forms without manual fetch code.
  • useOptimistic gives instant feedback and reverts automatically on failure.
  • revalidateTag and revalidatePath inside the action keep caches honest after writes.
  • Session checks, schema validation, and object-level authorization belong in the action body.
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