Design a Form Builder – Frontend System Design

We’ll walk through the frontend system design for a form builder like Typeform or Google Forms: an authoring surface that edits a document, a live preview of that document, and a published runtime that collects answers. You’ll see why the form is a JSON schema and not a tree of React components, how a drag becomes one undoable command, how show/hide rules form a graph you can sort, and why a respondent who started on version 3 still submits against version 3 after you publish version 4.
This is not “build a form.” A single <form> with five labeled inputs is an afternoon. The interviewer wants a product that lets other people invent forms, change them after people have answered, hide questions from earlier answers, and ship markup a screen reader can use. The schema is the product. The canvas is a view of it.
Problem Statement
Design the frontend for a form builder used by teams to create surveys and intake forms.
Requirements:
- Authors drag fields onto a canvas, edit titles and options, and undo mistakes
- A live preview shows the form as respondents will see it
- Fields have validation rules, including a few cross-field checks
- Conditional logic can show, hide, or skip questions
- Draft edits do not change the live form until the author publishes
- Published forms are keyboard and screen-reader usable
Describe the schema, the editor, the preview, the logic graph, and how versions work.
Interviewers are checking three things. Do you keep one document as the source of truth, or do you let the builder, the preview, and the runtime drift? Can you talk about undo and drag without snapshotting the world on every pointer event? And do you treat accessibility as a property of the generated form, not of the builder chrome?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Typeform (one question at a time) or Google Forms (a long page)? | Both. The schema is the same. The runtime layout is a setting. |
| 2 | How large is a large form? | A few hundred fields, a few dozen logic rules. Not tens of thousands. |
| 3 | Multiplayer editing? | Out of scope. Two tabs of the same author is enough. Last-write-wins on a revision. |
| 4 | File uploads, payments, e-signatures? | Files yes. Payments and signatures out of scope. |
| 5 | Who sees responses? | The author, in a separate results view. We design the builder and the runtime, not the analytics charts. |
| 6 | Custom HTML or scripts in a field? | No. Titles and descriptions are text. A statement field is still data, not a script tag. |
| 7 | Browsers? | Evergreen desktop and mobile. The published form must work on a phone. |
Question 1 is a presentation switch, not a data-model fork. Question 2 is why this is not the Figma question: a few hundred DOM nodes is fine. You would be wrong to reach for WebGL. Question 3 means a revision number and a conflict toast, not operational transforms. Question 6 is a security answer you should give before you are asked.
Requirements
Functional
- Palette of field types: short text, long text, email, number, single choice, multi choice, dropdown, date, file, rating, statement.
- Canvas: add, delete, reorder, nest into pages. Drag from the palette and drag to reorder.
- Inspector: title, description, required, type-specific options, validation, visibility or jump rules.
- Undo and redo for the author’s edits. One gesture is one stack entry.
- Live preview that uses the same renderer as the published form.
- Publish a draft. Unpublish or roll back by restoring a previous version as a new draft.
- Respondents fill the latest published version. In-flight sessions keep the version they started.
Non-Functional
- A drag stays at 60fps. The inspector does not re-render on every
pointermove. - Preview updates within one frame of a committed edit, without remounting the iframe.
- The published form works with a keyboard, a screen reader, and autofill.
- The server re-validates every submit against the pinned schema. The client is not trusted.
- A lost tab does not lose the draft. Local write first, then a debounced PATCH.
The number that shapes the design is not “50,000 nodes.” It is “one document, three consumers.” If the builder invents a field the runtime cannot render, or the runtime accepts an answer the schema would reject, the product is wrong even if the canvas feels nice.
Napkin Math
| Metric | Estimate | Calculation | So what? |
|---|---|---|---|
| Fields in a large form | ~200 | Intake form, 8 pages, ~25 fields each | A DOM canvas is fine. Virtualize only the palette and the results table. |
| Schema size | ~40–80 KB | 200 fields × ~300 bytes of JSON | Ship the whole draft. Do not paginate the editor document. |
| Logic rules | ~40 | A fifth of fields have a show/hide | Cycle detection is a DFS, not a research paper. |
| Pointer events in a drag | 60–120 / sec | One per frame | Write a draft index. Commit one command on pointerup. |
| Undo stack | ~20 KB | 100 inverse ops × ~200 bytes | Ops, not snapshots. A snapshot of the schema is 80 KB each. |
| Preview messages | One per commit | postMessage of a structured clone | Do not stream pointermove into the iframe. |
Architecture
Four layers, and only one of them owns the document.
| Layer | Owns | Runs on | Talks to |
|---|---|---|---|
| Builder chrome | Palette, canvas, inspector, publish bar | React, main thread | Sends intents, reads derived views |
| Schema core | Document, commands, undo, logic graph | TypeScript store, main thread | Chrome, preview, draft sync |
| FieldRenderer | One field → accessible DOM | Preview iframe and runtime | Reads a schema plus answers |
| Network | Draft PATCH, publish, sessions | Main thread + IndexedDB | Forms API, file uploads |
React never holds the schema as a giant useState tree that the canvas mutates in place. The store applies a command and notifies subscribers. The canvas re-renders the rows that changed. The inspector subscribes to the selected field. The preview is not React at all from the builder’s point of view: it is an iframe that receives the schema over postMessage.
“The form is a document. The builder is an editor for that document. Preview and the live form are two hosts for the same renderer. If I cannot serialize the form and get the same UI back, the design is wrong.”
That boundary is the whole interview. People who start with “a Page component that maps over Field components in React state” spend the rest of the hour bolting on undo, preview, publish, and server validation as afterthoughts.
Why not a canvas renderer?
| Surface | Use it for | Do not use it for |
|---|---|---|
| DOM | Published form, preview, inspector | A 50,000-node design file |
| HTML5 drag / pointer | Palette drops and reorder | Drawing vector paths |
| Canvas 2D / WebGL | Out of scope | Inputs, keyboards, autofill, a11y |
A published form is a form. Native inputs give you mobile keyboards, password managers, <label>, and a focus order. Drawing questions onto a canvas throws that away. That cost is correct for Figma. It is wrong here.
Data Model
The document is a flat map of fields keyed by id, plus an ordered list of pages. Order among siblings is a fractional index, the same trick as a design file: moving a field is one property write, not a splice of a shared array.
type FieldId = string; // ULID, minted on the client
type FieldType =
| "short_text" | "long_text" | "email" | "number"
| "single_choice" | "multi_choice" | "dropdown"
| "date" | "file" | "rating" | "statement";
interface Field {
id: FieldId;
type: FieldType;
pageId: string;
index: string; // fractional, e.g. "a0V"
title: string;
description?: string;
required: boolean;
properties: FieldProps; // discriminated by type
validation: ValidationRule[];
}
interface FormDocument {
id: string;
title: string;
schemaFormat: number; // migrations of the schema language
pages: Record<string, Page>;
fields: Record<FieldId, Field>;
logic: LogicRule[];
theme: ThemeTokens;
draftRev: number;
}
type LogicRule =
| { id: string; kind: "show"; targetId: FieldId; when: Condition }
| { id: string; kind: "jump"; fromPageId: string; toPageId: string; when: Condition };
interface Condition {
op: "all" | "any";
clauses: { fieldId: FieldId; cmp: "eq" | "neq" | "gt" | "contains" | "filled"; value?: unknown }[];
}
interface FormVersion {
formId: string;
version: number; // 1, 2, 3...
schema: FormDocument; // frozen
publishedAt: string;
}
interface Response {
id: string;
formId: string;
formVersion: number; // pin
answers: Record<FieldId, unknown>;
startedAt: string;
submittedAt: string | null;
}
Four choices are worth defending.
Schema as data, not as components. The builder, the preview, the published runtime, and the server validator all consume FormDocument. A React element tree cannot be versioned, cannot be sent to a phone, and cannot be re-run on the server when a client lies about required.
Client-generated ids. A ULID (or sessionId:counter) lets the author drop three fields, point a logic rule at them, and undo the batch without waiting for the API. The PATCH is a sync, not an id allocator.
Fractional indexes for order. To drop Email between Name at "a0" and Team at "a1", you generate a key between them. Two tabs reordering different fields do not rewrite the same array. The same helper you would cite in a Figma answer works here: generateKeyBetween(prev, next).
Answers are not on the schema. Preview answers live in the iframe and die with it. Runtime answers live on a Response pinned to a version. If you store answers on the field, you cannot preview twice and you cannot publish without shipping someone’s test input.
schemaFormat is not version. The first is the language (“we added a compare rule kind”). The second is a published snapshot of one form. Mixing them is how you break old responses when you ship a builder feature.
Changing a field’s type is a delete plus a create. The id goes away, options do not get jammed into a different shape, and analytics do not pretend the old number field is the new dropdown. Renames and copy edits keep the id.
Drag-and-Drop Canvas
The canvas is a list of pages, each a list of field rows sorted by index. It is not an infinite design surface. Hit testing is “which gap did the pointer enter,” not an R-tree.
Use two input paths. They look similar and they are not.
| Gesture | API | Why |
|---|---|---|
| Palette → canvas | HTML5 drag-and-drop | You are dragging a type, not a record. dataTransfer carries fieldType. |
| Reorder on the canvas | pointerdown / move / up + setPointerCapture |
You need a ghost, a drop slot, and a single commit. HTML5 DnD is clumsy for that. |
A reorder is a short-lived drag session owned by the canvas: the field id, its index when the drag started, and a draft index that is visual only. On each pointer move, the canvas hit-tests the gaps between rows, computes a fractional key between the two neighbors of the gap under the pointer, stores it as the draft index, and repaints the ghost. On pointer up, if the draft index equals the start index, nothing happens. Otherwise the session produces exactly one setIndex command from the start index to the draft index.
Three rules keep this from feeling cheap.
Pointermove does not commit. It updates a transient draftIndex the canvas uses to position the ghost. The undo stack never sees it. If you apply a command per event, Undo takes twenty presses to reverse one drag.
The row component is keyed by fieldId, not by position. A reorder is a sort of the same elements. Remounting an input on every slot change steals focus and drops what the author typed in the title.
Drop targets are gaps, not rows. Highlighting a row looks like “drop into this field.” Highlighting the line between two rows matches the model: a new fractional index between two siblings. Dropping onto a page header targets that page’s first or last slot.
Nested pages are just another list. Dragging a field across a page boundary is setIndex plus setPageId in one batched command, so Undo puts it back on the original page in one step.
Undo
Every committed edit is a command with an inverse. The store applies the forward op, pushes the inverse, and clears redo. Undo applies the inverse as a new forward op and pushes the original onto redo.
type Command =
| { kind: "setIndex"; id: FieldId; from: string; to: string }
| { kind: "setTitle"; id: FieldId; from: string; to: string }
| { kind: "addField"; field: Field }
| { kind: "removeField"; field: Field }
| { kind: "setLogic"; from: LogicRule | null; to: LogicRule | null }
| { kind: "batch"; ops: Command[] };
Every command carries enough data to invert itself, which is why each one stores both from and to. Inverting a setter swaps them. Inverting addField is removeField with the same field, and the reverse. Inverting a batch inverts each op and reverses their order, so the last change is undone first.
Group a gesture. A title keystroke burst is one setTitle from the value at focus to the value at blur (or a 400ms idle). A drag is one setIndex. A “duplicate page” is a batch of add-field ops so Undo removes the copy, not field 14 of 14.
Do not snapshot the whole FormDocument. It is large, it hides what changed, and it cannot merge with a draftRev the server already accepted. Inverse ops are small enough to persist next to the draft in IndexedDB, so a refresh still has Undo for the current session. You do not owe the author Undo across a reload after a publish; say that.
The preview iframe is not on the stack. Neither are preview answers. Cmd+Z in the builder undoes schema edits. If focus is inside a title input, the first Cmd+Z belongs to the text field; the command bus listens on document only when the selection is a canvas row.
Live Preview
Preview is the published runtime pointed at the draft. That sentence is the design. If you build a second set of components “just for the builder,” they will diverge, and the author will publish a form that does not match what they previewed.
Host the renderer in an iframe. Builder chrome CSS must not leak into field styles, and a Typeform-style full-viewport question must not steal the builder’s scroll container. The iframe loads a static host page once. After that, the builder sends schema updates:
type PreviewIn =
| { type: "schema"; doc: FormDocument; layout: "page" | "one_at_a_time" }
| { type: "select"; fieldId: FieldId | null }
| { type: "reset" };
type PreviewOut =
| { type: "focus"; fieldId: FieldId }
| { type: "ready" };
Send schema on a committed command, not on pointermove. The ghost already shows the drag. Remounting the iframe on every keystroke is how the preview flickers and loses its place. A select message scrolls the matching field into view and draws a thin overlay, so the canvas and the preview stay coupled without sharing a DOM.
Preview answers stay in the iframe. A reset clears them when the author wants a clean run. They are never PATCHed. If the author needs to see the empty published state, that is reset, not a second renderer.
Check event.origin on every message.
Validation Rules
Validation is a pure function of a field, its value, and the current answer map. The same function runs in the renderer (inline errors) and on the server (submit). Authors do not write JavaScript. They pick a kind and fill params.
type ValidationRule =
| { kind: "required" }
| { kind: "length"; min?: number; max?: number }
| { kind: "range"; min?: number; max?: number }
| { kind: "pattern"; source: string; flags?: string }
| { kind: "file"; maxBytes: number; accept: string[] }
| { kind: "compare"; otherId: FieldId; cmp: "gt" | "gte" | "eq" };
The validator takes a field, its value, and the read-only answer map, runs the field’s rules in order, and returns the first error message or null. Stopping at the first failure keeps messages short and predictable: “Required” before “Too short”, never both.
required is just another rule, even though the inspector shows it as a toggle. Putting it on the field as a boolean is fine if the validator still reads it. Do not special-case it in five places.
pattern is a string you compile with new RegExp inside a try, with a length cap. You never eval a rule. A compare rule (“end date after start date”) reads the other field by id. If that id is missing, the rule is a no-op and the inspector flags it, the same as a broken link.
The important order is: visibility first, then validation. A required field that is hidden must not block submit. The server uses the same order against the pinned schema, so a client that hides the field in CSS and posts an empty body still fails if the field was actually visible under the answers it sent.
Show the first error on the field, and on submit show an error summary at the top that links to each invalid control. That summary is an accessibility requirement, not a polish item.
Conditional Logic Graph
Show/hide is a directed graph. An edge from A to B means “B’s visibility depends on A.” Jumps are edges from a page to another page. Both must be acyclic. A cycle has no topological order, so there is no stable visible set.
The visibility evaluator is a pure function from the document and the current answers to the ordered list of visible fields. It topologically sorts fields by their logic dependencies, which fails loudly on a cycle. It then walks them in that order. A field with no show-rule is visible. A field with a show-rule is visible only if its condition passes, evaluated against both the answers and the set of fields already found visible. The result keeps the original display order.
The condition check must see the already visible set. If B shows only when A is “Yes” and E shows only when B is filled, hiding A must hide E even if an old answer for B is still in memory. That is the cascade. Dropping the visible-set check is how a hidden student-id field still appears after the author says they are not a student.
When the author adds a rule, run the cycle check immediately. DFS from the target: if you can reach the condition field, reject the rule and name the cycle (“B depends on A, A depends on B”). Do not wait for preview. The same check belongs on paste and on restore-version, because those can import a broken graph.
Jumps are evaluated at page boundaries, not continuously. Typeform-style runtimes ask “where do I go next?” after a page submits. Google-Forms-style runtimes keep every still-visible field on the page and ignore jump rules, or you disable jumps in that layout. Store both kinds on the document; the renderer picks the ones that apply.
Default visibility is “shown.” A field with no show-rule is in. That keeps the empty-logic form honest and matches what authors expect when they drag a new question onto the canvas.
Hidden answers are discarded on submit. Keeping them “just in case” leaks data the respondent was told would not be collected (“not a student,” but you still stored the school name from an earlier toggle). The session may keep them in memory so toggling back restores the typed value. The persisted Response.answers map only contains visible ids.
Publish vs Draft, and Versioning
The author edits a mutable draft. Publish copies that draft into an immutable FormVersion and points “latest” at it. The live URL always loads latest. A session created against latest stores formVersion: N and never upgrades in place.
| Object | Mutates? | Who writes it | Who reads it |
|---|---|---|---|
Draft FormDocument |
Yes | Builder commands | Builder, preview |
FormVersion |
No | Publish | Runtime, validator, results |
Response |
Answers only | Runtime | Results view |
That split is what lets an author rewrite the form at 4pm without corrupting the person who opened it at 3:59. Hot-swapping schema mid-fill changes the questions under them. If you need a “form closed” switch, that is a flag on latest, not a mutate of v3.
Restore-version copies a frozen snapshot back into the draft and increments draftRev. It does not delete the snapshot. Publish again to make it live. The author can look at v2, v3, and v4 the way they look at deploys.
Two-tab edits use draftRev. PATCH sends the rev the tab last saw. A 409 means reload and toast. That is enough for a laptop left open. It is not multiplayer.
Autosave writes IndexedDB on every committed command, then PATCHes after 800ms of quiet. Reload reads local first and compares draftRev. The higher rev wins; same rev with extra local ops PATCHes them up.
File uploads use a signed URL. The answer stores the file id, not bytes. The draft never contains respondent files.
API
// REST
GET /api/forms/:id
PATCH /api/forms/:id // body { doc, draftRev } -> 200 { draftRev } | 409
POST /api/forms/:id/publish // -> 201 { version }
GET /api/forms/:id/versions
POST /api/forms/:id/versions/:n/restore
POST /api/forms/:id/sessions // -> { sessionId, formVersion, schema }
PUT /api/sessions/:id/answers // partial answers, same version
POST /api/sessions/:id/submit // server validates against formVersion
POST /api/files // -> { uploadUrl, fileId }
interface PublishResult {
version: number;
publishedAt: string;
}
The session POST is how you pin the version. Passing the schema in that response means the phone does not have to know about drafts. Submit is the only call that runs the full validator and the logic graph. Partial answer PUTs are best-effort persistence so a refresh does not lose a long form; they do not need to fail the whole schema yet.
Do not put the draft on a CDN. Published schemas are immutable at /forms/:id/v/:n.json. Latest is a short-lived pointer.
Optimizations
| Problem | Technique | Effect |
|---|---|---|
| Inspector re-rendering during a drag | Subscribe to selection, not to the whole doc | Chrome stays quiet while the ghost moves |
| Twenty undos for one drag | Commit on pointerup | One stack entry per gesture |
| Preview flicker | Reuse the iframe, send schema on commit | No reload, no lost scroll |
| Large option lists | Virtualize the inspector list, not the canvas | A 200-choice dropdown does not mount 200 inputs in the editor |
| Lost draft | IndexedDB on command, PATCH on idle | Refresh restores local, then reconciles |
| Slow first preview | Preload the preview host on builder boot | First schema message paints immediately |
Code-split the builder from the runtime so a phone does not download the inspector.
Handling Edge Cases
- Deleted field that logic still names. Treat the clause as false and flag the rule in the inspector. Do not throw in the runtime.
- Type change. New field id. Old responses keep the old id on the old version. Do not coerce “3” into the third option of a new dropdown.
- Paste from another form. Remap ids, then run cycle detection. Keep option ids inside a choice field stable unless they collide.
- Empty required file on a flaky upload. The answer is missing until the PUT of the file id succeeds. Submit disables while an upload is in flight.
- Two tabs, one draft. 409 on PATCH. Toast, reload, do not silently overwrite.
- Author publishes while preview is mid-answer. Preview is draft. Runtime sessions are a different host.
- Long one-at-a-time form. Persist
visibleIndex / visibleCounton the session, not a scroll offset.
Accessibility and Security
Accessibility of generated forms
The builder can be a forest of icon buttons. The published form cannot. FieldRenderer is where the interview is won.
- Every control has a visible
<label>bound withfor/id. Placeholders are not labels. - Help text is
aria-describedby. The first error isaria-invalid="true"plusaria-errormessage(or describedby if you skip the newer attribute). - Single choice is a
<fieldset>with a<legend>, orrole="radiogroup"with a labelled group. Do not draw divs that look like radios. - Required is in the label text and
aria-required, not a red asterisk with no accessible name. - Tab order follows the schema order of visible fields. Hiding a field means
hiddenor not rendering it, notopacity: 0that still tabs. - One-at-a-time layout moves focus to the next field’s label or input on Next, and back on Back. A scroll-into-view without a focus move leaves a keyboard user on the old control.
- Submit builds an error summary as a list of links. Focus the summary on a failed submit.
- Theme tokens are contrast-checked the same way a theme switcher checks them. A brand purple on white that fails 4.5:1 is a publish blocker, not a warning in a backlog.
- Respect
prefers-reduced-motionfor the one-at-a-time transition.
Lint in the builder: missing title, unlabeled choice, contrast fail, a cycle, a dangling compare. Publish blocks on those unless the author overrides.
Security
- Titles, descriptions, and choice labels are text. Render them with text nodes or a sanitizer that allows no tags. Authors are not a trusted HTML source.
- Conditions are structured data. Never turn a rule into
evalornew Function. - The server ignores client-side
validflags and re-runs visibility plus validation on the pinned schema. - File uploads use short-lived signed URLs and an allow-list of MIME types. The runtime origin does not serve user files.
- Draft endpoints require the author session. Published schema is public if the form is public; responses never are.
- Preview
postMessagechecks origin. Do not load the preview fromsrcdocon the app origin if you later allow custom CSS: keep the same origin split you would use for any untrusted document.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| State | Array of Field components in React | Flat schema document; chrome sends commands; three consumers share it |
| Drag | HTML5 DnD everywhere | DnD for types, pointer capture for reorder, commit on pointerup |
| Undo | Deep-clone the form on every edit | Inverse ops, one entry per gesture, not on the preview |
| Logic | if (answers.a === "Yes") in JSX |
DAG, cycle check at edit time, topo evaluate, cascade hide |
| Publish | A boolean isLive |
Immutable versions; sessions pin formVersion; drafts never serve |
| A11y | The builder has aria labels | The generated form has names, groups, focus moves, an error summary |
For the document-and-command pattern in a much larger editor, see Design Figma. For contrast and tokens on the published theme, see Design a Theme Switcher. For a smaller input surface, see Design a Poll Widget.
Conclusion: How to Design a Form Builder
Start with the document. A form is a schema: pages, fields, validation, and a graph of show/hide and jump rules. The builder writes that document through commands. Preview and the published runtime read it through one renderer. The server validates a submit against a frozen copy of the same document.
That one decision pays off everywhere. Drag becomes setIndex. Undo becomes an inverse. Logic becomes a DAG you refuse to cycle. Publish becomes a snapshot, and a respondent who already started is pinned to the snapshot they saw. If you can explain why hidden required fields must not block submit, and why version 4 must not rewrite a version 3 session, you have shown the interviewer you designed a product, not a component tree.
