Skip to content

Write, Invalidate, Then Navigate

The Course
•
18 min study

The decision

A successful action has an order: validate, commit the write, invalidate the view that shows it, then redirect. The last step hides a trap. redirect() doesn't return: it throws a special error that Next.js catches to perform the navigation. A catch around it catches that too.

Read, predict, run

The lab's form calls this Server Action. It wraps the save in try/catch so a database failure becomes a message, and the redirect sits inside the try:

JavaScript
export async function saveItem(previous, formData) {
  const title = String(formData.get("title") ?? "").trim();
  if (!title) return { error: "Enter a title." };
  try {
    await addItem(title);
    revalidatePath("/");
    redirect("/saved");
  } catch (error) {
    console.log("saveItem caught:", error.message);
    return { error: "Could not save. Try again." };
  }
}

Run the lab, type Forms and press Save. Before you press it, predict what the page shows and what the console logs.

Write, Invalidate, Then Navigate Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import SaveForm from "./SaveForm.jsx"; import { listItems } from "@/lib/items.js"; export default async function Page() { const items = await listItems(); return ( <main> <h1>Write, Invalidate, Then Navigate</h1> <section> <h2>Items</h2> <ul> {items.map((title) => ( <li key={title}>{title}</li> ))} </ul> <SaveForm /> </section> <Cases /> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { addItem } from "@/lib/items.js"; export async function saveItem(previous, formData) { const title = String(formData.get("title") ?? "").trim(); if (!title) return { error: "Enter a title." }; try { await addItem(title); revalidatePath("/"); redirect("/saved"); } catch (error) { console.log("saveItem caught:", error.message); return { error: "Could not save. Try again." }; } } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useActionState } from "react"; import { saveItem } from "./actions.js"; export default function SaveForm() { const [state, action, pending] = useActionState(saveItem, { error: null }); return ( <form action={action}> <label> Title <input name="title" /> </label> <button disabled={pending}>{pending ? "Saving…" : "Save"}</button> <p role="alert">{state.error}</p> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } import Link from "next/link"; export default function Saved() { return ( <main> <h1>Saved</h1> <Link href="/">Back to the list</Link> </main> ); } export function run({ valid, saved }) { if (!valid) return ["validation_error"]; if (!saved) return ["save_error"]; return ["write", "revalidatePath", "redirect"]; } export const examples = [ [{ valid: false, saved: false }, ["validation_error"]], [{ valid: true, saved: true }, ["write", "revalidatePath", "redirect"]], ]; // A pretend database table, kept in server memory. const items = ["Routing"]; export async function listItems() { return [...items]; } export async function addItem(title) { await new Promise((resolve) => setTimeout(resolve, 50)); items.push(title); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction

Forms appears in the list, and under the form: Could not save. Try again. The console shows saveItem caught: NEXT_REDIRECT. Trace it: addItem succeeds, revalidatePath marks the list for re-rendering, then redirect("/saved") throws its special error. The catch takes it for a failure, logs it and returns an error, so the reader is told a saved item failed, and pressing Save again adds a duplicate.

Fix it

Move the two steps that should only run after a successful write out of the try, so the catch covers only the database call. Save Forms again: the page should go to Saved.

The repaired action
JavaScript
export async function saveItem(previous, formData) {
  const title = String(formData.get("title") ?? "").trim();
  if (!title) return { error: "Enter a title." };
  try {
    await addItem(title);
  } catch (error) {
    console.log("saveItem caught:", error.message);
    return { error: "Could not save. Try again." };
  }
  revalidatePath("/");
  redirect("/saved");
}

The catch now only sees errors from addItem. When you must keep a wider try, call unstable_rethrow(error) from next/navigation first thing in the catch: it rethrows Next.js's own control-flow errors, such as the ones from redirect() and notFound(), and does nothing for others.

The order as a rule

lib/contract.js states the same order as data, so it can be checked for every outcome. A rejected draft must not invalidate or navigate; a failed save must not either:

JavaScript
export function run({ valid, saved }) {
  if (!valid) return ["validation_error"];
  if (!saved) return ["save_error"];
  return ["write", "revalidatePath", "redirect"];
}

The failure to avoid

Putting redirect inside a catch-all can report a successful save as an error. Invalidating before a write can let readers reload stale data.

Trace {"valid": true, "saved": false}: which steps run? Then explain why revalidatePath must not come before write in the success list.

Exercise

Extend the contract

For a successful inline edit, invalidate but do not redirect when inline is true. Keep the normal create flow.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"valid": true, "saved": true, "inline": true} must return ["write", "revalidatePath"].
Your working space Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import SaveForm from "./SaveForm.jsx"; import { listItems } from "@/lib/items.js"; export default async function Page() { const items = await listItems(); return ( <main> <h1>Write, Invalidate, Then Navigate</h1> <section> <h2>Items</h2> <ul> {items.map((title) => ( <li key={title}>{title}</li> ))} </ul> <SaveForm /> </section> <Cases /> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { addItem } from "@/lib/items.js"; export async function saveItem(previous, formData) { const title = String(formData.get("title") ?? "").trim(); if (!title) return { error: "Enter a title." }; try { await addItem(title); revalidatePath("/"); redirect("/saved"); } catch (error) { console.log("saveItem caught:", error.message); return { error: "Could not save. Try again." }; } } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useActionState } from "react"; import { saveItem } from "./actions.js"; export default function SaveForm() { const [state, action, pending] = useActionState(saveItem, { error: null }); return ( <form action={action}> <label> Title <input name="title" /> </label> <button disabled={pending}>{pending ? "Saving…" : "Save"}</button> <p role="alert">{state.error}</p> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } import Link from "next/link"; export default function Saved() { return ( <main> <h1>Saved</h1> <Link href="/">Back to the list</Link> </main> ); } export function run({ valid, saved }) { if (!valid) return ["validation_error"]; if (!saved) return ["save_error"]; return ["write", "revalidatePath", "redirect"]; } export const examples = [ [{ valid: false, saved: false }, ["validation_error"]], [{ valid: true, saved: true }, ["write", "revalidatePath", "redirect"]], ]; // A pretend database table, kept in server memory. const items = ["Routing"]; export async function listItems() { return [...items]; } export async function addItem(title) { await new Promise((resolve) => setTimeout(resolve, 50)); items.push(title); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Navigation is the only step that differs between an inline edit and a create. The write and the invalidation are needed either way.

Hint 2: a first step

Choose navigation after the shared write and invalidation steps.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ valid, saved, inline }) {
  if (!valid) return ["validation_error"];
  if (!saved) return ["save_error"];
  return inline
    ? ["write", "revalidatePath"]
    : ["write", "revalidatePath", "redirect"];
}

The two failure branches stay first, so a rejected or failed edit still neither invalidates nor navigates. For an inline edit the reader is already looking at the list, so revalidatePath alone refreshes it, and a redirect would only reload the same place. Dropping revalidatePath instead would leave the old title on screen until a reload.

Explain it without the code

For each of write, revalidatePath and redirect, write what the reader would see if only that step were missing.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.