> ## Documentation Index
> Fetch the complete documentation index at: https://docs.frogbot.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Forms

> Let anyone with a link create records in a FrogBot collection through a form built in the admin.

The forms plugin lets people who aren't app users create records: leads, tickets, applications. You list which collections may take submissions; admins build a form for one of them in the `forms` collection; anyone with the link fills it in. Each response is a normal record in that collection, checked by its fields, validation, access and hooks.

The collection stays config. A form only picks which of its fields to ask for, with what wording, in which order and steps, and when it closes. A new question means a new field in config.

## Install

```bash theme={"theme":"tokyo-night"}
pnpm add @frogbotai/plugin-forms
```

```ts theme={"theme":"tokyo-night"}
import { formsPlugin } from '@frogbotai/plugin-forms'
import { buildConfig } from 'frogbot'

export default buildConfig({
  secret: process.env.FROGBOT_SECRET!,
  db: databaseAdapter,
  collections: [
    { slug: 'users', auth: true, fields: [] },
    {
      slug: 'leads',
      access: { create: ({ req }) => Boolean(req.user) },
      fields: [
        { name: 'email', type: 'email', required: true },
        { name: 'company', type: 'text' },
        { name: 'interest', type: 'select', options: ['sales', 'support'] },
        { name: 'source', type: 'text' },
      ],
    },
  ],
  plugins: [formsPlugin({ collections: ['leads'] })],
})
```

A collection that isn't listed is never touched, and listing one that doesn't exist fails at boot.

## Building a form

Admins build forms on the `forms` edit page. The **Questions** tab is a builder:

* **Add question** lists the fields of the form's collection that a question can use, with their type and a required mark. It greys out the fields it can't use, with the reason, and hides the ones already on the form.
* **A missing required field shows a warning.** A field that is `required` with no `defaultValue` and isn't on the form shows the warning that saving would give.
* **Edit** opens a question to change its label, help text, and placeholder. The field's own values show as placeholder text.
* **Add step** splits the form into steps. A step that still has questions asks before it's removed.
* **Move a question** by dragging its handle. With the keyboard, focus the handle and press Space, the arrow keys, and Space. A question moves within or across steps.

The other settings are in the **Settings** tab and the sidebar. The builder never changes the collection's fields. To ask for something new, add a field in config.

