Sub topic 10
Saving drafts and resuming later
A flow that collects ten fields is a promise that the user will not lose their work. Browsers crash, tabs close, phones lock, and people get called away from their desks. This chapter covers how to persist a flow's state and restore it safely.
It assumes you know the Data, Step, and FlowState types from the earlier chapters on flow state and navigation. It also assumes basic familiarity with JSON and key-value storage such as localStorage. The code is framework-neutral TypeScript and runs in Node or a browser.
What belongs in a draft
A draft is a snapshot of the flow that is good enough to rebuild the screen the user left. Not every field of FlowState earns a place in it.
| Field | Save it? | Reason |
|---|---|---|
| `data` | Yes | This is the user's work. |
| `current` | Yes | It tells you where to resume. |
| `history` | Optional | It can be rebuilt by replaying the steps, which is safer. |
| `errors` | No | Errors are derived from `data` and are recomputed on demand. |
| Passwords, card numbers, one-time codes | No | Persisting secrets in readable storage is a security risk. |
Add two pieces of metadata to every draft. A version number lets you reject drafts written by an older shape of the flow. A savedAt timestamp lets you expire drafts and, on a server, resolve conflicts.
Choosing where to store it
| Location | Survives reload | Survives device change | Main risk |
|---|---|---|---|
| In memory | No | No | Lost on any refresh. |
| `sessionStorage` | Yes, same tab | No | Lost when the tab closes. |
| `localStorage` or mobile local storage | Yes | No | Readable by anyone using the device and by any script on the page. |
| Server-side draft | Yes | Yes | Needs authentication, an API, and cleanup. |
Use local storage for short, low-sensitivity flows such as a sign-up form. Use a server draft when the flow is long, valuable, or sensitive, or when users switch between phone and laptop. Many products do both: write locally on every change for speed, and sync to the server at step boundaries.
The envelope and the storage interface
Wrap the state in a versioned envelope and talk to storage through a small interface. The interface lets you swap localStorage for a server client or an in-memory fake in tests.
First, the shared declarations from earlier chapters, repeated so this chapter runs on its own:
type Data = Record<string, string>;
type Step = {
id: string;
validate(data: Data): string[];
next(data: Data): string | null;
};
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};
const steps: Record<string, Step> = {
account: {
id: "account",
validate: (d) =>
/^\S+@\S+\.\S+$/.test(d.email ?? "") ? [] : ["Enter a valid email address."],
next: (d) => (d.accountType === "business" ? "company" : "review"),
},
company: {
id: "company",
validate: (d) => ((d.company ?? "").trim() ? [] : ["Enter your company name."]),
next: () => "review",
},
review: {
id: "review",
validate: () => [],
next: () => null,
},
};Now the persistence layer:
interface DraftStorage {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
const DRAFT_VERSION = 1;
const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
type Draft = {
version: number;
savedAt: number;
current: string;
data: Data;
};
function saveDraft(
storage: DraftStorage,
key: string,
state: FlowState,
now: number = Date.now(),
): void {
const draft: Draft = {
version: DRAFT_VERSION,
savedAt: now,
current: state.current,
data: state.data,
};
storage.setItem(key, JSON.stringify(draft));
}
function isDraft(value: unknown): value is Draft {
if (typeof value !== "object" || value === null) return false;
const v = value as Record<string, unknown>;
if (typeof v.version !== "number") return false;
if (typeof v.savedAt !== "number") return false;
if (typeof v.current !== "string") return false;
if (typeof v.data !== "object" || v.data === null) return false;
return Object.values(v.data).every((x) => typeof x === "string");
}
function loadDraft(
storage: DraftStorage,
key: string,
now: number = Date.now(),
): Draft | null {
const raw = storage.getItem(key);
if (raw === null) return null;
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
storage.removeItem(key);
return null;
}
if (!isDraft(parsed) || parsed.version !== DRAFT_VERSION || now - parsed.savedAt > MAX_AGE_MS) {
storage.removeItem(key);
return null;
}
return parsed;
}Three details matter here.
- Storage is untrusted input. Users, browser extensions, and old versions of your code can all write to it.
loadDraftparses insidetry, checks the shape withisDraft, and discards anything that does not match. - The clock is a parameter. Passing
nowmakes expiry testable without waiting a week. - Bad drafts are deleted. If a draft fails the checks, removing it prevents the same error on every visit.
Restoring by replaying instead of trusting
The saved current may no longer be valid. You might have renamed a step, removed a branch, or changed a validation rule since the draft was written. If you jump straight to current, you can land the user on a step they could not have reached.
A safer approach is to replay the flow from the first step using the saved data. At each step, run validate and next, and stop when you reach the saved step or hit a step that fails. This also rebuilds history correctly, so Back keeps working.
function restoreState(
draft: Draft,
flow: Record<string, Step>,
firstId: string,
): FlowState {
let current = firstId;
const history: string[] = [];
const visited = new Set<string>();
while (current !== draft.current) {
const step = flow[current];
if (!step || visited.has(current)) break;
visited.add(current);
if (step.validate(draft.data).length > 0) break;
const nextId = step.next(draft.data);
if (nextId === null || !(nextId in flow)) break;
history.push(current);
current = nextId;
}
return { current, history, data: draft.data, errors: [] };
}The loop ends in one of four ways:
- It reaches the saved step. The user resumes exactly where they left off.
- A step fails validation. The user resumes at the first step that needs attention, which is correct because later answers may depend on it.
- The saved step no longer exists or is unreachable, so the replay stops at the end of the path or at the first invalid step.
- A cycle appears. The
visitedset stops it, which protects against an infinite loop caused by a faultynextfunction.
Here is the whole cycle with an in-memory store:
const memory = new Map<string, string>();
const storage: DraftStorage = {
getItem: (k) => memory.get(k) ?? null,
setItem: (k, v) => {
memory.set(k, v);
},
removeItem: (k) => {
memory.delete(k);
},
};
const before: FlowState = {
current: "company",
history: ["account"],
data: { email: "[email protected]", accountType: "business" },
errors: [],
};
saveDraft(storage, "signup-draft", before);
const draft = loadDraft(storage, "signup-draft");
if (draft) {
const after = restoreState(draft, steps, "account");
console.log(after.current, after.history);
}This prints company [ 'account' ]. If you change email to "oops" in the saved data and run it again, the replay stops at account, because that step no longer validates.
When to save
Each save trigger trades freshness against cost.
- On a successful advance. This is the minimum. The user has just confirmed a step, so the data is known to be valid.
- On field change, debounced. This protects text the user typed but did not submit. A debounce waits until typing pauses before saving, so you do not write on every keystroke.
- On page hide. Browsers fire
visibilitychangeandpagehidewhen a tab is closed or backgrounded. This is a last chance to write, but it is not reliable on every platform, so do not depend on it alone.
A small debounce helper:
function debounce<A extends unknown[]>(fn: (...args: A) => void, ms: number) {
let timer: ReturnType<typeof setTimeout> | undefined;
return (...args: A): void => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
const saveSoon = debounce(
(state: FlowState) => saveDraft(storage, "signup-draft", state),
500,
);Call saveSoon(state) from your field-change handler, and call saveDraft directly after a successful advance. Saving a draft with invalid values in it is fine. A draft is work in progress, not a submission, so do not gate saving on validation.
Server drafts and conflicts
A server draft adds three concerns that local storage does not have.
- Identity. Key the draft by the signed-in user and a flow name, or by a random draft id returned when the flow starts. Never accept a client-supplied id that grants access to someone else's draft.
- Concurrent edits. A user may open the flow on two devices. Send the
savedAtvalue, or a revision counter, with each write. If the server holds a newer revision, reject the write and let the client choose between keeping its version or loading the server's. Silent last-write-wins loses data. - Latency and failure. Saving over a network can fail. Keep the local copy as the source of truth during editing, retry in the background, and show a quiet status such as "Saved" or "Could not save. Retrying." so the user knows whether leaving is safe.
Lifecycle and edge cases
A draft needs a clear start and end.
- Clear it on successful submission. Otherwise the next visit offers to resume a flow the user already finished. Delete the draft only after the server confirms the submission, not before.
- Expire old drafts. The 7-day limit in
loadDraftis an example. Pick a window that fits the data, and delete server drafts with a scheduled job. - Let users start over. When you detect a draft, offer "Continue" and "Start again". Choosing "Start again" deletes the draft. Do not silently resume, because the user may not remember the earlier session or may be on a shared device.
- Version your drafts. When you change field names or the meaning of a value, increment
DRAFT_VERSION. A cheap option is to discard older drafts. A kinder option is a migration function that upgrades version 1 data to version 2 before the replay runs. - Handle storage failures.
setItemcan throw when the quota is full or when the browser blocks storage, such as in some private modes. Wrap writes intry, and treat a failed save as a degraded mode, not a crash. - Respect branches. If the user switched
accountTypefrombusinesstopersonal, thecompanyvalue stays indata. Decide whether to keep it, in case they switch back, or to drop values that belong to unreachable steps before submission. Replay handles navigation correctly either way, but your submit code must not send stale answers from a branch the user abandoned. - Announce the resume. Moving a user to a later step on load is a screen change they did not trigger. Move focus to the step heading and say briefly that you restored their progress, so screen reader users know what happened.
Summary of the design
- Save
dataandcurrent, plus a version and timestamp. Leave outerrorsand secrets. - Treat stored text as untrusted. Parse defensively and discard drafts that fail the checks.
- Rebuild
historyby replayingvalidateandnextfrom the first step. - Save on advance, and on debounced field changes. Back both with a page-hide save where available.
- Delete the draft after a confirmed submission, on expiry, and when the user starts over.
Exercise
A user's saved draft says current is "company", but a release has since added a required "phone" step between "account" and "company", and the saved data has no phone value. Using restoreState with the updated steps, where does the user land, and why is that better than jumping straight to "company"?
Show answer
The replay starts at "account", which still validates, and moves to "phone". The phone step fails validation because the saved data has no phone value, so the loop stops and the user resumes at "phone". Jumping straight to "company" would skip a required step and could submit data that the new rules consider incomplete. Replaying also builds history as ["account"], so Back returns to the account step.
Exercise
Why does loadDraft delete a draft when JSON.parse throws or the version does not match, instead of just returning null and leaving it in storage?
Show answer
If the bad draft stays in storage, every later visit repeats the same failed parse and the same null result. In the case of a version mismatch, an old draft could also be overwritten only at the next save, leaving stale data around for a long time. Deleting it once keeps storage clean and makes the failure a one-time event.