Forms: @sonordev/site-kit/forms
Sonor-managed forms with multi-step support, conditional logic, validation, anti-bot protection, and automatic CRM routing.
Usage
Option 1: Managed (simplest)
import { ManagedForm } from '@sonordev/site-kit/forms'
export default function ContactPage() {
return <ManagedForm formId="contact-form" />
}Fetches form config from Sonor, renders fields, handles submission, routes to CRM.
Experiences (4.0)
Since 4.0 that one line gets you the spotlight experience by default: the familiar layout, alive. A glowing ring visits the field you're in, completed fields earn a check, and each finished row collapses into a sentence the form says back ("Nice to meet you, Jordan." or "We'll follow up at jordan@…"), with an edit control to reopen it.
| Experience | What it is | How to get it |
|---|---|---|
spotlight | Default. Fields perform in place; answered rows become sentences | nothing to do |
stage | Accordion: one beat at a time on a single surface, answered beats settle into filled rows | experience="stage" |
classic | The plain grid form, no choreography | experience="classic" |
<ManagedForm formId="contact-form" /> // spotlight
<ManagedForm formId="contact-form" experience="stage" /> // accordion
<ManagedForm formId="contact-form" experience="classic" /> // opt outSonor can decide instead of the site, with no deploy on either side: set the
form's layout to classic, stage, or spotlight. An explicit
experience prop always wins over the config.
Three things hold for every experience:
- The lead is always capturable. SSR and no-JS render the plain classic form; the experience layers on after hydration. If its chunk never arrives, the form still works and still submits.
- Nobody pays for what they don't use. Experience code is loaded on
demand, so a
classicform downloads none of it. - Same engine. Identical validation, spam protection and CRM routing. An experience is a rendering, not a fork.
Editing what the form says back
The sentence for a row comes from the kit's built-in wording unless you write
your own in Sonor: set completion_message on a field (the first answered
field in the row that has one wins). Tokens:
| Token | Resolves to |
|---|---|
{value} | this field's answer |
{label} | this field's label |
{first_name} | the form's first-name answer, if any |
{any_field_slug} | that field's answer |
Welcome aboard, {first_name}. We'll reach you at {email}.
Leave it empty to keep the built-in sentence. Unknown or unanswered tokens render as nothing, never raw braces.
Option 2: Headless Hook (full UI control)
'use client'
import { useForm } from '@sonordev/site-kit/forms'
export function ContactForm() {
const {
fields, values, errors, setFieldValue, handleSubmit, toolAttributes, isSubmitting,
step, totalSteps, isMultiStep, nextStep, prevStep, isLastStep,
} = useForm('contact-form')
return (
<form {...toolAttributes} onSubmit={handleSubmit}>
{fields.map(field => (
<div key={field.slug}>
<label>{field.label}</label>
<input
value={String(values[field.slug] || '')}
onChange={(e) => setFieldValue(field.slug, e.target.value)}
/>
{errors[field.slug] && <span className="error">{errors[field.slug]}</span>}
</div>
))}
{isMultiStep && !isLastStep && <button type="button" onClick={nextStep}>Next</button>}
{isLastStep && <button type="submit" disabled={isSubmitting}>Submit</button>}
</form>
)
}Set a deadline for a submission
Use submissionPolicy="bounded" when an inquiry needs a clear time limit
and the visitor should check an unconfirmed send before trying again.
<ServerForm formId="inquiry" defer={false} submissionPolicy="bounded" />The policy is also available on ManagedForm, FormClient and the
useForm options. It gives the send up to 18 seconds after validation,
including verification and reading the receipt. Verification itself waits
up to eight seconds. A verification failure leaves the form editable and
allows another attempt. Once the request could have reached Sonor, a
missing receipt leaves the entered answers visible and disables another
send in that form. Ask the visitor to contact the business to check whether
the request arrived. A confirmed receipt still completes normally.
When verification is required, focusing or filling a field gives its browser library a head start, including before the interactive form loads. Send can use that setup as soon as it is ready.
If you render the controls with useForm or a render prop, show
submitError as an alert and disable Send when isSubmissionUnconfirmed
is true. The bounded policy takes precedence over submitRetries.
For a form at the top of a dedicated inquiry page, defer={false} starts
loading the interactive form as soon as the page hydrates. If someone
presses Send before it loads, the server-rendered form shows that it is
getting ready. A request queued for more than six seconds needs another
explicit send after the form is ready. The answers carry over.
Update an open draft
Use defaultValues to prefill a form when it first renders. To update a
draft after a visitor takes an action, pass valueUpdates with a new
revision and the fields that action should change:
<ManagedForm
formId="inquiry"
valueUpdates={estimateUpdate}
/>For example, a calculator button can set
{ revision: 1, values: { estimated_area: '125.50', estimate_source: 'calculator' } }.
Use a unique string or number for each action. Keep the latest request in
state so it can apply once the form loads. Only configured data fields
are updated. Use an empty string to clear a text or select value.
The form stays on its current step, keeps other answers and errors, and
clears errors for the updated fields. Reusing a revision has no effect.
Updates received while a submission is pending or after it succeeds are
discarded.
An option can set disabled: true to prevent visitors from choosing it
directly. A supplied draft value can still select it, for example when a
calculator provides the source of an estimate.
For forms where retrying an unconfirmed request could create a duplicate,
set submitRetries={0} to skip automatic transport retries. The supported
counts are zero, one and two. Omitted or invalid counts use two retries.
Definite authentication rejection can still trigger
credential refresh. HTTP rejection errors passed to onError carry a
numeric status; a network failure may have no status. Treat a lost or
missing submission receipt as unconfirmed before offering another attempt.
Google address suggestions
Unreleased: this option is prepared for the next Site Kit release.
Opt specific managed text fields into Google address suggestions with their exact Sonor slugs. The field must already exist in the form configuration:
<ManagedForm
formId="inquiry"
addressAutocomplete={{ fields: ['street_address'], includedRegionCodes: ['us'] }}
/>addressAutocomplete is also available on ServerForm and FormEnhancer.
It works in the classic, spotlight and stage experiences. fields accepts
one or more text-field slugs; other field types and unlisted fields keep
their existing behavior. includedRegionCodes optionally restricts
suggestions to up to 15 two-letter country codes. Omit it for unrestricted
suggestions. The exported type is AddressAutocompleteOptions.
The field keeps its label, controlled value, validation and managed submission. Choosing a suggestion fills that field with the formatted address; it doesn't fill separate city, state or postal-code fields. Visitors can keep typing or edit the selected address. Use the arrow keys and Enter to choose a suggestion, Escape to dismiss, or touch a result. Enter without an active suggestion keeps its normal form behavior.
Google code and Sonor's browser-key lookup start after field interaction; predictions start at three characters and are debounced. Each field owns its search session, and selection requests only the formatted address. Missing keys, failed loads, unsupported existing Google scripts and request errors leave manual entry available. Suggestions use Google Maps attribution and aren't stored in browser persistence. The selected address is submitted through the normal managed-form path.
Your Sonor installation needs a dedicated Google browser key with the
site's HTTP referrer allowed and Maps JavaScript API and Places API (New)
enabled. Sites still use their existing SONOR_API_KEY; they don't need
Sonor's Google server key. Keep your privacy notice consistent with address
queries being sent to Google. See Google's Autocomplete data guide.
This option enhances the built-in field renderers. A children render
function or a headless useForm layout owns its controls, so it doesn't
automatically receive a suggestion UI. Browser autofill tokens below stay
available for those controls.
Autocomplete on your own controls
ManagedForm puts the right autocomplete token on each field that has one, so
browser autofill, password managers and AI assistants know what the field wants.
When you draw the controls yourself, with useForm or the render prop below, ask
for the same token with autocompleteFor (since 8.0.0) and pass it to
autoComplete:
'use client'
import { useForm, autocompleteFor } from '@sonordev/site-kit/forms'
export function QuoteForm() {
const { fields, values, setFieldValue, handleSubmit, toolAttributes } = useForm('quote-request')
return (
<form {...toolAttributes} onSubmit={handleSubmit}>
{fields.map(field => (
<label key={field.slug}>
{field.label}
<input
name={field.slug}
autoComplete={autocompleteFor(field)}
value={String(values[field.slug] || '')}
onChange={(e) => setFieldValue(field.slug, e.target.value)}
/>
</label>
))}
<button type="submit">Request a quote</button>
</form>
)
}It returns a token such as given-name, email, tel, organization or
postal-code, or undefined when a field has no confident match, and React
leaves the attribute off for undefined. Only text, email and phone fields and
selects get a token, so a message box, a number, a date or a checkbox gets
undefined. To stay short, the example draws every field as a text input and
leaves out error messages and steps; draw each field with the control it calls
for and pass the same autoComplete={autocompleteFor(field)} to all of them.
Use it instead of typing tokens per field. It works the token out from the
field's type, slug and label, so your markup doesn't keep a list of its own that
can drift. @sonordev/site-kit/forms is a client module, like useForm, so call
autocompleteFor from a client component (a file that starts with
'use client'). Calling it in a Server Component fails the build.
To type a field you pass around, use UseFormReturn['fields'][number], or
AutocompleteField for a helper that only needs the token. Don't use the
FormField this entry exports: that's the shape formsApi takes (camelCase keys
such as fieldType), not what useForm returns.
Option 3: Render Prop
<ManagedForm formId="contact-form">
{({ fields, values, setFieldValue, submit }) => (
<MyCustomFormUI fields={fields} values={values} onChange={setFieldValue} onSubmit={submit} />
)}
</ManagedForm>Option 4: Programmatic API
import { formsApi, field, configureFormsApi } from '@sonordev/site-kit/forms'
configureFormsApi({ baseUrl: 'https://api.sonor.io', apiKey: 'sonor_...' })
const form = await formsApi.create({
projectId: 'xxx',
slug: 'newsletter',
name: 'Newsletter Signup',
formType: 'newsletter',
fields: [
field.email('email', 'Email', { isRequired: true }),
field.text('name', 'Name'),
],
})ManagedForm Props
interface ManagedFormProps {
formId: string // Form slug or ID
className?: string
onSuccess?: (submission: FormSubmitResult) => void
onError?: (error: Error) => void
children?: (renderProps: UseFormReturn) => ReactNode // Render prop override
}useForm Return
interface UseFormReturn {
form: ManagedFormConfig | null
isLoading: boolean
fetchError: Error | null
allFields: FormField[]
fields: FormField[] // Current step's fields
visibleFields: FormField[] // After conditional logic
values: Record<string, unknown>
errors: Record<string, string>
setFieldValue: (key: string, value: unknown) => void
step: number
totalSteps: number
isMultiStep: boolean
progress: number // 0-100
nextStep: () => void
prevStep: () => void
goToStep: (n: number) => void
canGoNext: boolean
canGoPrev: boolean
isLastStep: boolean
validate: () => boolean
// Resolves with what happened: { status: 'sent' | 'invalid' | 'failed' | 'busy' | 'next_step', ... }
submit: (options?: FormSubmitOptions) => Promise<FormSubmitOutcome>
// A ready-made <form onSubmit>: steps or submits, and answers an AI agent (see below)
handleSubmit: (event: FormEvent<HTMLFormElement>) => void
// WebMCP attributes for your <form>; null until the config loads
toolAttributes: { toolname: string; tooldescription: string } | null
isSubmitting: boolean
isComplete: boolean
reset: () => void
}Field Types
text, email, phone, tel, number, textarea, select, multi-select, checkbox, radio, date, time, datetime, file, signature, rating, slider, hidden, heading, section_header, paragraph
Field Builder
field.text(slug, label, options?)
field.email(slug, label, options?)
field.phone(slug, label, options?)
field.textarea(slug, label, options?)
field.select(slug, label, { options: [{ value, label }] })
field.date(slug, label, options?)
field.checkbox(slug, label, options?)
field.rating(slug, label, options?)Form Routing
Submissions auto-route based on form_type:
| Form Type | Routes To | Use Case |
|---|---|---|
prospect / lead-capture / contact | CRM Contacts | Sales inquiries, quotes |
support | Support Tickets | Help requests |
feedback | Feedback entries | User feedback |
newsletter | Email Subscribers | Newsletter signups |
custom | Form Submissions only | Custom handling |
Spam protection
Sonor screens every submission on its side, and there's nothing to configure.
It only accepts a submission with evidence that a real browser rendered the
page, which <ManagedForm> and useForm send automatically. A hand-rolled
fetch to the forms API, or a proxy through your own API route, can't send
it, so Sonor refuses those before anything is written: the visitor sees an
error and you get no lead. Submit through site-kit, and define the form's
fields in Sonor so both can render and validate them.
Agent-ready forms (7.2.0)
People increasingly ask an AI assistant to fill out a form for them: a quote request, a booking, a newsletter signup. Assistants act on what the page's markup says each control is, so managed forms now say it clearly. There's nothing to configure.
- Autocomplete tokens. Name, email, phone, company, website and address
fields carry the right
autocompletetoken (given-name,email,tel,organization,url,postal-code, ...), read from the field's CRM destination in Sonor, then its type, slug and label. Browser autofill and password managers use the same tokens. A headless form adds them withautocompleteFor(see Autocomplete on your own controls). - Accessible wiring. Error and help text are tied to their control
(
aria-describedby), an errored control says so (aria-invalid), radio and checkbox groups are named by their question, and rating stars by their value. - WebMCP. Every interactive managed form carries the declarative WebMCP
attributes (
toolname,tooldescription), so a browser agent that supports WebMCP can treat it as a tool. It fills the same fields a person would, and the submit runs the same validation. There's notoolautosubmit: the assistant fills the form and the person it's helping presses Send. Browsers without WebMCP ignore the attributes. - Agent-sent leads are tagged. When the browser reports that an agent
pressed submit (
SubmitEvent.agentInvoked), the submission carries that flag and the lead is tagged in Sonor, so you can see how those leads compare over time, and Sonor's spam screening takes it into account. The agent is handed the outcome of its submit (respondWith). - Nothing typed before the form loads is lost.
ServerFormrenders the form in the page HTML and loads the interactive version at idle. Since 7.2.0, typing into the server-rendered form starts that upgrade at once and what was typed carries over, and a Send pressed before the upgrade is held and sent the moment it lands. The server-rendered Send button stays disabled until the page can catch the click.
With useForm, spread toolAttributes on your <form> and use
handleSubmit as its onSubmit to get the WebMCP behavior and the agent-sent
tag, and add autocompleteFor to your controls for the autofill tokens.
ServerForm's enhance prop is ignored since 7.2.0. Only the interactive
form can send a managed form, so enhance={false} only ever produced a form
that silently went nowhere.
Private documents (8.6.0+)
A managed file field with validation.private_attachments: true uses the
private document control. Set validation.max_files from one to four. It
accepts PDF, JPEG, PNG and WebP, up to 10 MB per file, with drag and drop,
upload status, removal and retry. A required field stays unanswered until
every selected file has uploaded successfully.
This requires the Sonor API private attachment migration and endpoints plus
the Sonor app's authorized document download controls. It never falls back
to the public media upload endpoint. The server-rendered file control stays
disabled until enhancement, so it can't accidentally use a public upload.
Keep the private flag in ServerForm's initialConfig; if configuration is
unavailable, render a contact fallback instead of fetching an unmarked field.
Uploads return signed, expiring grants. Submissions store private document references, and the Sonor app obtains short-lived download URLs only after checking access to the submission. Do not display those references as links.
Date and file controls load on demand. They also finish loading when React Strict Mode restarts their effects during development.
Styles
import '@sonordev/site-kit/forms/styles.css' // Optional default stylesAll components use .sk-form__* class names. Override with className prop or CSS variables.
Purpose-aware submission and tracking (8.9)
Managed form values can still submit when measurement is denied or unavailable. The canonical submit helper refreshes optional measurement context before every network attempt, including a credential-refresh retry. A withdrawal removes that context while preserving the functional request.
GA4 cookie reads, UTM fields and existing analytics visitor/session IDs follow the analytics purpose policy. Advertising grants alone don't authorize those reads. The separate opaque measurement proof can accompany an eligible request for server verification. A managed experiment exposure reference is included only after the measurement endpoint accepted that exposure. The server still verifies its subject, scope and current consent against the canonical accepted submission. The browser doesn't post a form conversion.
The existing form analytics hook uses the shared analytics gate for starts, field interactions, steps, completion and abandonment. Unknown required consent and explicit denial stop collection. Regrant creates a fresh tracking period without replaying denied interactions. Trackers in the same current period still share one row. Legacy sites without an analytics requirement keep their first-party unknown-policy behavior.
Connect your maintained consent manager through the Resonance adapter. Keep it separate from newsletter subscriptions and form follow-up permission.
Functional form submission stays available without optional measurement. Current measurement context is resolved at each actual attempt, including after transport loading or credential refresh. A withdrawn or stale context is omitted from the functional request; it isn't recovered from an old queued grant.