Sub topic 13
Handling submission failures and duplicates
This chapter covers what happens after the user presses the final submit button. You should already know how to model a multi-step flow as a state machine, how to keep form values in state, and how a review step collects data before submission. You should also be comfortable with fetch and Promises in TypeScript.
Submission is the point where a form meets the network, and the network fails in ways the earlier steps never do. A request can time out, the server can reject a value you thought was valid, the user can click twice, or the connection can drop after the server has already saved the data. A good flow handles each of these without losing what the user typed and without creating two orders.
Why submission needs its own design
Validation in the browser catches mistakes the client can detect. Submission adds failures the client cannot predict. Treat these as a separate category and decide how each one looks to the user.
| Failure | Typical signal | What the user needs |
|---|---|---|
| Field rejected by server | HTTP 400 or 422 with field details | The error beside the field, and a way back to that step |
| Not signed in or session expired | HTTP 401 or 403 | A sign-in path that keeps the draft |
| Conflict or duplicate | HTTP 409 | An explanation, and the existing record if possible |
| Server fault | HTTP 500 to 504 | A retry button and reassurance that data is kept |
| No connection or timeout | `fetch` rejects, or an abort fires | A retry button, ideally an automatic retry |
| Success lost in transit | Request sent, response never arrives | A safe retry that does not create a second record |
The last row is the hardest. The client cannot tell "the server never received it" from "the server saved it but the response was lost." Idempotency, covered below, solves this.
Model submission as part of the state machine
Add explicit submission states to the flow instead of using a loose isLoading boolean. A boolean cannot express the difference between "never tried," "in flight," "failed and retryable," and "done."
In TypeScript, a discriminated union keeps impossible combinations out of the code.
type Submission =
| { status: "idle" }
| { status: "submitting" }
| { status: "failed"; message: string; retryable: boolean }
| { status: "succeeded"; id: string };
function startSubmit(current: Submission): Submission {
// Ignore a second submit while one is already running.
if (current.status === "submitting" || current.status === "succeeded") {
return current;
}
return { status: "submitting" };
}The guard in startSubmit is the first line of defense against duplicates. If the state is already submitting, a second click changes nothing.
Prevent duplicate submissions in three layers
No single technique is enough. Use all three, because each covers a gap in the others.
- Interface layer. Disable the submit button while the request runs, and show progress. Keep the button focusable if you can, and announce the state change, because a button that vanishes from the tab order can drop keyboard focus.
- State layer. Ignore submit events while the status is
submitting. This protects against the Enter key, double clicks that arrive before the DOM updates, and programmatic submits. - Server layer. Make the request idempotent. An operation is idempotent when repeating it has the same effect as doing it once. Only the server can guarantee this, because only the server knows whether a record already exists.
Disabling the button alone fails when the user reloads the page and resubmits, when two tabs are open, or when a retry follows a lost response. Those cases need the server layer.
Idempotency keys
An idempotency key is a unique value the client generates once per intended submission and sends with every attempt of it. The server stores the key with the result. If the same key arrives again, the server returns the stored result instead of creating another record.
Generate the key when the user begins the final submit, not on every click. Reuse it for retries of the same data. Create a new key only when the user changes their answers and submits something different.
type Payload = Record<string, string>;
type Result =
| { ok: true; id: string }
| { ok: false; status: number; fieldErrors?: Record<string, string> }
| { ok: false; status: 0 }; // network failure or timeout
async function submitOnce(
payload: Payload,
idempotencyKey: string,
timeoutMs = 10000
): Promise<Result> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch("/api/signup", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify(payload),
signal: controller.signal,
});
if (response.ok) {
const body = await response.json();
return { ok: true, id: String(body.id) };
}
let fieldErrors: Record<string, string> | undefined;
if (response.status === 400 || response.status === 422) {
const body = await response.json().catch(() => null);
fieldErrors = body?.errors;
}
return { ok: false, status: response.status, fieldErrors };
} catch {
return { ok: false, status: 0 };
} finally {
clearTimeout(timer);
}
}Note that fetch does not reject on HTTP error statuses. It rejects only on network failure or abort, so you must check response.ok yourself. A timeout is also not proof of failure: the server may still be processing. That is why the key matters.
A short server-side sketch shows the contract. This example uses an in-memory map for clarity. A real server stores keys in a database with an expiry, and makes the check and the write one atomic step.
const results = new Map<string, { id: string }>();
function handleSignup(key: string | undefined, payload: Record<string, string>) {
if (!key) return { status: 400, body: { error: "Idempotency-Key header required" } };
const existing = results.get(key);
if (existing) return { status: 200, body: existing }; // replay, no new record
const record = { id: crypto.randomUUID() };
results.set(key, record);
return { status: 201, body: record };
}Sort errors and respond to each kind
After a failed attempt, classify the result and pick one response. Do not show the same generic "Something went wrong" for everything.
type Outcome =
| { kind: "success"; id: string }
| { kind: "fields"; errors: Record<string, string> }
| { kind: "auth" }
| { kind: "conflict" }
| { kind: "retry"; message: string };
function classify(result: Result): Outcome {
if (result.ok) return { kind: "success", id: result.id };
if (result.status === 0) {
return { kind: "retry", message: "We could not reach the server. Check your connection and try again." };
}
if ((result.status === 400 || result.status === 422) && "fieldErrors" in result && result.fieldErrors) {
return { kind: "fields", errors: result.fieldErrors };
}
if (result.status === 401 || result.status === 403) return { kind: "auth" };
if (result.status === 409) return { kind: "conflict" };
return { kind: "retry", message: "Something went wrong on our side. Your answers are saved. Try again." };
}Server-side field errors
When the server rejects a field, such as an email address that is already registered, merge the message into the same errors map your validation uses. Then take the user to the earliest step that contains an error. Because errors are keyed by field name, the existing error display works unchanged.
Find that step by mapping each field to its step. Move the state machine there, set focus on the error summary or the first invalid field, and keep every other value intact. Never clear the form because a single field failed.
Retrying safely
Retry only what is safe to retry. With an idempotency key, retrying a POST is safe. Without one, retry only when you know the request never reached the server, which you rarely can.
- Retry network failures and 502, 503, and 504 responses automatically, a small number of times.
- Wait longer between each attempt (exponential backoff) and add a random offset (jitter) so many clients do not retry at the same instant.
- Do not automatically retry 4xx responses. The same request will fail the same way.
- After the automatic attempts run out, show a manual "Try again" button.
async function submitWithRetry(
payload: Payload,
key: string,
maxAttempts = 3
): Promise<Result> {
let result: Result = { ok: false, status: 0 };
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
result = await submitOnce(payload, key);
const transient = !result.ok && (result.status === 0 || result.status >= 502);
if (!transient || attempt === maxAttempts) return result;
const delay = 2 ** attempt * 500 + Math.random() * 250;
await new Promise((resolve) => setTimeout(resolve, delay));
}
return result;
}Keep the user's data
Failure handling is mostly about not destroying work.
- Keep values in state through every failure. Do not reset the form on error.
- Save the draft before sending. If the page crashes or the user closes the tab during a failure, the persistence layer from the earlier chapter lets them resume.
- Clear the draft only after a confirmed success, never on submit.
- On an auth failure, send the user to sign in with the draft preserved, then return them to the review step.
Communicate the state to every user
Failures must be visible and announced. Show the message near the submit button, and also put it in a region that assistive technology reads without moving focus.
<div role="status" aria-live="polite" id="submit-status"></div>
<div role="alert" id="submit-error" hidden></div>
<button type="submit" id="submit-button">Create account</button>Use role="status" for progress such as "Submitting your answers." Use role="alert" for errors that need immediate attention. After a field-level rejection, move focus to the first invalid field or to an error summary so keyboard users land where the problem is.
Write messages that say what happened, whether the data is safe, and what to do next. "We could not reach the server. Your answers are saved. Try again." beats "Error 0."
Handle the success case just as carefully. Show a confirmation with a reference number, and prevent the Back button from returning to a live form that could be submitted again. Replacing the history entry with the confirmation page, or showing a "you have already submitted" state, covers this.
Common mistakes
- Using only a disabled button and no server-side idempotency.
- Generating a new idempotency key on every retry, which defeats the purpose.
- Treating a timeout as a definite failure and telling the user to start over.
- Retrying 4xx errors automatically.
- Clearing the draft when the request starts instead of when it succeeds.
- Showing server field errors only as a banner, leaving the user to guess which step holds the problem.
- Hiding the failure message in a toast that disappears before a screen reader or a slow reader can use it.
Exercise
A user clicks "Submit," the request times out after 10 seconds, and they click "Try again." The server had actually saved the first request but the response was lost. Explain what prevents a duplicate record, and name one mistake in the client that would break that protection.
Show answer
The client sends the same idempotency key with both attempts. The server stores the key with the first result, so on the second request it finds the key and returns the stored result instead of creating a new record. The protection breaks if the client generates a new key for the retry, because the server then sees a different request and creates a second record.
Exercise
The server returns 422 with the error {"email": "This address is already registered"} after the user finished the review step. Describe what the interface should do, in order.
Show answer
Merge the error into the form's errors map under the field name "email". Move the state machine from the review step back to the step that contains the email field. Keep all other entered values. Move focus to the email field or an error summary, and announce the error through an alert region. Reset the submission status to idle so the user can edit and submit again, with a new idempotency key once the answers change.