Skip to content

A Disabled Button Is Not Idempotency

The Course
•
18 min study

The decision

A pending button stops a person clicking twice. It can't stop a browser or proxy resending a request after a dropped connection, or two requests that left before the button was disabled. For that, each logical operation needs a key, and the server remembers which keys it has already done.

Where the key comes from

The page makes a fresh random key every time it renders, and the form carries it in a hidden input:

JSX
export default async function Page() {
  const items = await listItems();
  // One key per rendered form: a new render, after a save, gets a new key.
  const requestKey = newRequestKey();
  return (
    // …
    <AddForm requestKey={requestKey} />
  );
}
JSX
<form action={action} ref={form}>
  <input type="hidden" name="requestKey" value={requestKey} />
  <label>
    Title <input name="title" />
  </label>

Every request sent from that one rendered form has the same key, which is what a retry is. After a successful save, revalidatePath("/") renders the page again, so the next item gets a new key. The action passes the key to createOnce, which keeps a receipt per key:

JavaScript
export async function createOnce(key, title) {
  if (receipts.has(key)) return { id: receipts.get(key), repeated: true };
  const id = items.length + 1;
  items.push({ id, title });
  receipts.set(key, id);
  return { id, repeated: false };
}

Predict

The lab's Simulate a retry button sends the same form data twice, as a resent request would. Type Forms and press it. What two results appear, and how many items does the list end with?