![The form builder beside the Live Preview of a two-step form](https://mintcdn.com/firmware/-vEuEx3YcVVv67GN/images/forms-builder.png?fit=max\&auto=format\&n=-vEuEx3YcVVv67GN\&q=85\&s=037192507d1d46cc35e3df9ed7784d43)

Once a form is saved, [Live Preview](https://docs.frogbot.ai/live-preview/overview.md) opens beside it and shows the form as visitors get it while you type, before you save again.

* **Phone** in its toolbar shows the form at 390 px wide.
* Nothing is sent from the preview. Its last step shows the confirmation.
* Live Preview is off on a new document, so a new form shows it after its first save.
* The preview is the admin page `/forms-preview`, which only users who can create or update forms can open.

Saving works as on any edit page. A document in the `forms` collection has:

* `title`, and a unique `slug` of lowercase letters, numbers and hyphens.
* `collection`: one of the listed collections. Each response creates a record there.
* `mode`: `create` (the default) takes new records, `update` edits one record through an [edit link](#edit-links), and `both` does either.
* `steps`, each with an optional `title` and its `questions`. A question names a field of the collection and can override its `label`, `description` and `placeholder`. A file question also has `maxFileSize`, `maxFiles` and `mimeTypes`; see [File uploads](#file-uploads). A question can also have `rules` and `match`; see [Showing a question for some answers](#showing-a-question-for-some-answers).
* `hiddenParams`: URL parameters, like `utm_source`, saved to a field of the record.
* `confirmation`: a `message`, or a `redirect` to a path such as `/thanks` or an `http(s)` URL.
* `status` (`open` or `closed`), `closesAt` and `maxResponses`.

A question can use any top-level field of type `text`, `textarea`, `email`, `number`, `select`, `radio`, `checkbox`, `date`, or `upload`. Fields in unnamed rows, collapsibles, groups, and tabs count as top-level.

Saving a form is refused, naming the field at fault, when a question does any of these:

* Uses another field type, a list (`hasMany` text or number), or a hidden or virtual field.
* Repeats a field already on the form.
* Names a field whose `access.create` denies a form submission.
* Asks for files that could pass the app's upload limits, or stores them somewhere a form can't (see [File uploads](#file-uploads)).
* Has a rule that checks itself, a later question, a question not on the form or a file question, or has rules on a `required` field (see [Showing a question for some answers](#showing-a-question-for-some-answers)).

Saving is also refused when the form leaves out a field that is `required` and has no `defaultValue`, since no response could then be saved.

Two kinds of form skip checks:

* An `update` form skips the missing-required-field rule and the `access.create` check, and has its own checks. See [Edit links](#edit-links).
* A form saved as `closed` skips all of these checks, so it can always be closed, or drafted before it opens.

## Showing a question for some answers

A question with `rules` is shown only when the answers to earlier questions pass them. Each rule names an earlier question's field and an `operator`:

* `equals`: the answer is `value`. A checkbox answer is `true` or `false`, a number compares by value (`5` equals `05`), and a multi-select passes when any chosen option is `value`.
* `notEquals`: the answer isn't `value`, which includes no answer.
* `hasValue`: the question has an answer. An unchecked checkbox, empty text and no chosen option don't count.

Every rule must pass, or one with `match: 'any'`. In the builder, open a question with **Edit** and use **Show when**, which offers the questions above it:

```ts theme={"theme":"tokyo-night"}
steps: [
  {
    questions: [
      { field: 'business' },
      {
        field: 'company',
        rules: [{ question: 'business', operator: 'equals', value: 'yes' }],
      },
    ],
  },
]
```

The page and the server run the same check, `visibleQuestions` from `@frogbotai/ui/forms/rules`, over the answers in order, so the answer to a hidden question counts as no answer for the rules after it. A step whose questions are all hidden is skipped, and the step count leaves it out. Hidden questions aren't checked on the page, and the server drops their answers and files, even if a client sends them; through an edit link, a hidden question's field keeps its saved value, and the rules read the record's saved answer to any earlier question the edit leaves out. Since a hidden question must never block a response, a `required` field can't have rules, even one with a default: make it optional. If a field becomes `required` after a form gave it rules, the page and the server ignore those rules and always show it.

## Who can open a form

Like any collection, `forms` is readable by anyone and writable by signed-in users unless you pass `access`, which is merged over those defaults. A visitor who can't read a form gets the same 404 as for a form that doesn't exist:

```ts theme={"theme":"tokyo-night"}
formsPlugin({
  collections: ['leads'],
  access: {
    read: ({ req }) => (req.user ? true : { slug: { not_equals: 'staff-time-off' } }),
  },
})
```

## How a response passes access

Every listed collection's `access.create` is wrapped as `isFormSubmission(req, slug) || yourRule(args)`. A collection with no `create` rule keeps FrogBot's default, admin users only, behind the same check. The record is created with `overrideAccess: false`, so field access and the collection's hooks still run.

While the record is created, `req.context.form` holds `{ form, collection }`. Use `isFormSubmission` in your own hooks or access to tell responses apart:

```ts theme={"theme":"tokyo-night"}
import { isFormSubmission } from '@frogbotai/plugin-forms'

const leads = {
  slug: 'leads',
  hooks: {
    beforeChange: [
      ({ data, req }) => (isFormSubmission(req, 'leads') ? { ...data, status: 'new' } : data),
    ],
  },
  fields: [],
}
```

Only the plugin's submit endpoint can set the flag, and it names one collection, so a hook that creates a document elsewhere with the same `req` isn't admitted there.

## File uploads

An `upload` field makes a file question: visitors attach files, and the record points at them. The files go into an upload collection that you also list in `collections`, and nobody gets them back: the response holds no file, URL or ID, and the upload collection's own `read` rule decides who sees them.

```ts theme={"theme":"tokyo-night"}
const ticketFiles: CollectionConfig = {
  slug: 'ticket-files',
  upload: true,
  access: { read: ({ req }) => Boolean(req.user) },
  fields: [],
}

const tickets: CollectionConfig = {
  slug: 'tickets',
  fields: [
    { name: 'subject', type: 'text', required: true },
    { name: 'attachments', type: 'upload', relationTo: 'ticket-files', hasMany: true },
  ],
}

formsPlugin({ collections: ['tickets', 'ticket-files'] })
```

Each file question takes, on the form:

| Setting | Default | Description |
| - | - | - |
| `maxFileSize` | The app's per-file limit | The largest file accepted, in bytes. |
| `maxFiles` | `1` | How many files one response may attach, up to 5. Above 1 needs a `hasMany` field. |
| `mimeTypes` | Any | Accepted types, like `application/pdf` or `image/*`. The page's file picker uses them too. |

These checks use the type the browser sends. The upload collection then checks the file's contents: it refuses executables and scripts unless you set `upload.allowRestrictedFileTypes`, and with `upload.mimeTypes` set it also refuses files whose detected type isn't listed.

### Upload limits

Every file arrives in one request, under the app's upload limits. The defaults are 20 MB per file, 3 files, and 50 MB per request.

Saving a form is refused, naming the question, in these cases:

* One file could be larger than the per-file limit.
* The form's file questions together could take more files than one request allows.
* The form's file questions together could take more bytes, plus 1 MB for the answers, than one request allows.

An upload collection that requires a field with no default is refused too, since a form only sends the file.

For bigger files, raise the limits in your config:

```ts theme={"theme":"tokyo-night"}
export default buildConfig({
  // …
  upload: {
    limits: { fileSize: 60 * 1024 * 1024, files: 5 },
    requestSizeLimit: 320 * 1024 * 1024,
  },
})
```

Files are held in memory while the request is read. With large limits, set `upload.useTempFiles: true` to write them to a temporary folder instead. Your host may cap request bodies too; Vercel, for example, refuses bodies over 4.5 MB.

### How files are saved

A submit with files is `multipart/form-data`: the usual body as JSON in a `_payload` part, and each file as a part named after its question. Parts named after anything else are ignored. A value in `data` for a file question, such as the ID of a file already in the app, answers `400`: visitors can attach files, never point at existing ones.

A submit with files runs in this order:

1. Each question's count, size, and types are checked. A required question with no file answers `400`.
2. Each file is created in its upload collection the way the record is: flagged as this form's submission and with `overrideAccess: false`, so its hooks run.
3. The record is created last.

When a file or the record is refused, the plugin deletes the files it made for that submit, and only those, and answers `400` with the error on its question.

### Scanning files

FrogBot doesn't scan files itself. Add a `beforeChange` hook to the upload collection that scans `req.file` and throws when it's unsafe. The file is written to storage only after the collection's `beforeChange` hooks, so when the hook throws, nothing is kept. Boot logs a warning for each listed upload collection without a `beforeChange` hook.

This one uses [ClamAV](https://www.clamav.net/) through the [`clamscan`](https://www.npmjs.com/package/clamscan) package and a `clamd` server, which needs about 4 GB of memory:

```ts theme={"theme":"tokyo-night"}
import { Readable } from 'node:stream'

import NodeClam from 'clamscan'
import { APIError, type CollectionConfig } from 'frogbot'

const clamav = new NodeClam().init({
  clamdscan: { host: process.env.CLAMD_HOST, port: 3310 },
})

export const ticketFiles: CollectionConfig = {
  slug: 'ticket-files',
  upload: true,
  access: { read: ({ req }) => Boolean(req.user) },
  hooks: {
    beforeChange: [
      async ({ data, req }) => {
        if (!req.file) return data

        const scanner = await clamav
        const { isInfected } = req.file.tempFilePath
          ? await scanner.scanFile(req.file.tempFilePath)
          : await scanner.scanStream(Readable.from(req.file.data))

        if (isInfected) throw new APIError('This file failed a virus scan.', 400)

        return data
      },
    ],
  },
  fields: [],
}
```

An `APIError` below 500 reaches the visitor as the question's error. Any other error answers `500` and is logged.

## The form page

Every form has a public page at `/forms/<slug>` under the admin route, `/forms/contact` with FrogBot's default admin at `/`. It renders without the admin's sidebar and header, follows the app's theme, and works for visitors who aren't signed in. The page loads the form as the visitor, so a form they can't read, or one that doesn't exist, shows the not-found page. A closed form shows that it's closed.

The page reads the form's hidden parameters from its own URL, so `/forms/contact?utm_source=newsletter` saves `newsletter` to the field `utm_source` maps to. A required question must be answered before **Next** moves on, and errors from the collection's validation are shown on their questions.

## Rendering a form in your own frontend

The same renderer is a React component in `@frogbotai/ui/forms`. It imports nothing from FrogBot's server or Next.js, so it works in any React app. Fetch the definition, then render it against the submit endpoint:

```tsx theme={"theme":"tokyo-night"}
import { Form, type FormDefinition } from '@frogbotai/ui/forms'

export function ContactForm({ definition }: { definition: FormDefinition }) {
  return <Form definition={definition} submitUrl="https://app.example.com/api/forms/contact/submit" />
}
```

Load `@frogbotai/ui/styles.css` once for its styles. They sit in the `frogbot` cascade layer, so your own CSS overrides them without extra specificity. The form's root is `.fb-form`.

| Option | Type | Default | Description |
| - | - | - | - |
| `definition` | `FormDefinition` | Required | The form's render definition, from `GET /api/forms/<slug>/definition`. |
| `submitUrl` | `string` | None | Where answers are posted. For an edit link, add `?link=<token>`. Without it nothing is sent: the last step checks the answers and shows the confirmation, as a preview does. |
| `onSubmitted` | `(confirmation: FormConfirmation) => void` | None | Called with the confirmation after a successful submit. When set, a redirect confirmation is left to you. |
| `className` | `string` | None | Added to the form's root element. |

## Endpoints

Both endpoints are public and check the form's `read` access as the visitor.

```http theme={"theme":"tokyo-night"}
GET /api/forms/contact/definition
```

Returns what a page needs to show the form:

* Its title, steps, and questions. Each question has `key`, `type`, `label`, `description`, `placeholder`, `required`, `options`, `hasMany`, and `defaultValue`. A file question also has `maxFiles`, `maxFileSize`, and `mimeTypes`.
* The hidden parameter names and the confirmation.
* Whether the form is `closed`.
* The `honeypot` input's name and, with Turnstile on, `turnstile.siteKey`.

It never returns the collection's other fields.

```http theme={"theme":"tokyo-night"}
POST /api/forms/contact/submit
Content-Type: application/json

{ "data": { "email": "ada@example.com", "interest": "sales" }, "params": { "utm_source": "newsletter" }, "turnstile": "<token>" }
```

* Keys that aren't questions on the form are dropped, as are undeclared parameters. A declared parameter is cut to 500 characters.
* A form that is closed, past `closesAt` or at `maxResponses` answers `410`.
* On success the response is `{ "confirmation": { "type": "message", "message": "…" } }` or `{ "confirmation": { "type": "redirect", "url": "/thanks" } }`, never the record.
* When the collection refuses the record, the response is `400` with `{ "errors": [{ "field": "email", "message": "…" }] }`.
* With files, send `multipart/form-data` as described in [How files are saved](#how-files-are-saved). Files over the app's upload limits answer `413`.
* A missing or refused Turnstile token answers `400`, and too many submits from one address answer `429` with a `Retry-After` header. See [Spam protection](#spam-protection).

Both take `?link=<token>` for an [edit link](#edit-links): the definition then carries the record's answers as `values`, and the submit updates that record. An `update` form answers `404` without a link.

With `maxResponses` set, responses are counted under a per-form lock in the app's KV store, so two visitors submitting at once never pass the limit. Without it, the count is kept but not locked.

## Edit links

An edit link lets someone without an account change one record through one form. Examples are a customer who fixes their phone number and an applicant who updates their answers.

1. Set the form's `mode` to `update`, or to `both` to keep taking new records too.
2. Make a link for a record.

Whoever opens the link sees that record's answers filled in, changes the form's questions, and saves. The collection's validation and hooks run as for any update.

### Making a link

In the admin, open a record and choose **Create edit link** from its menu. The item shows when an `update` or `both` form targets the collection and you can update the record.

1. Pick the form, how long the link lasts, and how many saves it allows.
2. Copy the URL.

> [!NOTE]
>
> The URL is shown once. Only a hash of it is stored, so a lost link is replaced, not copied again.

From code, call `createFormLink` as the user who sends it:

```ts theme={"theme":"tokyo-night"}
import { createFormLink } from '@frogbotai/plugin-forms'

const { url, expiresAt } = await createFormLink(req.frogbot, {
  form: 'update-application',
  record: application.id,
  expiresIn: '3d',
  req,
})
```

| Option | Type | Default | Description |
| - | - | - | - |
| `form` | `string \| number` | Required | The form's slug or ID. Its `mode` must be `update` or `both`. |
| `record` | `string \| number` | Required | The ID of the record in the form's collection. |
| `expiresIn` | `number \| string` | `links.defaultExpiry` | Seconds, or a length like `'30m'`, `'12h'`, `'7d'` or `'2w'`, up to `links.maxExpiry`. |
| `maxSubmissions` | `number \| null` | None | Saves the link allows. Unset, it works until it expires or is revoked. |
| `req` | `FrogBotRequest` | None | The request whose user makes the link. |
| `overrideAccess` | `boolean` | `false` | Skip the check that the user can update the record. |

It returns `{ url, id, expiresAt }`.

* Without `overrideAccess`, the user must pass the collection's own `access.update` for that record, or the call throws `Forbidden`.
* A form that only creates, a bad length, or a bad use limit throws `ValidationError`.

`POST /api/form-links` with the same options as JSON makes a link as the signed-in user.

An agent can send links through a tool that calls it as the agent's user, so the collection's update rule still decides:

```ts theme={"theme":"tokyo-night"}
import { createFormLink } from '@frogbotai/plugin-forms'
import type { Tool } from 'frogbot'
import { z } from 'zod'

const sendEditLinkInput = z.object({ application: z.string() })

export const sendEditLink: Tool<typeof sendEditLinkInput, { url: string; expiresAt: string }> = {
  slug: 'send-edit-link',
  description: 'Make a link that lets an applicant update their application.',
  inputSchema: sendEditLinkInput,
  approval: 'ask',
  execute: async ({ application }, { frogbot, req }) => {
    const { url, expiresAt } = await createFormLink(frogbot, {
      form: 'update-application',
      record: application,
      req,
    })

    return { url, expiresAt }
  },
}
```

### How long links last

Links last 7 days unless `expiresIn` says otherwise, and at most 30 days. Change both in the plugin options:

```ts theme={"theme":"tokyo-night"}
formsPlugin({
  collections: ['applications'],
  links: { defaultExpiry: '14d', maxExpiry: '60d' },
})
```

A link works for any number of saves until it expires; set `maxSubmissions: 1` for a single-use link. Opening a link never counts, only saving.

### What a link can do

* It opens one form for one record. `/forms/<slug>?link=<token>` shows the record's current answers to the form's questions and nothing else, read with `overrideAccess: false`.
* Saving keeps only the form's questions, ignores URL parameters, and updates the record with `overrideAccess: false`. Emptying an answer clears its field. The response is the confirmation or field errors, never the record.
* While a link is used, each listed collection's `access.read` and `access.update` admit only the link's record. `req.context.formLink` holds `{ id, collection, record }`, so your hooks can tell link saves apart; only the plugin can set it, and a hook that writes another collection or record with the same `req` isn't admitted there.
* `updatedBy` stays as it was, since nobody is signed in. The link's `submissions` and `lastSubmittedAt` record each save. A save the collection refuses spends no use.
* An unknown, expired, revoked or used-up link, or another form's, shows one "This link is no longer valid" page, and the endpoints answer `410` with no detail. With `trustProxy`, each such link counts toward the visitor's [rate limit](#spam-protection).
* The token is random, not signed, so it never signs anyone in, and changing `FROGBOT_SECRET` doesn't break links.

Saving an `update` or `both` form is refused, naming the field, when a question's `access.read` or `access.update` denies a signed-out request, or when it's a file question. Collections with drafts can't take edit links.

To fix a value that a person may not change, such as the record's owner, set it in a `beforeChange` hook when `req.context.formLink` is present.

### Revoking links

Links live in the **Edit links** collection (`form-links`), with each link's status: active, expired, used up, or revoked.

* **Revoke in the admin.** **View edit links** in a record's menu lists that record's links. Select some and choose **Revoke selected**.
* **Revoke in code.** Setting `revokedAt`, or deleting the link, stops it at once. A revoked link stays revoked.
* **Deleting a form** deletes its links.
* **Access.** People who can update a record can see, revoke, and delete its links. `links.access` overrides that.

> [!WARNING]
>
> Anyone who has the URL can change the record's answers until the link expires or is revoked. Send links only to the person they're for, keep `maxExpiry` short, and revoke a link that may have leaked.

## Spam protection

A public form is a public write path, so every submit goes through these checks, in this order:

1. **Rate limit.** With `trustProxy` on, each visitor address gets `rateLimit.max` submits per `rateLimit.window` seconds across all forms, 10 per 10 minutes by default. The next one answers `429` before the body is read. Counts live in the app's KV store.
2. **Honeypot.** The page has a hidden input that people never see or reach with the keyboard. A submit that fills it gets the normal confirmation, and nothing is saved or counted.
3. **Turnstile.** With `turnstile` set, the page shows Cloudflare's [Turnstile](https://developers.cloudflare.com/turnstile/) widget and the plugin checks its token with Cloudflare before saving. A missing, invalid, expired or reused token answers `400`. Tokens last 300 seconds and work once.

```ts theme={"theme":"tokyo-night"}
formsPlugin({
  collections: ['leads'],
  turnstile: {
    siteKey: process.env.TURNSTILE_SITE_KEY!,
    secretKey: process.env.TURNSTILE_SECRET_KEY!,
  },
  rateLimit: { max: 5, window: 600 },
  trustProxy: true,
})
```

### Visitor addresses and `trustProxy`

The server can't see a visitor's address on its own; behind a proxy or load balancer, it gets it from the `x-forwarded-for` header the proxy sets. A visitor can send that header too, so the plugin reads it only when you set `trustProxy: true`, and then uses its last entry, the one your proxy appended, or `x-real-ip` when there's none.

Set `trustProxy: true` only when every request reaches the app through a proxy that sets those headers, such as Fly.io, Vercel, Cloudflare or nginx with `proxy_add_x_forwarded_for`. With it off, submits aren't rate-limited at all, since counting every visitor together would refuse real people on a busy day, and boot logs a warning. The honeypot and Turnstile still run.

### Email hooks can relay spam

A hook on the collection that emails the person who submitted, such as a "we got your request" reply, sends mail to any address a bot types in. Bots use this to relay spam through your domain. Turn on Turnstile for forms whose collection sends mail to the submitted address, or send those emails only after a person reviews the record.

## Options

| Option | Type | Default | Description |
| - | - | - | - |
| `collections` | `CollectionSlug[]` | Required | Collections forms may create records in. |
| `access` | `CollectionAccess` | Anyone reads, signed-in users write | Access for the `forms` collection, merged over the defaults. |
| `turnstile` | `{ siteKey: string; secretKey: string }` | None | Cloudflare Turnstile keys. When set, every submit needs a token Cloudflare accepts. |
| `rateLimit` | `{ max?: number; window?: number }` | `{ max: 10, window: 600 }` | Submits allowed from one visitor address per window, in seconds, across forms. Counted only with `trustProxy`. |
| `trustProxy` | `boolean` | `false` | Read the visitor's address from the `x-forwarded-for` (last entry) or `x-real-ip` header your proxy sets. Off, submits aren't rate-limited and boot warns. |
| `links` | `{ defaultExpiry?; maxExpiry?; access? }` | `{ defaultExpiry: '7d', maxExpiry: '30d' }` | Edit links: how long they last, as seconds or a length like `'7d'`, and access for the `form-links` collection, merged over the default (people who can update a record manage its links). |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.