Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 3

Server Actions, Revalidation and Hydration Pitfalls

Mutate data with a Server Action that re-checks the session and validates FormData, revalidate the routes that show the data, and diagnose the hydration mismatches a page can still produce.

Contentsand lesson path

What you will learn

  • Mutate data with Server Actions or Route Handlers that validate input on the server and revalidate affected routes, and diagnose hydration mismatches.

Prerequisites: Next.js App Router & Routing

01. The brief

The dashboard's note form must save a note and show the new list without a full client-side data layer. A Server Action does this with one async function: the form posts to it, it runs on the server with the session cookie attached, and the fresh UI comes back in its response. The same powers that make actions convenient make them dangerous when trusted: an action is a public endpoint that any HTTP client can call, and its inputs arrive as raw form values. This lesson walks through the action from the lab, then looks at the class of bugs that appears after every server-rendered page ships: hydration mismatches.

02. Step 1: The action checks, validates, saves, revalidates

The 'use server' directive marks functions that the browser may invoke but the server executes. Four duties follow. Re-check the session: the action runs in its own request, so whatever the page checked when it rendered says nothing about this call. Validate the input: FormData values arrive as strings (or Files) no matter what the form's TypeScript or HTML attributes promised; client-side validation is user experience, never protection — the deeper treatment of form validation is in Constraints and perceivable errors. Do the work next to the data. Revalidate the cached output that shows it, or readers keep seeing the old list.

TSX · app/dashboard/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { addNote } from '../../lib/data';
import { getSession } from '../../lib/session';

export type NoteState =
  | { status: 'idle' }
  | { status: 'saved' }
  | { status: 'error'; message: string };

export async function saveNote(
  _prev: NoteState,
  formData: FormData,
): Promise<NoteState> { // without it, status widens to string
  const session = await getSession(); // its own request, its own check
  if (!session) {
    return { status: 'error', message: 'Sign in before saving a note.' };
  }
  const title = formData.get('title'); // string | File | null
  if (typeof title !== 'string' || title.trim().length === 0
      || title.length > 100) {
    return {
      status: 'error',
      message: 'Give the note a title of 1 to 100 characters.',
    };
  }
  addNote(session.user, title.trim());
  revalidatePath('/dashboard');
  return { status: 'saved' };
}

The form in the Client Component (lesson 2) binds this action with useActionState, which hands it the previous state and the FormData, and exposes a pending flag for the submit button. Because the action returns state instead of throwing, the form can show a friendly message for the unauthenticated and invalid cases — and because Next renders forms that call Server Actions as real <form> elements, the flow also works with JavaScript disabled.

03. Step 2: Prove it without JavaScript

Next renders the form with hidden fields that name the action ($ACTION_REF_1, $ACTION_1:0, $ACTION_1:1 and $ACTION_KEY), so a plain HTML post reaches the same function. Their values are build-specific, so a test has to read them from the rendered <form> first. The lab lesson of this skill prints a short script, post-note.mjs, that does exactly that: it fetches the page, copies every hidden field, adds the title and posts the form as a browser without JavaScript would, then prints the status code and the message from the re-rendered page. With the lab app running on port 3100 and amara signed in (lab step 4):

Terminal — the form flow without any client JavaScript
export COOKIE="session=$(awk '$6 == "session" { print $7 }' amara.txt)"
node post-note.mjs "Order more lentils"

# then read the page again and look for the new note:
curl -s -b amara.txt http://localhost:3100/dashboard \
  | grep -o "<li>Order more lentils</li>"
Expected output
200 Note saved.
<li>Order more lentils</li>

The note the action saved is in the freshly rendered list, because revalidatePath('/dashboard') told Next to re-render that route's cached output. The two failure paths behave just as usefully. Posting an empty title re-renders the page with the message in the status paragraph. Posting without a session cookie (the script's optional second argument replaces the cookie, here with an empty one) renders the signed-out branch, and the action's own session check refuses to save anything:

Terminal — an empty title, then no session cookie
node post-note.mjs ""
node post-note.mjs "No session" ""
Expected output
200 Give the note a title of 1 to 100 characters.
200 Please sign in to view your portfolio.

One server-side message per failure, no client script involved. A detail from the server log while testing this way: Next warns "Missing origin header from a forwarded Server Actions request". Next compares the host in the Origin header of every Server Action request with the app's own host (from x-forwarded-host or host) and rejects the action on a mismatch: that is the built-in CSRF protection, and it needs no configuration. A request with no Origin at all, like the one Node's fetch sends from the script, is let through with that warning; browsers send Origin on form posts. The serverActions.allowedOrigins option (under experimental in the Next config) only adds extra trusted hosts, for example when a proxy serves the app on another domain and does not forward it in x-forwarded-host. Every entry loosens the check, so keep the list as short as possible.

04. Step 3: Hydration and its mismatches

After the browser receives the server's HTML, React runs the components again in the browser, attaches event handlers and takes over the page — hydration. It assumes the first client render produces exactly the HTML the server sent. When it does not, React 19 reports a hydration mismatch (in production builds, error 418: "Hydration failed because the server rendered text didn't match the client") and regenerates that part of the tree on the client, throwing the server HTML away. The fix belongs in the code, because the mismatch costs a second render and usually means the page shows something unstable.

The recurring causes: values that differ between environments — Date.now(), Math.random(), time zone or locale-dependent formatting; browser-only code that runs during render; invalid HTML that the browser silently repairs, such as a <div> inside a <p>; and markup that browser extensions inject into the page. The cures are just as patterned: compute the value on the server; or compute it after mount, inside an effect, and render a stable placeholder first; or, for unavoidable external text, mark the single element with suppressHydrationWarning rather than suppressing globally.

TSX · clock.tsx — a clock that cannot mismatch
'use client';

import { useEffect, useState } from 'react';

export default function Clock() {
  const [time, setTime] = useState<string | null>(null);
  useEffect(() => {
    const tick = () => setTime(new Date().toLocaleTimeString());
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);
  // First render (server and client) agrees: a stable placeholder.
  return <p>{time ?? ''}</p>;
}

When a clock or "posted 2 minutes ago" stamp is not essential markup, the better answer is often no Client Component at all: render the timestamp in a Server Component, where it is computed once and never compared. Reach for the effect-and-placeholder version only when the value must keep updating in the browser.

Diagnosing a mismatch is easier than it sounds. The development console prints the server HTML and the client render side by side, names the component, and links React's error page for error 418. Read the diff first: it usually points at exactly one unstable expression, and the fix is to make that expression deterministic or to move it out of the first render.

05. Check your understanding

Practice check · 2 questions

Actions and hydration

Two situations from the note form.

Q1. A visitor has JavaScript turned off and submits the note form, which uses a Server Action through `useActionState`. What happens?
Q2. The save action calls revalidatePath("/dashboard"). Which output refreshes?
Practice only: not graded, not saved, not evidence.

06. Apply it

Add a second mutation to the dashboard: a "delete note" button per list item, backed by a deleteNote Server Action. Write the action so that it re-checks the session, verifies the note belongs to the session user before deleting, validates the id, and revalidates the route. Then test all four paths from a terminal without JavaScript: signed-in delete, delete of another user's note id, an unauthenticated delete, and a non-numeric id. Finish by listing which of those checks a well-behaved browser would already have enforced — and confirm the server still enforces them.

07. Review prompt

Without looking back, list the four duties of a safe Server Action in order. Then explain why revalidatePath is needed at all when the action and the page live in the same application. Finally, name three causes of hydration mismatches and one fix for each.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check