Sub topic 10
Saving Drafts and Resuming Later
This chapter assumes you know basic HTML forms, TypeScript or JavaScript, and the step reducer from the earlier chapter on modeling the flow as a state machine. Here you will add draft saving so a user can reload, close a tab, or come back tomorrow and continue where they stopped.
Why drafts matter
A multi-step form takes minutes to finish. Anything that interrupts the user can destroy that work: an accidental reload, a crashed tab, an expired session, a phone call, or a dead battery. Without saved drafts, the user has to retype everything, and many will leave instead.
Draft saving is separate from submission. A draft is incomplete, unvalidated data that you keep for the user's convenience. A submission is a finished, validated request that the server acts on. Keep these two ideas apart in your code and your interface.
What to save
The step state machine already gives you the pieces. A draft needs only enough data to rebuild the state:
- The current step id.
- The field values entered so far.
- A version number for the draft format.
- A timestamp, so you can expire old drafts.
Do not save derived or transient data:
- Errors. Recompute them by validating when needed. Saved errors go stale when rules change.
- Loading and submission flags. Restoring "submitting" after a reload would leave the form stuck.
- Sensitive values. Do not store passwords, payment card numbers, government IDs, or security answers in browser storage. Treat these as fields that are never saved, and ask the user to enter them again.
Choosing where to save
You have two main options, and they solve different problems.
| Storage | Survives reload | Survives closing the browser | Works across devices | Notes |
|---|---|---|---|---|
| `sessionStorage` | Yes | No (cleared when the tab closes) | No | Simple. Good for short flows. |
| `localStorage` | Yes | Yes | No | Persists until cleared. Readable by any script on the same origin. |
| Server-side draft | Yes | Yes | Yes | Needs an account or a draft token. Needs an API. |
Pick based on what you promise the user. If you say "come back later," browser storage on one device only keeps that promise for the same browser. If users start on a phone and finish on a laptop, you need server-side drafts tied to an account or a link sent by email.
Browser storage can also be unavailable. Private browsing modes, enterprise policies, and full quotas can make setItem throw an error. Your form must still work when saving fails.
A basic save and restore
The following code stores the step and values after each change. It restores them on load, and falls back to a fresh start when the saved data is missing or broken.
const DRAFT_KEY = "signup-draft";
function saveDraft(step: string, values: Record<string, string>): void {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ step, values }));
}
function loadDraft(): { step: string; values: Record<string, string> } | null {
const raw = sessionStorage.getItem(DRAFT_KEY);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
}The try and catch around JSON.parse matter. A draft written by an older version of your code, or edited by hand, can be invalid JSON. Failing to parse should mean "start fresh," never "the page is broken."
Making the storage code safer
The basic version has three weaknesses. It trusts whatever it reads, it can throw when saving, and it cannot handle format changes. The next version fixes all three.
const DRAFT_KEY = "signup-draft";
const DRAFT_VERSION = 2;
const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
const NEVER_SAVE = new Set(["password", "cardNumber"]);
const STEP_IDS = ["account", "details", "review"];
type Draft = {
version: number;
savedAt: number;
step: string;
values: Record<string, string>;
};
function safeSave(step: string, values: Record<string, string>): boolean {
const filtered: Record<string, string> = {};
for (const [name, value] of Object.entries(values)) {
if (!NEVER_SAVE.has(name)) filtered[name] = value;
}
const draft: Draft = {
version: DRAFT_VERSION,
savedAt: Date.now(),
step,
values: filtered,
};
try {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
return true;
} catch {
return false;
}
}
function safeLoad(): Draft | null {
try {
const raw = sessionStorage.getItem(DRAFT_KEY);
if (!raw) return null;
const data = JSON.parse(raw);
if (typeof data !== "object" || data === null) return null;
if (data.version !== DRAFT_VERSION) return null;
if (typeof data.savedAt !== "number") return null;
if (Date.now() - data.savedAt > MAX_AGE_MS) return null;
if (!STEP_IDS.includes(data.step)) return null;
if (typeof data.values !== "object" || data.values === null) return null;
return data as Draft;
} catch {
return null;
}
}
function clearDraft(): void {
try {
sessionStorage.removeItem(DRAFT_KEY);
} catch {
// Nothing useful to do if storage is unavailable.
}
}Points worth noticing:
safeSavereturns a boolean. If it returnsfalse, you can decide whether to tell the user that progress is not being saved.- The version check discards drafts from an incompatible format. For a small form, discarding is acceptable. For a long form, write a migration function that converts version 1 to version 2 instead.
- The step id is checked against the known list. If you rename or remove a step in a release, an old draft cannot send the user to a step that no longer exists.
- Values are not trusted. The reducer and validation still run on them like any other input.
When to save
You have several moments to choose from, each with a trade-off.
- On every change. Safest against data loss, but it writes to storage on every keystroke. This is cheap for
sessionStoragebut costly for server requests. - After a pause. Save when the user stops typing for a short time, such as one second. This is called debouncing. It cuts writes sharply.
- On step change. Easy to reason about, and the data is validated at that point. A user who leaves in the middle of a step loses that step's input.
- On page hide. Listen for the
visibilitychangeevent and save when the page becomes hidden. This catches tab switches and many closings, including on mobile wherebeforeunloadis unreliable.
A practical combination is a debounced save on change plus a save on visibilitychange. The following helper does both.
function debounce<T extends unknown[]>(fn: (...args: T) => void, delay: number) {
let timer: ReturnType<typeof setTimeout> | undefined;
const wrapped = (...args: T) => {
if (timer !== undefined) clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
wrapped.cancel = () => {
if (timer !== undefined) clearTimeout(timer);
timer = undefined;
};
return wrapped;
}
function setupAutosave(
getState: () => { step: string; values: Record<string, string> }
) {
const save = () => {
const { step, values } = getState();
safeSave(step, values);
};
const debounced = debounce(save, 1000);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
debounced.cancel();
save();
}
});
return debounced; // call this after each state change
}Cancelling the pending debounced call before the immediate save avoids a second, redundant write.
Restoring the user's place
Restoring has to cooperate with the state machine. Build the initial state from the draft, then let the normal rules apply.
Three decisions deserve care:
- Restore silently or ask? If the draft is recent and on the same device, restore and show a short message such as "We restored your answers from earlier." If the form is on a shared device, ask first, and offer "Start over."
- Which step to open? Opening the saved step is usually right. But if earlier steps would now fail validation, for example because rules changed, send the user to the first invalid step.
- How to move focus. After a restore, place focus on the page heading or a status message so keyboard and screen reader users know what happened. Do not put focus on a field that suddenly has an old value without announcing it.
Always give the user a visible way to discard the draft. Without it, a person using a shared computer can leave personal data behind for the next user.
Conditional fields and drafts
The conditional fields chapter taught that hidden fields must not be validated or submitted. Drafts add a twist. If the user chose "ship" and typed an address, then switched to "pick up," you have two choices:
- Keep the hidden address in the draft, so switching back restores it. This is friendlier.
- Remove hidden values, so stale answers never exist.
Either choice is acceptable in the draft, as long as the final submission uses only visible fields. The activeValues function from the conditional fields chapter does that filtering at submit time. Keep draft storage and submission payloads as separate concerns.
Server-side drafts
When drafts live on the server, extra problems appear.
- Identity. Tie the draft to a signed-in user, or issue an unguessable draft token placed in a "resume" link. Never use a guessable id such as a sequential number.
- Concurrency. A user may open the form in two tabs or on two devices. Decide what happens. A simple rule is "last write wins." A safer rule attaches a revision number to each save, and the server rejects a save with an old revision so the client can ask the user which copy to keep.
- Network failure. Saving over the network can fail. Keep the latest values in memory, retry quietly, and show a status such as "Saved" or "Could not save, retrying." Do not block typing while a save is in flight.
- Privacy. A server draft is stored personal data. Set a retention period, delete drafts after submission, and cover them in your privacy policy.
Cleaning up
A draft must end at the right moment. Clear it:
- After a successful final submission, and only after the server confirms success. If you clear it before and the request fails, the user loses everything.
- When the user chooses "Start over."
- When the draft expires.
The submission chapter that follows covers failure handling in detail. For now, remember the rule: clear the draft after confirmed success, never before.
Common mistakes
- Saving validation errors, which then show up as stale messages after restore.
- Saving a "submitting" flag, which leaves the form disabled after reload.
- Storing sensitive fields in
localStorage, where any script on the page can read them. - Not handling
JSON.parsefailures or storage exceptions. - Skipping a version number, so an old draft crashes the new code.
- Restoring a step that the current flow no longer contains.
- Never clearing the draft, so a finished form reopens with old answers.
Summary
- A draft holds the step id, the values, a version, and a timestamp. It leaves out errors, flags, and sensitive data.
- Use
sessionStorageorlocalStoragefor one device, and server drafts for cross-device resume. - Treat saved data as untrusted input: parse safely, check the version, and check the step.
- Save after a short pause and when the page is hidden.
- Tell the user when you restore, and let them discard.
- Clear the draft only after the server confirms submission.
Exercise
A user fills in step 1 and step 2 of a three-step form, then your app releases an update that renames the step "details" to "profile". The user reloads and their old draft contains step: "details". Describe two protections from this chapter that prevent a crash, and what the user sees as a result.
Show answer
First, the draft version number: if you bump the version when the step ids change, the loader sees a mismatch and discards the draft, so the user starts fresh. Second, the check that the saved step id exists in the current list of steps: safeLoad returns null when "details" is not in STEP_IDS. A better option than discarding is a migration that maps "details" to "profile" and keeps the values, so the user resumes with their answers intact. In the discard case the user sees an empty first step. In the migration case they see the restored step and a short "We restored your answers" message.
Exercise
Why should the draft be cleared only after the server confirms a successful submission, and not when the user presses the submit button?
Show answer
The request can fail because of a network error, a server error, or a rejected value. If the draft was already cleared, the user would have to re-enter everything. Clearing after confirmed success keeps the data available for a retry.