JSON vs builder
A form is a FormConfig: a plain object. You can get one from code (FormBuilder) or from JSON (what the visual builder exports and the Hub stores). Both feed the same <Form>.
The same contact form both ways. Switch between them: the render is identical, and the check below confirms the two configs are the same.
Same config both ways: true
validateFormConfig(json) → {"ok":true,"errors":[]}
Same JSON, one field without a type → {"ok":false,"errors":[{"code":"field-type-missing","path":"fields.name.type","message":"field \"name\" requires a type"}]}
/**
* Demo de «JSON vs builder». SIN RED: el mismo formulario escrito con FormBuilder y como JSON a
* mano; la demo renderiza el que elijas, comprueba que son el mismo config y pasa el JSON por
* `validateFormConfig` (con una versión rota para ver el error).
*/
import type { FormConfig } from '@saastro/forms';
import { Form, FormBuilder } from '@saastro/forms';
import { validateFormConfig } from '@saastro/forms/validation';
import { useMemo, useState } from 'react';
import { FormProvider } from '@/components/FormProvider';
import { Button } from '@/components/ui/button';
import { TooltipProvider } from '@/components/ui/tooltip';
/** Way 1 — in code. */
export const fromBuilder = () =>
FormBuilder.create('contact')
.layout('manual')
.columns(12)
.addField('name', (f) =>
f.type('text').label('Name').required().minLength(2).columns({ default: 12 }),
)
.addField('email', (f) =>
f.type('email').label('Email').required().email().columns({ default: 12 }),
)
.addField('topic', (f) =>
f
.type('select')
.label('Topic')
.optional()
.options([
{ value: 'sales', label: 'Sales' },
{ value: 'support', label: 'Support' },
])
.columns({ default: 12 }),
)
.addStep('contact', ['name', 'email', 'topic'])
.initialStep('contact')
.successMessage('Thanks!')
.build();
/** Way 2 — as JSON: what the visual builder exports and the Hub stores. */
export const fromJson: unknown = {
formId: 'contact',
layout: { mode: 'manual', columns: 12 },
fields: {
name: {
type: 'text',
label: 'Name',
schema: { required: true, minLength: 2 },
layout: { columns: { default: 12 } },
},
email: {
type: 'email',
label: 'Email',
schema: { required: true, format: 'email' },
layout: { columns: { default: 12 } },
},
topic: {
type: 'select',
label: 'Topic',
schema: { required: false },
options: [
{ value: 'sales', label: 'Sales' },
{ value: 'support', label: 'Support' },
],
layout: { columns: { default: 12 } },
},
},
steps: { contact: { id: 'contact', fields: ['name', 'email', 'topic'] } },
initialStep: 'contact',
successMessage: 'Thanks!',
};
/** Key-order-insensitive stringify: two configs are the same when their JSON is. */
const canonical = (v: unknown): string =>
JSON.stringify(v, (_k, value) =>
value && typeof value === 'object' && !Array.isArray(value)
? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)))
: value,
);
export default function JsonVsBuilderDemo() {
const [way, setWay] = useState<'builder' | 'json'>('builder');
const builderConfig = useMemo(() => fromBuilder(), []);
const same = canonical(builderConfig) === canonical(fromJson);
const good = validateFormConfig(fromJson);
// The same JSON with a field that lost its `type`.
const broken = validateFormConfig({
...(fromJson as Record<string, unknown>),
fields: { name: { label: 'Name' } },
steps: { contact: { id: 'contact', fields: ['name'] } },
});
return (
<TooltipProvider>
<FormProvider>
<div className="mb-4 flex gap-2">
<Button
type="button"
size="sm"
variant={way === 'builder' ? 'default' : 'outline'}
onClick={() => setWay('builder')}
>
Built with FormBuilder
</Button>
<Button
type="button"
size="sm"
variant={way === 'json' ? 'default' : 'outline'}
onClick={() => setWay('json')}
>
Loaded from JSON
</Button>
</div>
<Form
key={way}
config={(way === 'builder' ? builderConfig : (fromJson as FormConfig)) as FormConfig}
className="space-y-4"
/>
<div className="mt-6 space-y-2 rounded-md border bg-muted/40 p-4 text-sm">
<p>
Same config both ways: <strong>{String(same)}</strong>
</p>
<p>
<code>validateFormConfig(json)</code> →{' '}
<code>{JSON.stringify({ ok: good.ok, errors: good.errors })}</code>
</p>
<p>
Same JSON, one field without a <code>type</code> →{' '}
<code>{JSON.stringify({ ok: broken.ok, errors: broken.errors })}</code>
</p>
</div>
</FormProvider>
</TooltipProvider>
);
}The same form, both ways
The Code tab above has both. The builder version is the chain you already know; the JSON is the object .build() returns, written out. Rendering JSON is one cast, because a parsed file is not typed:
import { Form, type FormConfig } from '@saastro/forms';
import contact from './contact.json';
export const ContactForm = () => <Form config={contact as FormConfig} components={uiComponents} />;
What does not survive JSON
Everything in a config that is not data is lost the moment it is serialised, or never reaches the JSON at all:
- Functions —
onSuccess,onError,onStepChange, acustomsubmit’sonSubmit, a custom action’shandler,loadOptions, and function-valuedtransforms,hidden,disabledandreadOnly. The visual builder’s export drops them. - Zod schemas — a field
schemathat is a Zod object, and a form-levelformSchema. Use serialisableValidationRules(required,minLength,format…) andcrossFieldRulesinstead, and they travel. - React nodes — a field
iconthat is a ReactNode. - Plugins — attach them in code:
.usePlugins(manager)on the builder, or thepluginsprop of<HubForm>. trustedHtml—.trustedHtml()is a marker only code can create. A"trustedHtml": truein JSON is ignored with a warning and the block is sanitised like any otherhtmlfield.
A remote list is the serialisable alternative to loadOptions: use optionsSource (a URL spec) when the options must live in JSON.
When to use which
- FormBuilder when the form lives in your codebase: you get types and autocomplete, and you can use handlers, Zod, icons and plugins.
- JSON when the form is data: edited in the visual builder, stored in the Hub or your database, served per tenant, or validated on a server.
- Both is common: the JSON defines the fields and rules, and the host attaches handlers in code through
<Form>props (onSubmit) or<HubForm>(onSuccess,plugins).
Check a JSON config
validateFormConfig checks the shape of a serialised config and never throws. It returns { ok, errors }, each error being { code, path, message }. It is exported from @saastro/forms/validation, which has no React and runs in a Worker.
import { validateFormConfig } from '@saastro/forms/validation';
const { ok, errors } = validateFormConfig(JSON.parse(body));
if (!ok) return Response.json({ errors }, { status: 422 });
It accepts either a bare FormConfig or the envelope the builder writes, { version, formConfig }; with the envelope, version must exist and its major must be the one the package knows (FORM_SCHEMA_VERSION). Among other things it fails a field without a type, two steps with the same id, a step that lists a field that does not exist, and the rules FormBuilder.build() already enforces. A field type that is not in the registry is valid, because plugins register their own.