Getting started
Formhaus keeps fields, validation, visibility, and steps in a JSON definition. The core engine runs without a UI framework; React, Vue, Figma, and custom renderers use the same format.
This guide covers the open-source library: MIT, no account, and onSubmit sends the data to your own backend.
The same definition renders natively on iOS and macOS with SwiftUI, and runs on Android and the JVM with Kotlin. See iOS and macOS and Android and JVM.
Hosted form without a backend
Formhaus Cloud is a separate, optional service. Run claude mcp add --transport http formhaus https://api.formhaus.dev/mcp and ask: "Make me a waitlist form and give me the link." See the Cloud quickstart.
Install
npm install @formhaus/core @formhaus/reactnpm install @formhaus/core @formhaus/vuenpm install @formhaus/coreInstall @formhaus/core next to the adapter: the stylesheet and the FormDefinition type come from it. With any other framework, use @formhaus/core directly. See the Svelte recipe.
Optional baseline styles
The default React and Vue components render unstyled HTML. For a finished look import the shared stylesheet:
import '@formhaus/core/style.css';Theme via CSS custom properties (--fh-color-primary, --fh-radius, --fh-gap, etc.). The hover and selected-option colors are derived from --fh-color-primary. With FormhausForm, set theme tokens on .fh-cloud to also style the notices, load errors and success message. Inside FormhausForm, --fh-color-border-focus, --fh-input-padding, --fh-font-size-heading, --fh-font-size-title, --fh-card-padding, --fh-color-primary-hover, --fh-color-primary-soft and --fh-color-error-soft have no value unless you set them. Custom CSS that reads one needs a fallback, for example var(--fh-input-padding, 10px 14px).
Inputs, textareas, selects, date, time and file fields, scale boxes and the switch track use --fh-color-input-border. Radio and multiselect option cards use --fh-option-card-border, which is --fh-color-input-border by default. Group cards, dividers and dialogs use --fh-color-border. The token source is in @formhaus/core/tokens/.
Colors come from these variables:
| Variable | Used for |
|---|---|
--fh-color-text | Body text |
--fh-color-text-muted | Helper text, counters and secondary labels |
--fh-color-bg | Page and control fill |
--fh-color-bg-disabled | Disabled controls |
--fh-color-primary | Primary buttons, checked controls and the selected option card border |
--fh-color-primary-text | Text and icons on --fh-color-primary |
--fh-color-primary-soft | Background of a selected option card |
--fh-color-border | Group cards, dividers, matrix rows and dialogs |
--fh-color-border-focus | Focus outline of every control |
--fh-color-input-border | Inputs, scale boxes and the switch track |
--fh-color-input-border-strong, --fh-color-input-border-strong-hover | Input borders under prefers-contrast: more |
--fh-option-card-border | Radio and multiselect option cards |
--fh-color-secondary-border | Secondary button and file button border |
--fh-color-error | Error text and invalid borders |
--fh-color-scrim | Dialog backdrop |
--fh-color-shadow | Shadow of raised elements and dialogs |
Hover states apply only on devices with a mouse or trackpad, and transitions turn off under prefers-reduced-motion. These variables set the hover colors:
| Variable | Used for |
|---|---|
--fh-color-input-border-hover | Input and scale box borders and the switch track |
--fh-option-card-border-hover | Option card borders |
--fh-color-border-hover | Secondary button borders |
--fh-color-control-hover | Radio and checkbox borders |
--fh-color-bg-hover | Option, secondary and text button backgrounds |
--fh-color-primary-hover | Primary button background and checked switch track |
Spacing and sizes come from these variables:
| Variable | Default | Used for |
|---|---|---|
--fh-space-1 … --fh-space-10 | 4, 6, 8, 10, 12, 14, 16, 18, 20, 24px | Every margin, padding and gap in the stylesheet |
--fh-gap | 28px | Space between fields, also inside sections and group cards |
--fh-card-padding | 24px (16px up to 480px wide) | Side and bottom padding of group item cards |
--fh-input-padding | --fh-space-4 --fh-space-6 | Padding inside inputs |
--fh-control-height, --fh-radius | 46px, 10px | Input and button height, corner radius |
--fh-icon-button-size | 32px | Width and height of the picture Enlarge button and the dialog Close button |
--fh-star-size | 32px (40px on touch screens) | Size of a rating star |
--fh-option-image-width | 200px | Smallest picture card width when the field has no columns |
--fh-shadow-raised | 0 2px 8px --fh-color-shadow | Shadow of the picture Enlarge button |
--fh-font-size, --fh-font-size-small | 15px, 13px (17px, 15px on touch screens) | Labels and inputs; helpers, errors and item titles |
--fh-font-size-heading, --fh-font-size-title | font size + 2px, + 5px | Section headings; step titles |
--fh-color-error-soft, --fh-color-error-hover | derived from --fh-color-error, #9e2a23 | Hover of the group item Remove button |
--fh-matrix-sticky-top | 0 | Top offset of the sticky matrix column header, such as the height of a fixed page header |
The stylesheet is light by default. For dark colors add data-fh-theme="dark" to the form or any ancestor:
<div data-fh-theme="dark">
<!-- FormRenderer -->
</div>When you bring your own components via the components prop, the stylesheet doesn't apply to them.
Action buttons use these classes:
| Class | Buttons |
|---|---|
fh-form-actions__button--primary | Continue, Submit |
fh-form-actions__button--secondary | Back |
fh-form-actions__button--text | Skip, Cancel |
Every button also has fh-form-actions__button. A variant on back, skip or cancel replaces the role class.
Stable names
From 1.0, the --fh-* variables in the tables above and these class names do not change within a major version. Other custom properties in style.css start with --fhi-: they are private and can change in any version. Their values and the look can change in a minor version, and the changelog lists each change.
| Class | Element |
|---|---|
fh-form | The <form> |
fh-form__fields | The list of fields of the current step |
fh-cloud | The FormhausForm wrapper |
fh-section | A section |
fh-section__title | A section heading |
fh-section__description | A section description |
fh-section__body | The fields of a section |
fh-group | A group |
fh-group__header | The header of a group item |
fh-group__title | The title of a group item |
fh-group__helper | The helper text of a group |
fh-group__body | The items of a group |
fh-group__item | A group item |
fh-group__fields | The fields of a group item |
fh-group__remove | The Remove button of a group item |
fh-group__add | The Add button of a group |
fh-group__status | The live announcement of a group |
fh-field__label | A field label |
fh-field__helper | A field helper text |
fh-form-actions__button | Every action button |
fh-form-actions__button--primary | Continue, Submit |
fh-form-actions__button--secondary | Back |
fh-form-actions__button--text | Skip, Cancel |
Quick start
Save the definition as contact-form.json:
{
"id": "contact",
"title": "Contact Us",
"submit": { "label": "Send" },
"fields": [
{ "key": "name", "type": "text", "label": "Name", "validation": { "required": true } },
{ "key": "email", "type": "email", "label": "Email", "validation": { "required": true } }
]
}TypeScript types JSON strings as string, so values such as layout or variant do not match FormDefinition. parseDefinition() checks the JSON and returns it typed, or throws a FormDefinitionError that lists every problem:
import { parseDefinition } from '@formhaus/core';
import { FormRenderer } from '@formhaus/react';
import '@formhaus/core/style.css';
import json from './contact-form.json';
const definition = parseDefinition(json);
export function ContactForm() {
return (
<FormRenderer
definition={definition}
onSubmit={(values) => console.log(values)}
/>
);
}<script setup lang="ts">
import { parseDefinition } from '@formhaus/core';
import { FormRenderer } from '@formhaus/vue';
import '@formhaus/core/style.css';
import json from './contact-form.json';
const definition = parseDefinition(json);
async function submit(values: Record<string, unknown>) {
console.log(values);
}
</script>
<template>
<FormRenderer :definition="definition" @submit="submit" />
</template>The renderer reads the form definition, renders fields, handles validation, and gives you values on submit.
Choose a renderer
Three paths render the same definition. Sizes for each are in Bundle size.
| Path | You write | Renderer does |
|---|---|---|
useFormEngine | All markup | Nothing. It gives the visible fields of the step, values, errors, the current step, setValue, next, back and submit |
HeadlessFormRenderer | A component for each field type, actions and progress | Steps, field order, conditions, focus and the error summary, with your components |
FormRenderer | Nothing, or a component for some types | The same as HeadlessFormRenderer, with built-in fields, actions and progress |
useFormEngine has no component map. It is the smallest path.
import type { FormDefinition } from '@formhaus/core';
import { useFormEngine } from '@formhaus/react';
type Props = { definition: FormDefinition; send: (values: Record<string, unknown>) => Promise<void> };
export function ContactForm({ definition, send }: Props) {
const engine = useFormEngine(definition);
return (
<form
onSubmit={(event) => {
event.preventDefault();
engine.submit(send);
}}
>
{engine.visibleFields.map((field) => (
<label key={field.key}>
{field.label}
<input value={String(engine.values[field.key] ?? '')} onChange={(event) => engine.setValue(field.key, event.target.value)} />
{engine.errors[field.key]}
</label>
))}
{!engine.isFirstStep && (
<button type="button" onClick={() => engine.back()}>
Back
</button>
)}
{engine.isLastStep ? (
<button type="submit">Send</button>
) : (
<button type="button" onClick={() => engine.next()}>
Next
</button>
)}
</form>
);
}<script setup lang="ts">
import type { FormDefinition } from '@formhaus/core';
import { useFormEngine } from '@formhaus/vue';
const props = defineProps<{ definition: FormDefinition; send: (values: Record<string, unknown>) => Promise<void> }>();
const { engine, visibleFields, values, errors, isFirstStep, isLastStep } = useFormEngine(() => props.definition);
function input(key: string, event: Event) {
engine.setValue(key, (event.target as HTMLInputElement).value);
}
</script>
<template>
<form @submit.prevent="engine.submit(props.send)">
<label v-for="field in visibleFields" :key="field.key">
{{ field.label }}
<input :value="values[field.key] ?? ''" @input="input(field.key, $event)" />
{{ errors[field.key] }}
</label>
<button v-if="!isFirstStep" type="button" @click="engine.back()">Back</button>
<button v-if="isLastStep" type="submit">Send</button>
<button v-else type="button" @click="engine.next()">Next</button>
</form>
</template>HeadlessFormRenderer renders your components for a design system. See Headless renderer.
<HeadlessFormRenderer
definition={definition}
components={{ text: MyInput, email: MyInput, select: MySelect }}
layout={{ actions: MyFormActions, progress: MyStepProgress }}
onSubmit={handleSubmit}
/><HeadlessFormRenderer
:definition="definition"
:components="{ text: MyInput, email: MyInput, select: MySelect }"
:layout="{ actions: MyFormActions, progress: MyStepProgress }"
@submit="onSubmit"
/>FormRenderer uses the built-in fields. components replaces only the types you list. See Override default components.
<FormRenderer definition={definition} components={{ phone: MyPhoneInput }} onSubmit={handleSubmit} /><FormRenderer :definition="definition" :components="{ phone: MyPhoneInput }" @submit="onSubmit" />Definition and initial values
initialValues is the starting value of the form, not a controlled value: changing it later does not change the form. A new definition object creates a new form and resets its values, even with the same content. Keep the definition in a module constant, useMemo or a Vue computed, and change key to reset the form on purpose:
const definition = parseDefinition(json);
function ProfileForm({ user, plans }) {
const withPlans = useMemo(() => addPlanOptions(definition, plans), [plans]);
return <FormRenderer key={user.id} definition={withPlans} initialValues={user} onSubmit={save} />;
}<script setup lang="ts">
const definition = parseDefinition(json);
const props = defineProps<{ user: User; plans: Plan[] }>();
const withPlans = computed(() => addPlanOptions(definition, props.plans));
</script>
<template>
<FormRenderer :key="user.id" :definition="withPlans" :initial-values="user" @submit="save" />
</template>In development, the renderer warns when it gets a new definition object with the same content as the previous one.
Keep answers when the definition changes
Some flows load part of the form later. A signup form asks for the plan, then the backend returns the steps for that plan. Set keepValues and pass the new definition: the form keeps the answers and the current step instead of resetting.
function SignupForm() {
const [definition, setDefinition] = useState(baseDefinition);
return (
<FormRenderer
definition={definition}
keepValues
onFieldChange={async (key, value) => {
if (key === 'plan') setDefinition(await loadPlanDefinition(value));
}}
onSubmit={submit}
/>
);
}<script setup lang="ts">
const definition = shallowRef(baseDefinition);
async function changed(key: string, value: unknown) {
if (key === 'plan') definition.value = await loadPlanDefinition(value);
}
</script>
<template>
<FormRenderer :definition="definition" keep-values @field-change="changed" @submit="submit" />
</template>A field keeps its value when the new definition has a field with the same key and type. New fields start from their defaults. The user stays on the same step when it still exists, and steps added before it are checked on submit. Without keepValues, a new definition resets the form as before. The useFormEngine hook and composable take keepValues in their options, and engine.replaceDefinition() does the same on a bare engine. See Replacing the definition.
Build the definition from app values
A definition that reads app data, such as helper text built from saved settings, changes whenever that data does. Build it in useMemo or computed and set keepValues. A refetch of the settings then updates the text without resetting the answers, and the unsaved-changes baseline survives.
import type { FormDefinition } from '@formhaus/core';
type Limits = { dailyLimit: number };
function withSaved(definition: FormDefinition, saved: Limits): FormDefinition {
return {
...definition,
fields: definition.fields?.map((field) =>
field.key === 'dailyLimit' ? { ...field, helperText: `Saved: ${saved.dailyLimit} per day` } : field,
),
};
}function LimitsForm({ saved, save }: { saved: Limits; save: (values: Record<string, unknown>) => Promise<void> }) {
const definition = useMemo(() => withSaved(base, saved), [saved]);
const { markClean, ref } = useFormDirty();
return (
<FormRenderer
ref={ref}
definition={definition}
initialValues={saved}
keepValues
onSubmit={async (values) => {
await save(values);
markClean();
}}
/>
);
}<script setup lang="ts">
const props = defineProps<{ saved: Limits; save: (values: Record<string, unknown>) => Promise<void> }>();
const definition = computed(() => withSaved(base, props.saved));
const { markClean, ref: formRef } = useFormDirty();
async function submit(values: Record<string, unknown>) {
await props.save(values);
markClean();
}
</script>
<template>
<FormRenderer :ref="formRef" :definition="definition" :initial-values="saved" keep-values @submit="submit" />
</template>base is the parsed definition. initialValues is read once, so saved does not overwrite what the user typed. Without keepValues, every new saved object resets the form.
Renderer handle
Put a ref on FormRenderer or HeadlessFormRenderer to drive the form from app code. The ref is typed as FormRendererHandle.
| Member | Description |
|---|---|
setValue(key, value) | Sets a value. It does not call onFieldChange (React) or emit fieldChange (Vue) |
getValues() | A copy of the values |
values | The current values. Reactive in Vue |
goToStep(stepId) | Opens a step. See Opening a step by id |
showField(key) | Opens the step of a field and focuses it. See Errors in app code |
getErrors() | The error summary. See Errors in app code |
submit() | Validates and submits like the submit button. Resolves to true when the submit handler ran and accepted. Added in 1.9.0 |
reset(values?) | Resets the form to values, or to the defaults. Added in 1.9.0 |
submitting | true while a submit runs. Added in 1.9.0 |
engine | The running FormEngine. Added in 1.9.0 |
id goes on the <form> element, so a submit button outside the form, such as in a dialog footer, submits it:
<Dialog footer={<button type="submit" form="settings">Save</button>}>
<FormRenderer id="settings" definition={definition} layout={{ actions: () => null }} onSubmit={save} />
</Dialog><Dialog>
<FormRenderer id="settings" :definition="definition" :layout="{ actions: () => null }" @submit="save" />
<template #footer>
<button type="submit" form="settings">Save</button>
</template>
</Dialog>On a multi-step form the button runs Continue until the last step, like the built-in primary button.
useSubmitState keeps such a button in sync. Pass its ref to the renderer, or pass an engine or handle: useSubmitState(engine). It works for a renderer that mounts later, such as in a dialog body. Added in 1.9.0.
import { FormRenderer, useSubmitState } from '@formhaus/react';
const status = useSubmitState();
<Dialog footer={<button type="submit" form="settings" disabled={!status.canSubmit}>{status.submitting ? 'Saving' : 'Save'}</button>}>
<FormRenderer ref={status.ref} id="settings" definition={definition} layout={{ actions: () => null }} onSubmit={save} />
</Dialog><script setup lang="ts">
import { FormRenderer, useSubmitState } from '@formhaus/vue';
const { canSubmit, submitting, ref: formRef } = useSubmitState();
</script>
<template>
<FormRenderer :ref="formRef" id="settings" :definition="definition" @submit="save" />
<button type="submit" form="settings" :disabled="!canSubmit">{{ submitting ? 'Saving' : 'Save' }}</button>
</template>useSubmitState | Description |
|---|---|
submitting | true while a submit runs |
validating | true while async step validation or a step hook runs |
canSubmit | true on the last step, or in a single-step form, when no submit or validation runs and submit.disabled does not match |
ref | Callback ref for the renderer |
In Vue the values are computed refs. The handle keeps one identity for each engine, so storing it in state does not re-render in a loop.
The renderer puts noValidate on the <form>, so the browser never shows its own validation bubbles. In React, className, style, aria-* and data-* props go to the <form>. In Vue, attributes fall through to it.
onValuesChange (React) and valuesChange (Vue) fire on mount and on every value-changing operation, with a frozen copy of the values. In Vue, the handle also has a reactive values. See Derived values.
How it works
Form definition --> FormEngine (TypeScript) --> Adapter --> UI components
|
|-- values, errors, step state
|-- visibility (show/hide fields)
|-- validation (required, pattern, etc.)
+-- general, field, and structure subscriptions5 published packages:
| Package | What it does | Dependencies |
|---|---|---|
@formhaus/core | Types, validation, visibility, FormEngine class | None (pure TS) |
@formhaus/vue | Vue adapter with default HTML field components | @formhaus/core |
@formhaus/react | React adapter with default HTML field components | @formhaus/core |
@formhaus/mcp | MCP server that validates definitions and simulates step paths for AI agents | @formhaus/core, MCP SDK |
formhaus | CLI that sets up the MCP server and agent instructions in coding agents | None |
The engine is framework-agnostic. It holds form state, runs validation, tracks field visibility, and manages step navigation. Adapters connect the engine to framework-specific reactivity and render UI components.
Packages
@formhaus/core
Pure TypeScript, zero deps. Contains:
- Type definitions for the form definition format
FormEngineclass (state machine for the form)- Visibility evaluation (
show/showAnyconditions) - Validation (built-in rules + custom validators)
- Definition warnings for missing dependencies and field or step cycles
@formhaus/vue
Vue 3.3.3+. Renders native HTML form elements by default. Override any field type with your own components via the components prop.
@formhaus/react
React 18 and 19. Renders native HTML by default and accepts replacements through components. It works with Next.js prerendering and React's renderToString without a next/dynamic wrapper.
@formhaus/mcp
Node 22.12+. Runs over stdio in Claude Code, Claude Desktop, Cursor and other MCP clients. See MCP Server.
Next steps
- Field Types: all supported form field types
- Validation: add rules to your fields
- Examples: working form definitions to learn from