# forms
Wires `@payloadcms/plugin-form-builder` (forms + form-submissions collections) and
provides `submitForm` — a server function (called from a Server Action) that chains:
rate limit → Turnstile → validation against the form definition from the panel → storing the submission.
Emails are sent by the form-builder (Forms → Emails) through `mailAdapter()`.
## ⚠️ RULE: the form COMES FROM the builder in the panel (mandatory)
**Forms are built by the editor in the panel** (Forms collection), NOT by the developer in code.
This is a CMS — the client defines fields, labels, messages and the recipient. The front end
only RENDERS the form from the panel and submits it through `submitForm`.
**NEVER build your own hard-coded form** — with hand-written
fields, labels in JSX, your own validation. It breaks "nothing hard-coded" (the client cannot
change fields or texts) and skips the plugin's whole mechanism (Turnstile, rate limit,
GDPR consent, notifications).
| WRONG (your own form) | RIGHT (the plugin's builder) |
|---|---|
| ` ` in JSX | fields from the Forms collection (panel) |
| labels/messages in code | labels per language in the panel |
| your own validation/submit | `submitForm` (Turnstile+consent+mail) |
| the client cannot change the form | the client edits fields in the panel |
**How to do it right:** the editor creates a form in the Forms collection → a block renders it
with `` → it is submitted through `sendForm` (`createSubmitAction` → `submitForm`). Fields,
labels, messages, recipient — all from the panel.
If a form needs a field the builder does not have — add it through the `fields`
configuration (see below) or extend the plugin. Do NOT hard-code your own form.
## Dependency
```json
"dependencies": { "@payloadcms/plugin-form-builder": "3.94.1" } // same version as payload
```
(the plugin's peer dependency: `^3.90.2`)
## Config (payload.config.ts)
```ts
iapl({
forms: {
redirectRelationships: ['pages'], // a form can redirect to a Page
// fields: { date: false, … }, // default: text, textarea, email, number, date,
// // time, select, radio, checkbox, checkboxGroup, message, step
},
})
```
`forms` options (`FormsOption`):
| Option | Default | Description |
|---|---|---|
| `adminGroup` | `'Forms'` | group in the panel; `false` = Payload's default; `admin.group` in overrides wins |
| `attachments` | `false` | files on forms: adds the **File** field; a file is checked, e-mailed to the company and dropped — never stored ("Files" below) |
| `fields` | see below | builder field types; `false` turns a type off, an object (block) replaces it; `true` = the default IAPL block |
| `redirectRelationships` | — | collections a form can redirect to |
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
| `emailLayout` | `false` | nice emails + the Site settings → E-mails tab |
| `beforeEmail` | — | the form-builder's `beforeEmail` (after the layout, when `emailLayout`) |
| `consentFieldName` | `'consent'` | name of the GDPR consent field for `submitForm` / `createSubmitAction` (the call's argument wins) |
`payment` is always off — `fields: { payment: true }` does **not** turn it on (the value `true`
is skipped); it can only be turned on by passing a block object. `country` / `state` keep the form-builder's
default settings.
Adds the **Forms** (the editor builds forms) and **Form Submissions**
(submissions) collections — in the panel in the **Forms** group with the labels "Form/Forms" and
"Submission/Submissions" (no overrides needed in the project). A different group:
`forms: { adminGroup: 'Content' }`; Payload's default: `adminGroup: false`. Emails after a submission are sent by the form-builder according to the form's **Emails**
tab — through the adapter from `email:` in the config (the "Emails" section below).
## Front end — RenderForm (recommended, one line)
The whole front end of a panel form lives in the plugin. The project has the block and the classes:
```tsx
// src/blocks/FormBlock/Component.tsx
import { RenderForm } from '@intecion/ipal-kit/rsc'
```
- `form` — the relation from the block (depth ≥ 1; an ID or null → nothing renders),
- `action` — `sendForm` from `createSubmitAction` (below), `texts` — `getFormTexts(locale)` from `lib/content`
(Form messages → Form messages),
- `classNames` — the **only** place for looks (`src/components/forms/formClasses.ts`, template in iapl-form);
the plugin has no styles at all. Keys: `form, progress, step, stepTitle, stepDescription, fields,
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
next, submit, success, required, fixed, file, help, fileList, fileItem, fileRemove`. For CSS there are also `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
- options: `requiredMark` (e.g. `" *"`), `converters` / `richTextClassName` (rich text looks),
`linkOptions` (`await getLinkOptions(locale)` — redirect to a page from the panel), `turnstileTheme`
(default `'page'`), `values` (below).
`RenderForm` (server) renders **message** blocks and the confirmation through `RenderRichText`, binds
the action to the form and the language, resolves the redirect and gives the browser **only the public part of the
form** — the Local API reads with `overrideAccess`, so the document has the Emails tab (company addresses);
a hand-written `` used to send them in the HTML. Underneath it is `BuilderForm` (client).
### Field types in the panel
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state as text), and **File** when `forms.attachments` is on ("Files" below).
Turning a type off: `forms.fields: { date: false }`.
**Placeholder** (1.11.1): text, email, textarea and number have a localized "Placeholder" field — a hint
in the empty field ("e.g. 10:00–12:00"). `BuilderForm` and `useBuilderForm` (`getInputProps`, `getTextareaProps`)
pass it on by themselves. Your own block with this field: `withPlaceholder(block)` / `placeholderField` from the root;
the time block: `timeBlock`. New fields in form blocks = a migration (`pnpm payload migrate:create`).
| Type | Value | The server checks |
|---|---|---|
| radio, select | one value | only values from the panel |
| Checkbox group | `string[]` (stored as "www, seo") | only values from the panel, no duplicates, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | a real date |
| time | `HH:MM` (` `) | a time 00:00–23:59 |
| File | files (never a text value) | field, count, size, type by content — "Files" below |
| Step | — (split) | not a field |
### Multi-step form
A **Step** block (title, description, per language) starts a new screen; fields above the first Step are screen 1.
`BuilderForm`: "Step 1 of 3" (`stepOf`), Next validates only the current step, Back keeps the
values, focus moves to the new step, Turnstile is on the last step, a field error from the server goes back
to the step with that field. Button texts: Form messages → `next`, `back`, `stepOf`.
### Conditional fields and steps ("Show only when")
Every form block (built-in, **Checkbox group**, **Step**, message) has a
**Show only when** group in the panel (`showWhen`): `field` — the technical name of another field, `values` — option values,
comma-separated (empty = when that field is filled in / checked). An empty `field` = always visible.
- On a field: the field shows up only for a matching answer (e.g. "What sets the deadline?"
only when `deadline = fixed`).
- On a **Step**: the whole step (with its fields) drops out when the condition does not match — the following steps are renumbered
("Step 2 of 3"). This is how a brief is built: screen 1 picks areas (Checkbox group), each following
Step has `showWhen: { field: 'areas', values: 'web' }`.
- A field in a hidden step is hidden, even when its own condition matches; a condition that points at a hidden field
does not match either. The name of a field that does not exist (a typo) or a cycle hides the field — you can see it in the preview.
- One shared rule `visibleFields(fields, values)` (`@intecion/ipal-kit`, `/client`) — the browser
(`useBuilderForm`/`BuilderForm`: what to show, validate and send) and the server (`validateSubmission`):
a hidden field **is not required and is not stored**, even when someone sends it by hand.
Exception: the GDPR consent field (`consent`) is always enforced — a condition cannot turn it off.
- The `FieldCondition` type (`{ field, values }`) for your own markup on `useBuilderForm`; `splitSteps(fields, isShown)`
skips hidden fields and steps, keeping the original `index` (message blocks render by it).
- The new group = columns `show_when_field` / `show_when_values` in the form block tables →
after updating, generate a migration (`payload migrate:create`).
### Field values from the page (`values`, 1.11.0)
The page knows a field value the visitor does not type — the chosen product variant, category, offer.
The editor adds a plain text field to the form (e.g. `subject`, "Regarding"), and the page fills it:
```tsx
// a value known on the server (the "coming soon" category)
```
A field with `values` is shown read-only (``, class `classNames.fixed`, `data-ipal="form-fixed"`),
sent like any other field and validated by the server against the definition from the panel. Names not in the form are skipped.
The value is in the first HTML (SSR), not only after hydration.
A value that changes in the browser (a configurator): the server prepares the form with `prepareBuilderForm` (`/rsc`) —
the public part (`publicForm`, without the Emails tab), the rendered message blocks and confirmation, the action bound
to the form and the language, the redirect target — and a client component renders `BuilderForm` with the current `values`:
```tsx
// server
const form = prepareBuilderForm({ form: catalog.inquiryForm, action: sendForm, locale })
// client ('use client')
```
`publicForm(form)` (`/rsc`) — just the public part of the document, when you build your own hand-off to the client. Never
pass the raw form document to the browser.
### An unusual form — without copying the engine
1. `renderField` (BuilderForm in a `'use client'` file) — replaces selected fields:
`renderField={({ field, defaultRender }) => field.name === 'budget' ? : undefined}`.
2. `useBuilderForm({ form, action, texts })` — all the logic, the markup is yours: `steps`, `step`,
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `isFixed`, `getFieldProps`,
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
`TurnstileWidget`; for a File field `getFileProps`, `getFiles`, `removeFile`, `helpId`. Example: `iapl-form/resources/CustomForm.example.tsx`.
3. Pure logic (also on the server / in tests): `splitSteps`, `initialBuilderValues`,
`validateBuilderFields`, `stepOfField`, `inputFields`, `visibleFields`, `autoCompleteFor` (autocomplete hint from the field's type and name),
`fileFieldRules`, `fileFieldError`, `formatFileSize` (File field).
`useOptionalTurnstile()` — like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing.
## Files — sent by e-mail, never stored (`attachments`)
A visitor attaches a file (a CV, a specification); the company gets it **as an attachment of the notification
e-mail**. The site does not keep it: no upload collection, no bucket, no disk, no download route. The submission
records only the file's name, type and size and whether the mail server took the message.
### Set up
```ts
// payload.config.ts
iapl({ forms: { attachments: true } }) // adds the File field to the form builder
```
1. Turn the option on (above). Postgres / SQLite projects: `pnpm payload migrate:create` (new block and submission
columns). MongoDB: nothing. Then `pnpm generate:types`.
2. In the panel (or the form seed) add a **File** field to the form: field key, label, help text, required, allowed
file types, maximum size (MB), maximum files, "Show only when".
3. The form needs an e-mail whose **To / CC / BCC are fixed addresses** (Forms → the form → E-mails) — that e-mail
carries the file. The panel refuses to save a form with a File field and no such e-mail.
4. Nothing else: `RenderForm` / `BuilderForm` render the field, and the plugin registers the endpoint the browser
posts files to (`POST /api/ipal/forms/submit`). No route file, no `next.config` change, no env variable.
5. Check that your mail server takes the size: **Site integrations → E-mail sending → Test e-mail** with
"Attach a 10 MB test file" ticked ([email.md](./email.md) "Attachments").
**Verify:** submit the form with a PDF → the confirmation shows; the company e-mail has the file attached and the
line "…was not checked for viruses"; the confirmation e-mail to the visitor has no file; Form Submissions shows
**Files** (name, type, size) and **File delivery: Handed to the mail server**. Rename a `.exe` to `.pdf` and submit →
the File field shows "The file … was refused: …", nothing is stored or sent.
### Options (`FormAttachmentsOption`)
| Option | Default | Description |
|---|---|---|
| `maxSizeMB` | `10` | ceiling for a field's "Maximum size (MB)" — the editor cannot set more |
| `maxTotalMB` | = `maxSizeMB` | ceiling for all files of one submission together (= one e-mail) |
| `maxFiles` | `3` | ceiling for a field's "Maximum files" |
| `fileTypes` | built-in | add a type (`{ dwg: { label, extensions, mimeType, detect } }`), replace one, or remove one (`{ rtf: false }`) |
| `allowRisky` | `[]` | extensions from the refused list this project accepts after all, e.g. `['zip']` (the type must also exist in `fileTypes`) |
| `scan` | — | antivirus hook: `async ({ name, type, size, data, field }) => ({ ok })` — `ok: false` (or a throw) refuses the file |
| `strictPdf` | `false` | refuse PDFs that declare JavaScript, launch actions or embedded files (a byte search) |
| `notice` | built-in text | the "not checked for viruses" line in the e-mail: `false` = none, a string or `(locale) => string` = your own |
| `maxConcurrent` | `2` | file submissions handled at once per instance (each holds its files in memory); more get the "too many attempts" message; `0` = no guard |
| `path` | `'/ipal/forms/submit'` | endpoint path under the API route |
| `submit` | `{}` | the endpoint's gates, same meaning as in `createSubmitAction`: `maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`; `allowedOrigins` (other origins allowed to post, e.g. a front end on another domain); `idleTimeoutMs` (default `30000`: no byte of the upload for this long → the request is given up, `0` = off) and `timeoutMs` (default `300000`: ceiling for the whole request, `0` = off) **While Turnstile cannot check (wrong or missing secret, Cloudflare down) this endpoint refuses the submission by default** — `forms.turnstileOnConfigError: { files: 'allow' }` or `submit.turnstileOnConfigError: 'allow'` changes it (turnstile.md) |
Built-in types (`FORM_FILE_TYPES`): PDF, DOC, DOCX, ODT, RTF, XLS, XLSX, JPG, PNG, WebP. A new field has PDF, DOC and
DOCX ticked.
### The security wall — in this order
Each step runs before the next; a failure ends the request and nothing after it happens.
1. Same origin (`Origin` / `Sec-Fetch-Site`), `multipart/form-data`.
2. **Rate limit** per IP — from the headers, before any of the body is read.
3. A request that declares a body over the limit is refused unread.
4. Concurrency guard (`maxConcurrent`).
5. The answers are read (they come first in the request): **honeypot** → fake success; **Turnstile**; **field
validation and GDPR consent** — exactly the checks of a text-only form.
6. The form has a visible File field under that key, and an e-mail that can carry a file.
7. Per file, before its bytes: **count**, then the **name** — the last extension must be one of the field's types;
a refused extension anywhere in the name (`cv.pdf.exe`, `cv.exe.pdf`) or a second known extension
(`cv.pdf.docx`) is refused.
8. **Size** is counted while the file is read (per file and per submission); the read stops keeping data at the limit.
9. **Signature** of the first bytes must match the type the extension claims; programs (Windows, Linux, macOS,
`#!` scripts) are refused under any name.
10. Whole-file checks: DOCX / XLSX / ODT must be a ZIP whose directory lists the entries that type requires
(read without unpacking — no zip-bomb exposure), with no macro project, no encrypted entry and no program
inside; DOC / XLS must not carry a VBA macro storage.
11. `scan`, when the project provides one.
12. The e-mail is sent, the buffers are released.
**An upload that breaks off, stalls or never ends** is given up at once: the connection dropped (400), no byte
arrived for `submit.idleTimeoutMs` (408), the whole request ran past `submit.timeoutMs` (408), or a body without a
declared length went over the ceiling (413 — the read stops there). On every way out the endpoint lets go of what
it held: the buffered bytes, its slot in the concurrency guard and the attempt key, so the next upload — and the
browser's retry — work.
**Refused by default whatever the field allows** (`RISKY_FILE_EXTENSIONS`): programs and scripts (`exe`, `dll`,
`msi`, `bat`, `js`, `ps1`, `sh`, `jar`…), macro-enabled Office files (`docm`, `xlsm`, `pptm`…), archives and disk
images (`zip`, `rar`, `7z`, `iso`…), HTML, SVG and XML.
**What this is not.** It is **not an antivirus**. The checks stop the wrong *kind* of file; they cannot tell a
harmful PDF or DOC from a harmless one. The macro check for legacy `.doc` / `.xls` is **best-effort**: it finds
ordinary macro-enabled documents, not one built to hide. Need scanning → plug a scanner into `scan`. The e-mail
says so to the recipient ("This file came from a public form and was not checked for viruses.").
The attachment's name is rebuilt, never passed through: no path, no control or bidi characters, at most 80
characters, the extension of the detected type (`CV Jan Kowalski.pdf`; an empty name becomes `attachment.pdf`).
### Limits
- The limit a visitor sees and the server enforces is the lowest of: the field's value, `attachments.maxSizeMB`,
and what the e-mail transport can carry. With the Intecion mail service that is what the service reports (10 MB
unless Intecion set another number); on Microsoft Graph without the large-file path and without SMTP
settings about 2.8 MB ([email.md](./email.md) "Attachments"). The form document read through Payload
carries the result per File field in `resolved` (`maxSizeMB`, `maxTotalMB`, `maxFiles`, `accept`, `extensions`,
`typeLabels`) and `fileSubmitUrl` — `RenderForm` passes them on; nothing to wire.
- **Request size:** files do not go through the Server Action, so `serverActions.bodySizeLimit` (1 MB by default)
does not apply. The proxy from `createProxy` does not match `/api` (its buffer limit of 10 MB would otherwise
apply — keep `/api` out of your matcher). Coolify's Traefik has no body limit by default; an nginx in front
needs `client_max_body_size 12m`. [deployment.md](./deployment.md) "Form files".
- Memory: a file is held in memory while it is checked and sent (about 2.4 × its size during the send); nothing
touches the disk.
### E-mails
- The file is attached to **every e-mail of the form whose To, CC and BCC are fixed addresses from the panel**.
An e-mail addressed with a placeholder (`{{email}}` — the confirmation to the visitor) **never** gets it.
- The answers get a text row per File field — `CV Jan Kowalski.pdf (2.1 MB)` — so `{{attachment}}`, `{{*}}`,
`{{*:table}}` and the readable summary of `emailLayout` show the file name in every e-mail.
- `forms.beforeEmail` still runs on every e-mail (before the files are attached). A custom e-mail adapter must
support `attachments` (nodemailer's shape); `mailAdapter()` does on both transports.
### When the e-mail cannot be sent
The file is not kept, so there is nothing to retry with. Then:
- the **visitor** sees an error **at the File field** — Form messages → **File not sent** ("We could not send the
file "cv.pdf". Choose a smaller file or another format and try again.") — keeps their answers and the selected
file, and can try again. The mail server's own words never reach the visitor. No confirmation e-mail goes out;
- **staff** get the notification once more **without** the file: "The visitor attached a file: … but it could not
be sent. Ask them to send it again.";
- the **submission** is stored and marked **File delivery: Not sent**, with a note (the mail server's reason). The
Form Submissions list shows the "File delivery" column.
"Handed to the mail server" means the mail server accepted the message. A later bounce (the recipient's server
refuses it) cannot be seen by the site; it arrives in the sender mailbox.
**No duplicates:** each submit carries an attempt key from the browser; a repeated request with the same key
(double click, a resend by the browser or a proxy) gets the first answer and sends nothing again. The plugin sends
each e-mail once — there is no automatic resend.
### What the visitor is told
**When a submission fails because of the file, the message says it is the file, why, and what to do** — and it
shows at the File field (the result carries `field`). Everything the visitor typed stays in the form.
| Problem | Code | Text (Form messages → Files) | English default |
|---|---|---|---|
| too large | `kind: 'file_too_large'` (`file`, `max`) | `fileTooLarge` | The file "cv.pdf" is too large. Choose a file of up to 10 MB. |
| a format the field does not take | `kind: 'file_type'` (`file`, `types`) | `fileType` | The file "cv.txt" is in a format we do not accept. Choose one of: PDF, DOC, DOCX. |
| refused: a program, an archive, macros, a doubled extension, content that does not match the type, the scanner said no | `kind: 'file_refused'` (`file`, `types`) | `fileRefused` | The file "cv.docx" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file (PDF, DOC, DOCX). |
| too many files | `kind: 'file_count'` (`max`) | `fileCount` | Too many files in "Attachment". Remove some: the limit is 1. |
| the e-mail with the file could not be sent | `reason: 'delivery'` (`field`, `file`) | `fileNotSent` | We could not send the file "cv.pdf". Choose a smaller file or another format and try again. |
- On a File field that is **not required**, every one of these ends with `fileOptional` — "You can also send the
form without the file." (the result carries `optional: true`).
- A required File field left empty is `kind: 'required'` → the ordinary field text ("Check the field …").
- A failure that is **not** about the file keeps its own text: consent, a field error, the rate limit, the
general error.
- The texts are in the panel like every form message: Form messages → **Files**, per language, with English and
Polish defaults — fill the other languages of the site ([notifications.md](./notifications.md)). The browser
shows the size, format and count messages before anything is sent; the server answers with the same texts.
### Your own markup
`BuilderForm` renders a native ` ` with its label, the help text, the list of selected files
(`aria-live`) and a "Remove {file}" button per file. On `useBuilderForm`:
```tsx
const props = f.getFileProps(field) // id, name, type, accept, multiple, onChange, ref, aria-*
{field.label}
{field.help ? {field.help}
: null}
{f.getFiles(field).map((file, i) => (
f.removeFile(field, i)} type="button">Remove {file.name} ({formatFileSize(file.size)})
))}
```
`fileFieldRules(field)` gives the limits in the browser, `fileFieldError(field, files, texts)` the first problem as
the visitor's message. `isSubmitting` is the pending state (there is no upload percentage).
### Your own transfer path
`submitForm({ data, files })` takes files as whole buffers (`{ [fieldKey]: [{ name, data }] }`) and runs the same
checks and the same delivery — for an action or route that receives files itself. `splitFormFiles(values)`
(`/server`) splits `File` values from the answers; `createSubmitAction` already does it, so a hand-built form may
pass `File`s through the action (then raise `experimental.serverActions.bodySizeLimit` in `next.config.ts`).
`mailAttachmentLimit(payload)` returns the transport's ceiling in bytes (or `null`).
### Turn off, override, extend
- Off: leave `attachments` out. Only the block: `forms.fields: { file: false }`. Your own block:
`forms.fields: { file: buildFileBlock({ maxSizeMB: 5 }) }` (`fileBlock` = the default one).
- The endpoint's gates and path: `attachments.submit`, `attachments.path`; the browser can post elsewhere with
`BuilderForm fileSubmitUrl`.
- Submission fields (`submissionFiles`, `filesDelivery`, `filesDeliveryNote`, `attemptKey`) are appended to the
default fields — change them in `formSubmissionOverrides.fields`.
## Front end — submitForm (server)
Call it in a Server Action. The shape matches `useForm` / `useContactForm` 1:1
(`(values, turnstileToken) → { success, message }`) — you attach `formId` and `locale`
with `.bind`, and turn the error code into text from the panel:
```ts
// src/app/(frontend)/[locale]/actions.ts
'use server'
import { headers } from 'next/headers'
import { submitForm } from '@intecion/ipal-kit/server'
import { clientIp, isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
export async function sendForm(
formId: string,
locale: string,
values: Record,
turnstileToken?: string,
) {
const payload = await getCachedPayload()
const texts = (await getNotificationTexts({ payload, locale })).form
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: fake success
const { [HONEYPOT_FIELD]: _hp, ...data } = values
const ip = clientIp(await headers()) || undefined // headers(): OK in a server action — NOT in the page tree (SSG)
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
return { success: result.success, message: resolveFormMessage(result, texts) }
}
```
```tsx
// in a client component:
const f = useForm({ initialValues, validate, submitAction: sendForm.bind(null, form.id, locale) })
```
`submitForm` result: `{ success: true, submissionId }` or `{ success: false, reason, … }`
(codes below). Options: `payload`, `formId`, `data` (required), `files`, `attemptKey` ("Files" above), `ip`, `locale`, `turnstileToken`,
`maxPerMinute` (default 5, `0` turns it off; without `ip` — the shared `unknown-ip` bucket, below),
`consentFieldName` (default from `iapl({ forms })`, then `'consent'`), `turnstileOnConfigError`
(`'allow'` | `'reject'`, default `'allow'`), `turnstileHostnames` (see [turnstile.md](./turnstile.md)).
Simpler: `createSubmitAction({ getCachedPayload, headers })` from `/server` (section 1.9.1 below) —
extra options: `clientIp`, `honeypotField`, `consentFieldName`, `maxPerMinute`,
`turnstileOnConfigError`, `turnstileHostnames`.
### Client IP and rate limit
`clientIp(req | headers, { header?, trustedProxies? })` (from `@intecion/ipal-kit`):
- **Pinned header** — `header` or the env **`IAPL_IP_HEADER`**: only that header is read (missing → empty
string). For `x-forwarded-for` it takes the `trustedProxies`-th entry (default 1) from the right.
- **Not pinned** (default): it trusts **any** of the headers, in this order: `cf-connecting-ip`,
`x-real-ip`, then `X-Forwarded-For` counted **from the right** (the client writes the left part itself). A client
that reaches the app bypassing the proxy can therefore inject `cf-connecting-ip` /
`x-real-ip` and dodge the limit. In production without `IAPL_IP_HEADER` there is a one-time warning in the log.
Set e.g. `IAPL_IP_HEADER=cf-connecting-ip` behind Cloudflare, `x-forwarded-for` only behind Traefik/nginx.
- No recognised IP → the shared bucket (below). The same `clientIp` option exists in `createSearchRoute`
and `createMcpRoute`.
A missing IP (the proxy strips the header, a wrong `IAPL_IP_HEADER`) does **not** bypass the limit: such requests
share one `unknown-ip` bucket with a ×20 limit (`UNKNOWN_IP_FACTOR`) — real
visitors get through, a flood without the header does not. `setUnknownIpFactor(n)` (root, once at startup)
changes the multiplier; `setUnknownIpFactor(0)` = the old behaviour (no limit), when a limiter sits in front.
Without a pinned header the order
`cf-connecting-ip` → `x-real-ip` → XFF stays (switching to XFF-only, from the right, would put every visitor
behind Cloudflare into the bucket of the edge node) — that is why `IAPL_IP_HEADER` is mandatory in production
(`iaplEnvRules({ ipHeader: true })`).
Limits are kept in memory by default, separately for each instance. Several instances
→ a shared store (e.g. Redis) once at startup: `setRateLimitStore({ hit })`
(example in the `RateLimitStore` JSDoc). When the store fails, the request goes through (a warning in the log).
## Flow and guarantees
1. **Rate limit** per IP → `rate_limited`.
2. **Turnstile** — the **server** configuration decides, not whether the front end sent a token.
Both keys set (panel or env) → the token is **required**: missing or failed →
`turnstile`, rejected **before** storing. Keys not set → the widget does not
show, and the check is skipped. Details: [turnstile.md](./turnstile.md).
3. **Validation** against the form definition from the panel (+ enforced GDPR consent).
4. **Storing** the submission (form-submissions) → the form-builder composes the emails from the Emails tab;
they go out right after the submission is saved ("When e-mails go out").
**A stored submission = success, even when the email fails** — Payload logs the sending error,
the submission data is not lost (it is in Form Submissions).
## Emails
The plugin does not compose form emails. After storing a submission, the form-builder sends the
messages the editor configured (Forms → form → Emails), through
`payload.sendEmail`. For them to go out, the config needs an adapter:
```ts
email: mailAdapter(), // from '@intecion/ipal-kit' — the mail service, or SMTP when the panel has a server (email.md)
```
Then they go through the transport in effect (the Intecion mail service, or the SMTP server from Site integrations). The editor sets recipients, subject and
body (placeholders: `{{field}}`, `{{*}}`, `{{*:table}}`) without touching the code.
`submitForm` is responsible only for Turnstile verification and storing. It stores the submission in the page's language
(`locale` from `createSubmitAction`), so the form-builder takes the email texts and labels in that language.
### When e-mails go out (`emailsInTransaction`)
By default (since 1.17.0) a form's e-mails go out **right after the submission is saved**: they are composed inside
the submission's database transaction (layout, `forms.beforeEmail`, the kind marks, all with the transaction's
`req`), and handed to the mail server once that transaction has committed and given its connection back — still
within the same request, so `submitForm` answers as before (a file that could not be sent is still reported to the
visitor). What this changes:
- a slow or hanging mail server holds **no database connection** — on Postgres, many submissions at once used to stop
the site ([deployment.md](./deployment.md) §4.3a);
- a submission whose transaction is **rolled back** (a later hook of yours throws) sends **nothing**; before, its
e-mails had already gone out;
- **a failure after the commit leaves a stored submission without its e-mail** (the mail server refused it, or the
process ended in between) — as an e-mail failure always did: the submission is in Form Submissions, the error in
the log and the panel status, a file marked **File delivery: Not sent**;
- `payload.create` of a submission inside **your own transaction** (`req` passed from a hook or a script): the e-mails
go out when that transaction commits, and not at all when it is rolled back;
- **MongoDB without a replica set, SQLite** (no transactions): sent at once, exactly as before.
`forms: { emailsInTransaction: true }` sends them inside the transaction, as before 1.17.0 (not recommended on
Postgres). Building blocks: `sendAfterCommit(prepare, deliver)` (the `beforeEmail` that does this),
`sendFormEmails(req, emails)` (form-builder's own send loop), `afterCommit(req, fn)` (deployment.md §4.3a).
### Nice emails (`emailLayout`)
```ts
forms: { emailLayout: true } // optional: beforeEmail: (emails, args) => emails (after the layout)
```
- `{{*:table}}` turns into a **readable summary**: the question text instead of the field name, option labels
instead of values (Checkbox group too), a checked checkbox = ✓, empty answers skipped, groups by
step (Step titles). Only fields the visitor saw (the server does not store fields hidden by a condition).
- Every email gets a **template** (tables + inline CSS — Gmail, Outlook, Apple Mail): a header with the logo,
the body from the panel, a footer. Settings: **Site settings → Emails** — logo (**PNG/JPG**, SVG does not work in
Gmail/Outlook; empty = the site name), accent colour (hex), footer (per language). The link to the site and the
absolute logo address come from `serverURL` in `buildConfig` (set it from `NEXT_PUBLIC_SERVER_URL`).
- An error while building the template never blocks sending — the original email goes out, the error goes to the log.
- New tab = a migration in the project (`payload migrate:create`).
## Your own fields in the forms collection
`formOverrides` goes straight to the form-builder — the plugin has no opinion about what
a form needs beyond its own fields:
```ts
iapl({
forms: {
redirectRelationships: ['pages'],
formOverrides: {
fields: ({ defaultFields }) => [
...defaultFields,
{ name: 'internalNote', type: 'textarea' },
],
admin: { group: 'Content' },
},
// formSubmissionOverrides: { ... } // the same for submissions
},
})
```
`fields` gets the collection's default fields and returns the final list — you can add,
remove and reorder. Besides `fields` it accepts any collection settings
(admin, access, hooks).
## Security and the submission result
`submitForm` passes three gates in order of increasing cost: rate limit
(in-memory, per IP), Turnstile, validation against the form schema. Only
then does it store. A flood dies before it touches the network or the database.
**REST is closed.** By default the form-builder lets anyone create submissions through
`POST /api/form-submissions` — skipping all the gates below. IAPL
sets `access.create` of the `form-submissions` collection to "logged-in users only"; the front end
submits through `submitForm` (server action → Local API), so this does not affect it.
A deliberately public REST (e.g. an external app) →
`forms: { formSubmissionOverrides: { access: { create: () => true } } }` — then
the `submitForm` safeguards do not apply on that path.
**Only `editor+` edits forms.** The `forms` collection is publicly readable (the fields render the
form), but `create`/`update`/`delete` and reading the Emails tab (recipients, BCC) require the role
`editor` or `admin` — a `user` account cannot add itself as BCC to every submission. Override:
`forms: { formOverrides: { access: { … } } }`.
Validation matters, because a server action is a public endpoint — it can be called
without the form. The plugin loads the form definition and: rejects unknown
keys, enforces `required` fields and **rejects** a text value longer than 5000 characters — nothing is cut
or stored. The limit is fixed (no option today). The result is `{ success: false, reason: 'validation',
kind: 'too_long', field, label }`, and the visitor sees the **validation** text at that field ("Check the field
"{field}"." — Form messages → Form, `{field}` = the field's label) with every answer kept. Only what the
form defines reaches the database.
Rate limit: 5/min/IP by default (60 s window, the `form` counter is separate from search and MCP),
`maxPerMinute` changes it, `0` turns it off (when a limiter sits in front). In-memory — with several
instances the counter is per process (unless `setRateLimitStore`).
Unknown keys in `data` (other than form fields and `cf-turnstile-response` /
`g-recaptcha-response`) reject the **whole** submission (`kind: 'unknown_fields'`).
### Honeypot — a free second anti-spam layer
A hidden field that a real user neither sees nor fills in, but a naive bot
does. Zero friction (no network, no interaction), alongside Turnstile. Pure functions —
the client renders the input, the server checks it:
```tsx
// front end — in the form:
import { honeypotInputProps } from '@intecion/ipal-kit/client'
// off-screen, aria-hidden, tabIndex -1
```
```ts
// server action — CHECK FIRST, before submitForm:
import { isHoneypotTripped, HONEYPOT_FIELD } from '@intecion/ipal-kit'
if (isHoneypotTripped(values)) return { success: true } // fake success (no signal to the bot)
const { [HONEYPOT_FIELD]: _hp, ...clean } = values // remove it so submitForm does not see an unknown field
return submitForm({ /* … */ data: clean })
```
The field name defaults to `company_url` (looks real to a bot); your own:
`honeypotInputProps('website_2')` + `isHoneypotTripped(values, 'website_2')`.
### The result is a CODE, not text
`submitForm` returns a structured error — the plugin says WHAT happened, the project
decides HOW to show it (language, wording, per-field handling):
```ts
type SubmitFormResult =
| { success: true; submissionId: string | number }
| { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' }
| { success: false; reason: 'validation'; field?: string; kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields' | 'file_too_large' | 'file_type' | 'file_refused' | 'file_count'; label?: string; file?: string; max?: number; types?: string; optional?: boolean }
| { success: false; reason: 'delivery'; field?: string; file?: string; optional?: boolean; submissionId?: string | number } // the file could not be e-mailed
| { success: false; reason: 'not_found' }
| { success: false; reason: 'consent'; field?: string }
| { success: false; reason: 'error' }
```
The front end maps codes to its own messages:
```tsx
function errorMessage(r) {
switch (r.reason) {
case 'rate_limited': return 'Too many submissions...'
case 'validation':
if (r.kind === 'required') return 'Fill in the required fields.'
// r.field → highlight the specific field
}
}
```
The same pattern as consent: the plugin does not hard-code a language, it hands over data.
## GDPR consent (consent field)
The GDPR consent field is the field named `consent` (the name is changed by the `consentFieldName` argument
of `submitForm` / `createSubmitAction`). The plugin ENFORCES it being checked SERVER-SIDE
(the value must be exactly `true`) — regardless of how the editor set up the field
in the panel and of the "Show only when" condition.
### Why server-side
Consent is enforced in `validateSubmission`, not by a flag in the panel. It is the only
place the editor cannot weaken (by forgetting `required`) or break
(by setting `defaultValue: true` — a pre-checked box, which GDPR forbids), and the
front end cannot bypass. If the form has a `consent` field, it MUST be checked,
otherwise `submitForm` returns `reason: 'consent'`.
### How to use
1. The editor adds a checkbox named `consent` in the panel, with a label like "I accept the
privacy policy [link]" (the policy link goes into the label — the consent text
belongs to the panel).
2. The plugin enforces it being checked. Unchecked → `reason: 'consent'`.
3. The message comes from the notifications module (`notifications.form.consent`, per language).
Renaming the field:
```ts
export const sendForm = createSubmitAction({ getCachedPayload, headers, consentFieldName: 'zgoda' })
// or: submitForm({ …, consentFieldName: 'zgoda' })
```
Or once for the whole site: `iapl({ forms: { consentFieldName: 'zgoda' } })` — `submitForm`
reads it from `payload.config.custom.ipal` when the call does not pass one.
## Messages — resolveFormMessage (recommended)
Instead of a hand-written switch on `reason`, use `resolveFormMessage` from the
notifications module — it maps the code to text from the panel, per language, with `{field}` interpolation:
```tsx
import { resolveFormMessage, getNotificationTexts } from '@intecion/ipal-kit'
const notifications = await getNotificationTexts({ payload, locale })
// in FormRenderer:
if (!result.success) {
setError(resolveFormMessage(result, notifications.form))
}
```
It handles ALL codes (including `consent`, `rate_limited`, `validation` with
`{field}`) with texts from the panel. Keep the hand-written switch (above) only if you do not
use the notifications module. Details: [notifications.md](./notifications.md).
## Client logic — useForm / useContactForm (lower level)
For panel forms use `RenderForm` / `useBuilderForm` (above) — they have steps, choice
lists and validation from the field definition. `useForm` is the engine underneath: for a form **outside
the builder** (e.g. a search with filters), not for contact forms.
`submitForm` is the server. On the client side the same plumbing was repeated in
every project: `useState` for fields, an email regex, the Turnstile token, submit,
success/error state — ~150 lines of identical code per project. It was moved into a
hook. **The hook renders NO markup at all** — the project keeps 100% control
over the looks (the rule "we do not take control over the looks away from projects").
This is a LOGIC layer, not a replacement for the builder. The rule "fields from the builder" still
applies: for forms the editor can edit, you build `initialValues` and
rules from the definition in the panel and pass them to `useForm` (dynamic variant below).
`useContactForm` is a preset for a classic contact form with fixed
fields — when that is deliberately the right choice.
The anti-pattern the hook removes is **duplicated logic** (validation/submit/
Turnstile by hand in every project), not "using a hook".
### Preset — contact form (zero validators)
```tsx
'use client'
import { useContactForm } from '@intecion/ipal-kit/client'
const f = useContactForm({
submitAction, // your server action that calls submitForm
requireTurnstile: Boolean(siteKey),
requireTopic: topics.length > 0,
requireConsent: Boolean(consentText),
})
// JSX and classes are yours — only the wiring comes from the hook:
f.setField('email', e.target.value)}
className={f.errors.email ? 'border-red-500 …' : '…'} />
{f.isSuccess && }
```
Preset fields: `name, email, phone, topic, message, consent`. Returns:
`values, errors, isSubmitting, isSuccess, errorMessage, turnstileToken,
setField, setValues, setTurnstileToken, handleSubmit, reset`.
### Generic engine — any / dynamic fields
```tsx
import { useForm, buildValidator, required, email, minLength, pattern } from '@intecion/ipal-kit/client'
const f = useForm({
initialValues: { company: '', nip: '', email: '', message: '' },
submitAction,
validate: buildValidator({
company: [required()],
nip: [required(), pattern(/^\d{10}$/, 'NIP = 10 digits')],
email: [required(), email()],
message: [required(), minLength(10)],
}),
})
```
Dynamic fields from the builder — the schema is built at runtime from the definition in the panel:
```tsx
const initialValues = Object.fromEntries(fields.map((fl) => [fl.name, fl.type === 'checkbox' ? false : '']))
const validate = buildValidator(Object.fromEntries(fields.map((fl) => [fl.name, fl.required ? [required()] : []])))
const f = useForm({ initialValues, submitAction, validate })
```
### Validators (pure — also server-side)
`required`, `email`, `minLength`, `maxLength`, `checked`, `pattern`, `custom`,
`isEmail`, `buildValidator`. Each takes its own message; without one it uses the English
default from `VALIDATION_MESSAGES` (type `ValidationMessages`). `localizedRules(locale)` returns the
same rules with the defaults in the page language (`validationMessages(locale)`: Polish for `pl`,
English otherwise). They are pure (no `'use client'`), so you can use the same rules to
re-validate in a server action.
### errors are a STRING, not a boolean
`errors.` is a message (truthy when there is an error). It works as a `className` condition
like the old boolean, and you also get text to display. `setField` clears the field's error
on edit (by default).
### GTM/analytics event after submitting (Lead/Pixel)
A "Lead" tag (Meta Pixel / GA) in GTM usually fires on a `form_submit` event
in `dataLayer`. The hook has `onSuccess` (fires ONCE after a successful submit), and the plugin
provides the `pushDataLayer` helper — so the event goes out automatically, without a manual push
in every project:
```tsx
import { useContactForm, pushDataLayer } from '@intecion/ipal-kit/client'
const f = useContactForm({
submitAction,
onSuccess: (_result, v) => pushDataLayer('form_submit', { form_name: v.topic || 'contact' }),
})
```
In GTM: Data Layer Variable `DLV – form_name` (key `form_name`) + a custom event
trigger `form_submit`. **Consent is still gated by GTM** (`ad_storage`) — `pushDataLayer`
only emits the event, it does not bypass consent. `onSuccess` is wrapped in
try/catch — broken analytics will not block a successful submit. `pushDataLayer` is
SSR-safe and buffers the event when GTM has not loaded yet.
#### Managing from the PANEL (no code per form)
Instead of writing the event name/parameters in code, move them to the panel. Add
the analytics fields to the Forms collection:
```ts
// payload.config.ts
import { buildFormAnalyticsFields } from '@intecion/ipal-kit'
iapl({
forms: {
formOverrides: {
fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],
},
},
})
```
The editor sets per form (panel labels are in English): **Event name**
(default `form_submit`) and **Event parameters** (key/value; a `$field` value
is taken from the form field, e.g. `form_name = $topic`). The field group is called
**Analytics (GTM / dataLayer)**. The front end reads it and emits automatically — one generic
line in the shared renderer works for ALL forms:
```tsx
import { useContactForm, formAnalyticsOnSuccess } from '@intecion/ipal-kit/client'
const f = useContactForm({
submitAction,
onSuccess: formAnalyticsOnSuccess(form.analytics), // form.analytics from the panel
})
```
Result: adding a tracked form or changing the event name/parameters = **panel only,
zero deploys**. An empty event name → nothing is pushed.
What stays in GTM (deliberately — it is also a panel, just Google's): the tag itself (Lead/Pixel),
its trigger on the event name and the `ad_storage` consent condition. The plugin provides the
event + the consent signal; GTM decides what to fire and when.
### resolveLocalized — no more getSafeString
Resolving a localized value (topics, labels) is one import, not a
copied `(v as any)[locale]`:
```ts
import { resolveLocalized } from '@intecion/ipal-kit' // root only (not in /client)
const label = resolveLocalized(topic.label, locale)
```
## TRAP — captcha fields
Turnstile injects a hidden `cf-turnstile-response` field. The plugin tolerates it
(does not reject it as `unknown_fields`) — because it handles Turnstile itself. You do not need to
filter it out on the client.
## 1.9.1 — ready action, form seed, type validation
- **`createSubmitAction({ getCachedPayload, headers })`** from `/server` replaces a hand-written `actions.ts`:
`export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`headers` from
`next/headers`, injected). Honeypot → `clientIp` → `submitForm` → text from Notifications;
result `{ success, message, reason?, field? }`.
- **Form seed** (`iapl-form/resources/seed-form.template.ts`): fields, confirmation, an email to the company
(address from the panel) and a confirmation to the customer (`{{email}}`), every language, idempotent. Mandatory.
- **Validation by the field type from the panel:** email = one address (no `a@x, b@y`, no CR/LF), select/radio
only values from the panel, numbers, checkbox `true/false`, objects and arrays rejected, control
and bidi characters removed. Error: `reason: 'validation'`, `kind: 'invalid_format'`, `field`.
- **Access:** submissions are read only by `editor`/`admin` (before: any account), deleted by `admin`;
the form's Emails tab (recipient addresses) is hidden in the public `GET /api/forms`.
## Turn off, override, extend
- **Turn off:** without the `forms` option the plugin does not wire the form-builder (no Forms / Form Submissions collections).
Single field types: `forms.fields.: false`. Files: `forms.attachments` is off unless you set it ("Files").
- **Override the collections:** `formOverrides` / `formSubmissionOverrides` — fields (the `fields` function), `labels`,
`admin`, `access`, `hooks`. The default submissions access (`create`: logged-in users, `read`: editor+, `delete`: admin)
is overridden by keys in `formSubmissionOverrides.access`; forms access (`create`/`update`/`delete`:
editor+, `read`: public) — in `formOverrides.access`. The Emails tab protection (`read`: editor+) is
applied to the default fields **before** `formOverrides.fields`, so you change it there.
- **Override a field type:** `forms.fields.: ` replaces the block; your own blocks with "Placeholder" /
time: `withPlaceholder`, `placeholderField`, `timeBlock`, `stepBlock`, `checkboxGroupBlock` (root).
- **Submit gates:** `submitForm` / `createSubmitAction` — `maxPerMinute` (`0` = no limit),
`turnstileOnConfigError`, `turnstileHostnames`, `consentFieldName`, `clientIp`, `honeypotField`;
site-wide consent field name: `forms.consentFieldName`; shared limit store: `setRateLimitStore`; missing IP: `setUnknownIpFactor`.
- **Check:** `POST /api/form-submissions` without a session = 403; a `user` account → `PATCH /api/forms/` = 403;
submits without an IP header → past `maxPerMinute × 20` per minute (100 by default) you get `rate_limited`.
- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template,
`emailsInTransaction: true` sends them inside the submission's transaction ("When e-mails go out").
- **Your own front end:** `BuilderForm` (`renderField`), `useBuilderForm`, pure logic (`splitSteps`,
`visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, validators, `buildFormsPlugin` (root).