Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
SDK:
FormsServiceTypes: SDK Types
Prerequisites
A client exported from
@/lib/lynkow(Add Lynkow to an Existing Project)A form created in the dashboard, and its slug (
contactbelow)
Fetch the form
import { lynkow } from '@/lib/lynkow'
const form = await lynkow.forms.getBySlug('contact')
form.schema.fields // FormField[], in display order
form.schema.settings.submitLabel // "Send message", optional
form.locale // The translation served, reused on submitform.schema is an object: the fields are in form.schema.fields and the settings in form.schema.settings. Only an active form resolves; any other slug throws a LynkowError with code NOT_FOUND.
Render the fields
Each field has an id, a type, a label, and optionally required, placeholder, description, defaultValue, options and validation. The id is generated by the dashboard (field_1764776796820): read it from the schema, never hard-code a name like 'email'.
| Element |
|---|---|
|
|
|
|
|
|
|
|
|
|
| one |
| one box without |
|
|
|
|
The renderer names every input after the field id, so a FormData built from the <form> is keyed the way submit() expects.
// components/form-field.tsx
import type { FormField } from 'lynkow'
const INPUT_TYPES: Partial<Record<FormField['type'], string>> = {
datetime: 'datetime-local',
rating: 'number',
}
export function FormFieldInput({ field, error }: { field: FormField; error?: string }) {
const v = field.validation
const props = {
id: field.id,
name: field.id,
required: field.required,
placeholder: field.placeholder,
defaultValue: field.defaultValue === undefined ? undefined : String(field.defaultValue),
}
let input: React.ReactNode
switch (field.type) {
case 'textarea':
input = <textarea {...props} minLength={v?.minLength} maxLength={v?.maxLength} rows={5} />
break
case 'select':
input = (
<select {...props}>
<option value="">Select...</option>
{field.options?.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
)
break
case 'radio':
case 'checkbox':
input = field.options?.length ? (
<fieldset>
{field.options.map((o) => (
<label key={o.value}>
<input type={field.type} name={field.id} value={o.value} />
{o.label}
</label>
))}
</fieldset>
) : (
<input type="checkbox" name={field.id} id={field.id} required={field.required} />
)
break
case 'file':
input = <input id={field.id} name={field.id} type="file" required={field.required} />
break
default:
input = (
<input
{...props}
type={INPUT_TYPES[field.type] ?? field.type}
minLength={v?.minLength}
maxLength={v?.maxLength}
min={v?.min}
max={v?.max}
pattern={v?.pattern || undefined}
title={v?.message || undefined}
/>
)
}
return (
<div className={`form-field form-field--${field.width ?? 'full'}`}>
{field.type !== 'hidden' && <label htmlFor={field.id}>{field.label}{field.required && ' *'}</label>}
{input}
{field.description && <small>{field.description}</small>}
{error && <span role="alert">{error}</span>}
</div>
)
}field.width is 'full', 'half' or 'third' (absent means full): map the three classes to column widths in your CSS. The validation attributes give you client-side checks for free; the API runs the same rules again on submit.
Submit
submit() sends JSON, so every value is a string, a number or a boolean, keyed by field id. The API drops any key that matches no field id, so a payload keyed by names arrives with its required fields missing.
// components/form-helpers.ts
import type { FormField, FormSubmitData } from 'lynkow'
export function readValues(
fields: FormField[],
formData: FormData,
uploads: Record<string, string> = {} // field id -> URL or media id of a file you uploaded
): FormSubmitData {
const data: FormSubmitData = {}
for (const field of fields) {
if (field.type === 'file') {
if (uploads[field.id]) data[field.id] = uploads[field.id]
} else if (field.type === 'checkbox' && !field.options?.length) {
if (formData.has(field.id)) data[field.id] = true
} else {
// getAll() keeps every ticked box of a checkbox group
const values = formData.getAll(field.id).filter((x): x is string => typeof x === 'string')
if (values.length > 0) data[field.id] = values.join(',')
}
}
return data
}const result = await lynkow.forms.submit('contact', readValues(form.schema.fields, formData), {
locale: form.locale,
formStartedAt, // Date.now() taken when the form was shown
})
// { success: true, message: string, redirectUrl?: string }The SDK adds the anti-spam fields _hp (always empty) and _ts (a timestamp) to every submission. Unless the site uses reCAPTCHA, the API refuses a _ts younger or older than the window set in the site's spam settings (3 seconds to 1 hour by default). _ts defaults to the moment the client was created, so pass formStartedAt whenever your client outlives a page view, and always from server code.
The submission is stored when submit() resolves. The response carries no submission id. message is the form's success message, or a default one in the form's language. redirectUrl is present only when the form has one.
A form whose schema.settings.requireAuth is true accepts only a signed-in customer. The SDK sends the customer session it holds (Guide 20).
After submission
Show result.message, then follow redirectUrl when there is one. Check its protocol before navigating, so that a value never runs as a javascript: URL.
// components/form-helpers.ts
export function redirectTarget(redirectUrl?: string): string | null {
if (!redirectUrl) return null
try {
const url = new URL(redirectUrl, window.location.href)
return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null
} catch {
return null
}
}
const target = redirectTarget(result.redirectUrl)
if (target) window.location.assign(target)reCAPTCHA
A token is required when the site or the form enables verification. The site policy wins: read it from the public spam settings, and fall back to the form's own fields.
import type { Form } from 'lynkow'
type Policy = { version: 'v2' | 'v3'; siteKey: string } | null
export async function verificationPolicy(form: Form): Promise<Policy> {
const res = await fetch(
`https://api.lynkow.com/storefront/${process.env.NEXT_PUBLIC_LYNKOW_SITE_ID}/spam-settings`
)
const { data: site } = await res.json()
if (site.protectionMethod === 'recaptcha' && site.recaptchaEnabled && site.recaptchaSiteKey) {
return { version: site.recaptchaVersion, siteKey: site.recaptchaSiteKey }
}
if (form.recaptchaEnabled && form.recaptchaSiteKey && form.recaptchaVersion) {
return { version: form.recaptchaVersion, siteKey: form.recaptchaSiteKey }
}
return null
}For a v3 policy, load https://www.google.com/recaptcha/api.js?render=<siteKey> and mint the token with the action form_submit. A token with any other action, submit included, is refused.
const recaptchaToken = await new Promise<string>((resolve, reject) =>
window.grecaptcha.ready(() =>
window.grecaptcha.execute(policy.siteKey, { action: 'form_submit' }).then(resolve, reject)
)
)
await lynkow.forms.submit('contact', values, { locale: form.locale, recaptchaToken })For a v2 policy, render the v2 checkbox with the same site key and pass grecaptcha.getResponse() as recaptchaToken.
Errors
|
| Cause |
|---|---|---|
| per field in | A value breaks a field rule |
|
|
|
|
|
|
|
| Missing or rejected token |
|
| The form is closed; |
|
| The form requires a signed-in customer |
Each entry of error.details carries the field id in field, the same key as the submitted value:
import { isLynkowError } from 'lynkow'
try {
await lynkow.forms.submit('contact', values, { locale: form.locale, formStartedAt })
} catch (error) {
if (isLynkowError(error) && error.code === 'VALIDATION_ERROR') {
const fieldErrors: Record<string, string> = {}
for (const detail of error.details ?? []) {
if (detail.field) fieldErrors[detail.field] = detail.message
}
setErrors(fieldErrors)
} else {
setGlobalError(isLynkowError(error) ? error.message : 'Something went wrong.')
}
}Guide 12 covers LynkowError in general.
Complete component
// components/dynamic-form.tsx
'use client'
import { useEffect, useRef, useState } from 'react'
import { isLynkowError, type Form, type FormSubmitResponse } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
import { FormFieldInput } from './form-field'
import { readValues, redirectTarget } from './form-helpers'
export function DynamicForm({ slug }: { slug: string }) {
const [form, setForm] = useState<Form | null>(null)
const [errors, setErrors] = useState<Record<string, string>>({})
const [globalError, setGlobalError] = useState<string | null>(null)
const [result, setResult] = useState<FormSubmitResponse | null>(null)
const [loading, setLoading] = useState(false)
const startedAt = useRef(Date.now())
useEffect(() => {
lynkow.forms.getBySlug(slug).then(setForm)
}, [slug])
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
if (!form) return
setErrors({})
setGlobalError(null)
setLoading(true)
try {
const res = await lynkow.forms.submit(
slug,
readValues(form.schema.fields, new FormData(e.currentTarget)),
{ locale: form.locale, formStartedAt: startedAt.current }
)
setResult(res)
const target = redirectTarget(res.redirectUrl)
if (target) window.location.assign(target)
} catch (error) {
if (isLynkowError(error) && error.code === 'VALIDATION_ERROR') {
const fieldErrors: Record<string, string> = {}
for (const d of error.details ?? []) if (d.field) fieldErrors[d.field] = d.message
setErrors(fieldErrors)
} else {
setGlobalError(isLynkowError(error) ? error.message : 'Something went wrong.')
}
} finally {
setLoading(false)
}
}
if (!form) return <p>Loading form...</p>
if (result) return <p role="status">{result.message}</p>
return (
<form onSubmit={handleSubmit}>
{form.schema.fields.map((field) => (
<FormFieldInput key={field.id} field={field} error={errors[field.id]} />
))}
{globalError && <p role="alert">{globalError}</p>}
<button type="submit" disabled={loading}>
{form.schema.settings.submitLabel ?? 'Submit'}
</button>
</form>
)
}Add the token from the reCAPTCHA section to the submit() options when verificationPolicy(form) returns a policy. Several <DynamicForm> on one page work independently.
Languages
Read and submit the same translation:
const form = await lynkow.forms.getBySlug('contact', { locale: 'pt-BR' })
// form.isFallback is true when no pt-BR translation exists: form.locale names the one served
await lynkow.forms.submit('contact', values, { locale: form.locale, formStartedAt })The read follows the fallback contract, and the submission is stored against the translation the visitor filled in. Pass fallback: false to getBySlug() to get NOT_FOUND instead of another language; submit() never sends fallback, so always submit with form.locale. Without a locale, a multi-language site serves its default-locale translation.
Cache
With a client created with cache: true, forms.getBySlug() is kept in memory for 10 minutes per slug and locale; lynkow.forms.clearCache() empties it. submit() is never cached. Without cache: true only your framework's cache applies.
Next Steps
Guide 5: Customer Reviews - the same submit flow for reviews
Guide 11: Webhooks & Cache Revalidation - react to
form.submittedon your server