A Disabled Button Is Not Idempotency Next.js · 8 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 AddForm from "./AddForm.jsx"; import { listItems, newRequestKey } from "@/lib/store.js"; export default async function Page() { const items = await listItems(); // One key per rendered form: a new render, after a save, gets a new key. const requestKey = newRequestKey(); return ( <main> <h1>A Disabled Button Is Not Idempotency</h1> <section> <h2>Items</h2> <ul> {items.map((item) => ( <li key={item.id}> #{item.id} {item.title} </li> ))} </ul> <AddForm requestKey={requestKey} /> </section> <Cases /> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { createOnce } from "@/lib/store.js"; export async function addItem(previous, formData) { const key = formData.get("requestKey"); const title = String(formData.get("title") ?? "").trim(); if (typeof key !== "string" || !key) return { message: "A request key is required." }; if (!title) return { message: "Enter a title." }; const { id, repeated } = await createOnce(key, title); revalidatePath("/"); return { message: repeated ? `Already saved as #${id}` : `Saved as #${id}` }; } "use client"; import { useActionState, useRef, useState } from "react"; import { addItem } from "./actions.js"; export default function AddForm({ requestKey }) { const [state, action, pending] = useActionState(addItem, { message: "" }); const [retryLog, setRetryLog] = useState([]); const form = useRef(null); // Sends the same form data twice, as a browser or proxy might after a // dropped connection. Both requests carry the same hidden key. async function simulateRetry() { const data = new FormData(form.current); const first = await addItem(null, data); const second = await addItem(null, data); setRetryLog([first.message, second.message]); } return ( <form action={action} ref={form}> <input type="hidden" name="requestKey" value={requestKey} /> <label> Title <input name="title" /> </label> <button disabled={pending}>{pending ? "Saving…" : "Save"}</button> <button type="button" onClick={simulateRetry}> Simulate a retry </button> <p role="status">{state.message}</p> <ol aria-label="Retry results"> {retryLog.map((line, i) => ( <li key={i}>{line}</li> ))} </ol> </form> ); } 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> ); } 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; } export function run({ key, receipt, count }) { if (receipt && receipt.key === key) return { id: receipt.id, count }; return { id: count + 1, count: count + 1 }; } export const examples = [ [ { key: "a", receipt: { key: "a", id: 3 }, count: 3 }, { id: 3, count: 3 }, ], [ { key: "b", receipt: null, count: 3 }, { id: 4, count: 4 }, ], ]; // Pretend tables in server memory: the items, and one receipt per request key. const items = [{ id: 1, title: "Routing" }]; const receipts = new Map(); export async function listItems() { return items.map((item) => ({ ...item })); } // Creates the item once per key. A repeated key returns the first result. // (A real database needs a unique constraint on the key to make this atomic.) export async function createOnce(key, title) { await new Promise((resolve) => setTimeout(resolve, 100)); if (receipts.has(key)) return { id: receipts.get(key), repeated: true }; const id = items.length + 1; items.push({ id, title }); receipts.set(key, id); return { id, repeated: false }; } // A random, unguessable key. (On a real server, crypto.randomUUID() does this.) export function newRequestKey() { const bytes = crypto.getRandomValues(new Uint8Array(16)); return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); }
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

Saved as #2, then Already saved as #2, and the list ends with two items: #1 Routing and #2 Forms. The second request found the receipt for its key and returned the first result instead of inserting again. If the page made a new key per request instead of per rendered form, both requests would have different keys and the list would get two Forms.

The rule on its own

lib/contract.js models the same receipt check as a pure function, so its cases can be checked without a server:

JavaScript
export function run({ key, receipt, count }) {
  if (receipt && receipt.key === key) return { id: receipt.id, count };
  return { id: count + 1, count: count + 1 };
}

The failure to avoid

Checking for a duplicate and inserting later is not atomic in a concurrent database. This in-memory model teaches the contract; a real implementation needs a unique constraint and transaction.

Trace two calls with key "a": the first with no receipt, the second with the receipt the first created. Then say what happens if the page made a new key for every request.

Exercise

Extend the contract

Reject a missing or blank key with an error field equal to A request key is required. No count should be returned for that failure.

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 {"key": " ", "receipt": null, "count": 3} must return {"error": "A request key is required."}.
Your working space Next.js · 8 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 AddForm from "./AddForm.jsx"; import { listItems, newRequestKey } from "@/lib/store.js"; export default async function Page() { const items = await listItems(); // One key per rendered form: a new render, after a save, gets a new key. const requestKey = newRequestKey(); return ( <main> <h1>A Disabled Button Is Not Idempotency</h1> <section> <h2>Items</h2> <ul> {items.map((item) => ( <li key={item.id}> #{item.id} {item.title} </li> ))} </ul> <AddForm requestKey={requestKey} /> </section> <Cases /> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { createOnce } from "@/lib/store.js"; export async function addItem(previous, formData) { const key = formData.get("requestKey"); const title = String(formData.get("title") ?? "").trim(); if (typeof key !== "string" || !key) return { message: "A request key is required." }; if (!title) return { message: "Enter a title." }; const { id, repeated } = await createOnce(key, title); revalidatePath("/"); return { message: repeated ? `Already saved as #${id}` : `Saved as #${id}` }; } "use client"; import { useActionState, useRef, useState } from "react"; import { addItem } from "./actions.js"; export default function AddForm({ requestKey }) { const [state, action, pending] = useActionState(addItem, { message: "" }); const [retryLog, setRetryLog] = useState([]); const form = useRef(null); // Sends the same form data twice, as a browser or proxy might after a // dropped connection. Both requests carry the same hidden key. async function simulateRetry() { const data = new FormData(form.current); const first = await addItem(null, data); const second = await addItem(null, data); setRetryLog([first.message, second.message]); } return ( <form action={action} ref={form}> <input type="hidden" name="requestKey" value={requestKey} /> <label> Title <input name="title" /> </label> <button disabled={pending}>{pending ? "Saving…" : "Save"}</button> <button type="button" onClick={simulateRetry}> Simulate a retry </button> <p role="status">{state.message}</p> <ol aria-label="Retry results"> {retryLog.map((line, i) => ( <li key={i}>{line}</li> ))} </ol> </form> ); } 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> ); } 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; } export function run({ key, receipt, count }) { if (receipt && receipt.key === key) return { id: receipt.id, count }; return { id: count + 1, count: count + 1 }; } export const examples = [ [ { key: "a", receipt: { key: "a", id: 3 }, count: 3 }, { id: 3, count: 3 }, ], [ { key: "b", receipt: null, count: 3 }, { id: 4, count: 4 }, ], ]; // Pretend tables in server memory: the items, and one receipt per request key. const items = [{ id: 1, title: "Routing" }]; const receipts = new Map(); export async function listItems() { return items.map((item) => ({ ...item })); } // Creates the item once per key. A repeated key returns the first result. // (A real database needs a unique constraint on the key to make this atomic.) export async function createOnce(key, title) { await new Promise((resolve) => setTimeout(resolve, 100)); if (receipts.has(key)) return { id: receipts.get(key), repeated: true }; const id = items.length + 1; items.push({ id, title }); receipts.set(key, id); return { id, repeated: false }; } // A random, unguessable key. (On a real server, crypto.randomUUID() does this.) export function newRequestKey() { const bytes = crypto.getRandomValues(new Uint8Array(16)); return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); }
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

A missing key isn't a new operation: it's a request the receipt check can't protect. Reject it before anything is counted.

Hint 2: a first step

Validate the key before consulting receipts or allocating an id.

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({ key, receipt, count }) {
  if (typeof key !== "string" || !key.trim())
    return { error: "A request key is required." };
  if (receipt && receipt.key === key) return { id: receipt.id, count };
  return { id: count + 1, count: count + 1 };
}

The check comes first, so a keyless request can't allocate an id or match a receipt by accident. Returning only error, with no count, stops a caller reading an unchanged count as if it were a result. !key.trim() treats a whitespace key as blank, since one is almost certainly a bug.

Explain it without the code

A reader double-clicks Save on a slow connection. Write what each of the two requests carries and what each gets back.

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.