You're reading docs for Nextly Alpha. APIs may change between releases.

Plugins

Form Builder

Create and manage dynamic forms with a visual drag-and-drop builder, submission tracking, email notifications, spam protection, webhooks, and data export.

Alpha (0.x) — pin your versions.

The plugin SDK is alpha: its @public surface becomes semver-protected at 1.0 (see API stability). Until then, pin exact versions of the plugin packages and read the release notes before upgrading.

The Form Builder plugin adds a complete form management system to Nextly. Build forms visually in the admin panel or define them in code, collect submissions, send email notifications, and protect against spam -- all without writing custom endpoints.

Installation

npm install @nextlyhq/plugin-form-builder

The plugin declares these peer dependencies:

PeerRange
nextlythe matching lockstep version, pinned exactly
@nextlyhq/adminthe matching lockstep version, pinned exactly
@nextlyhq/plugin-sdkthe matching lockstep version, pinned exactly
@nextlyhq/uia caret range on the matching lockstep version
@tanstack/react-query>= 5
lucide-react>= 0.400.0
reactthe supported range in Requirements
nextthe supported range in Requirements

While Nextly is in alpha every publishable package ships on one train, so three of the four Nextly peers are pinned to the exact version the plugin was built against, and @nextlyhq/ui publishes as a caret range on it. Either way, install the plugin and your core at the same version rather than reaching for a range of your own. @tanstack/react-query and lucide-react are the two most likely to be missing from a project that has not needed them yet, and their absence shows up as a broken admin screen rather than an install error.

Basic Setup

// nextly.config.ts
import { defineConfig } from "nextly";
import { formBuilder } from "@nextlyhq/plugin-form-builder";

const fb = formBuilder();

export default defineConfig({
  plugins: [fb.plugin],
  collections: [Posts, Users, Media],
});

This creates two collections automatically:

CollectionDefault SlugPurpose
FormsformsStores form definitions (fields, settings, notifications)
Submissionsform-submissionsStores submitted data with status tracking

Both collections appear in the admin sidebar under the Forms group.

Configuration Options

Pass an options object to formBuilder() to customize behavior.

// nextly.config.ts
const fb = formBuilder({
  // Customize collection slugs and labels
  formOverrides: {
    slug: "contact-forms",
    labels: { singular: "Contact Form", plural: "Contact Forms" },
  },
  formSubmissionOverrides: {
    slug: "responses",
    labels: { singular: "Response", plural: "Responses" },
  },

  // Enable/disable specific field types
  fields: {
    file: false, // Disable file uploads
    hidden: false, // Disable hidden fields
  },

  // Email notifications
  notifications: {
    defaultFrom: "noreply@example.com",
    defaultToEmail: "submissions@example.com",
    enabled: true,
  },

  // Spam protection
  spamProtection: {
    honeypot: true,
    rateLimit: {
      maxSubmissions: 10,
      windowMs: 60_000,
    },
  },

  // File upload limits
  uploads: {
    maxFileSize: 10_485_760, // 10 MB
    allowedMimeTypes: ["image/*", "application/pdf", "text/*"],
  },

  // Feature flags
  features: {
    builder: true,
    conditionalLogic: true,
    fileUploads: true,
  },

  // Collections that can serve as redirect targets after submission
  redirectRelationships: ["pages"],

  // Your own words for what visitors see that no form's author wrote,
  // per language (experimental)
  words: {
    fr: { choose: "Faites un choix…" },
    pl: { submit: "Wyślij", other: "Inne" },
  },
});

Words visitors see in their language

A form on a page shows some words its author didn't write: a dropdown's empty first choice ("Choose…") where it has no placeholder, the send button ("Submit") where the form names none, the required marks, the messages a send comes back to, an Other choice's "Other" and "Please say", and why an answer was refused. They follow the page's language. The plugin ships them in English, Spanish (es), French (fr), German (de), Portuguese (pt), Italian (it) and Dutch (nl); where a browser says the same thing in its own form checks, the words are the browser's own. A regional language (fr-CA) reads its base language's words, and a language the plugin doesn't ship reads English. A page in the site's default language reads that language's words, one chosen in Settings included; a site with no languages reads English.

The experimental words option gives your own, for any language code, word by word; yours come first, then the plugin's. The words are submit, choose, required (said to a screen reader after a required field's label), requiredNote (after the * above a form), sent, invalid, closed, error, refused (beside a refused field with no reason of its own), other, otherPlaceholder, otherEmpty and atLeastOne. A word the plugin has no place for, or one that isn't text, stops the app at start-up with the option named. Words a form's author wrote (a placeholder, an Other choice's words, the button, the confirmation message) always come first, in each language the form is written in.

Collection Overrides

You can add custom fields to the Forms or Submissions collections, or restrict access control.

Array style -- appends fields to the defaults:

formOverrides: {
  fields: [
    text({ name: 'internalNotes', label: 'Internal Notes' }),
  ],
  access: {
    read: () => true,
    create: ({ permissions }) => permissions.includes('create-forms'),
  },
}

By default a visitor can read a form and create a submission. Everything else needs the matching permission on the Roles screen: read-form-submissions to read submissions, update-forms to edit a form, delete-form-submissions to delete one. An override narrows from there; check the permission in it rather than a role's name.

The plugin's collections are open to the built-in Admin, Editor, Author and Viewer roles, each by its own rule (an Author does not delete, a Viewer reads); grants in an override, or presetGrants in the config, changes that.

Function style -- full control over the field list:

formSubmissionOverrides: {
  fields: ({ defaultFields }) => {
    const formIndex = defaultFields.findIndex(f => f.name === 'form');
    return [
      ...defaultFields.slice(0, formIndex + 1),
      { name: 'source', type: 'text' },
      ...defaultFields.slice(formIndex + 1),
    ];
  },
}

Fields you add show on each submission's page in the admin, under Details, with their values, except a field hidden from the admin (admin: { hidden: true }), one shown only when a condition holds (admin.condition), and one that holds fields of its own (a group, array or blocks). The page shows them read-only: it draws editors for a submission's answers, status and note, not for fields it does not know. Set them from your own code with the Direct API (nextly.update({ collection: 'form-submissions', id, data: { priority: 'high' } })) or the REST entries API.

Field Types

All 14 field types are enabled by default. Set any to false in the fields option to remove it from the builder.

TypeDescriptionKey Options
textSingle-line text inputminLength, maxLength, pattern
emailEmail address with format validationpattern
numberNumeric inputmin, max, step
phonePhone number inputpattern
urlURL with format validationpattern
textareaMulti-line text inputrows, minLength, maxLength
selectDropdown menuoptions, allowMultiple, startEmpty
checkboxSingle boolean toggledefaultValue
radioRadio button groupoptions
fileFile uploadaccept, multiple, maxFileSize
dateDate pickermin, max
timeTime pickerdefaultValue (HH:mm format)
hiddenHidden value (not shown to users)defaultValue
consentRequired box agreeing to a textagreementText

Every field supports these common properties: name, label, placeholder, helpText, defaultValue, required, validation, conditionalLogic, and admin.width (25% to 100%).

A dropdown's placeholder is the words of its empty first choice, which a required dropdown won't send; without one it reads "Choose…". Set startEmpty: false for a dropdown with no empty choice: it starts on its defaultValue, or its first option. Absent, a dropdown starts empty, as every form saved before the setting does. In the builder, a one-choice Dropdown has a Placeholder box and a Start empty switch under its choices; the Placeholder is off while Start empty is off.

An option of a radio list, or of a select with allowMultiple (drawn as checkboxes), can carry a description: a second line under its label, such as { label: "Pay by the hour", value: "hourly", description: "Billed in 15-minute steps" }. In the builder, each such option has + Add description under it. A one-choice dropdown's options show one line, so it offers none.

In the builder, a select's or a radio list's default is marked on its choice's own row: a radio for a field taking one answer, a checkbox on each row for a select with allowMultiple, whose defaultValue is then a list. Clear default above the choices removes it. Turning Allow several choices off keeps the first default. Each choice's stored value is taken from its label and kept out of sight until Show values is on; the switch stays on while a value differs from the one its label gives, or two values are the same, so a value you set is never hidden.

A radio list and a select with allowMultiple can also take, in the builder under their choices (all experimental):

  • Pictures: choicePictures: "images" draws each option's image (a media item's id) above its label, and "icons" its icon (such as "lucide:star"). Each option sets its picture on its own row: + Add image, or an icon picker. A choice without one, or whose image can't be read, shows its label alone. Turning images on lays the choices out three to a row.
  • + Add "Other" choice: otherChoice: { label?, placeholder? } adds a last choice, "Other" unless worded otherwise, with a text box beside it, "Please say" unless worded otherwise. What the visitor types is saved as the field's answer, as they typed it (beside the other picks of a set of checkboxes), up to 200 characters. Other picked with nothing typed is refused with "Please say what your other answer is." A required field with Other is checked when it is sent rather than by the browser, since words typed with nothing picked are an answer.
  • Layout: choiceLayout sets how the choices sit: "list" (one under another, the default), "2-columns", "3-columns", or "inline" (side by side, wrapping). Columns become one on a form narrower than 640 px.
  • Shuffle choices: shuffleChoices: true shows the choices in a new order for each visitor, "Other" kept last. It needs JavaScript in the visitor's browser: the plugin's page script orders them, without moving the page's own markup, and the list stays out of sight until it has (shown in the stored order after a moment if the script never runs). With JavaScript off the choices are in the order stored. The builder's preview shows the stored order.

A select with allowMultiple can ask for a number of picks (experimental): choiceLimits: { min?, max? }, in the builder Fewest picks and Most picks under its choices. Blank is no limit; the same number in both asks for exactly that many; "Other" counts as a pick. The rule is said under the field's label in the page's language ("Choose 2 to 3."), the browser holds the send until the count fits, and the server refuses any other count ("Please choose 2 to 3."), beside the field when the form was sent with no JavaScript. An optional field may still be left with none. Limits that can't be met (not whole numbers from 1, the most fewer than the fewest, or more than the choices) are refused when the form is saved. The words are among those the words option takes: picksRange, picksAtLeast, picksAtMost, picksExactly and the hints hintRange, hintAtLeast, hintAtMost, hintExactly, each naming its numbers as {min} and {max}.

Creating Forms

Visual form builder (admin UI)

Navigate to Forms in the admin sidebar and click Create New. The form builder provides:

  • Field Library -- click or drag field types to add them to the form
  • Form Canvas -- reorder fields with drag-and-drop, click to edit
  • Field Editor -- configure each field's label, validation, placeholder, help text, and conditional logic
  • Settings Tab -- submit button text, confirmation type (message or redirect), multiple submission settings
  • Notifications Tab -- configure email integrations per form
  • Preview -- see how the form will look to end users

Forms have three statuses:

  • Draft -- not accepting submissions (use for building)
  • Published -- live and accepting submissions
  • Closed -- shows a configurable closed message

Code-First Definitions

Use the field helper functions to define forms programmatically. These helpers set the type property automatically.

import {
  text,
  email,
  textarea,
  select,
  checkbox,
  option,
} from "@nextlyhq/plugin-form-builder";

const contactFields = [
  text({ name: "firstName", label: "First Name", required: true }),
  text({ name: "lastName", label: "Last Name", required: true }),
  email({ name: "email", label: "Email Address", required: true }),
  select({
    name: "subject",
    label: "Subject",
    required: true,
    options: [
      option("General Inquiry"),
      option("Support Request"),
      option("Feedback"),
    ],
  }),
  textarea({
    name: "message",
    label: "Message",
    required: true,
    rows: 5,
    validation: { minLength: 10, maxLength: 2000 },
  }),
  checkbox({ name: "subscribe", label: "Subscribe to our newsletter" }),
];

The option() helper converts labels to slug values automatically ('General Inquiry' becomes 'general_inquiry'). Pass a second argument for an explicit value: option('United States', 'us').

Additional field helpers: number(), phone(), url(), radio(), file(), date(), time(), hidden(), consent().

A consent field is a box the visitor ticks to agree to a text, such as your privacy policy. It is always required. The answer stores the choice with the text the form showed, so changing the text later leaves what earlier visitors agreed to as it was:

import { consent } from "@nextlyhq/plugin-form-builder";

consent({
  name: "privacy",
  label: "Privacy",
  agreementText: "I agree to the privacy policy",
});
// A submission stores: { privacy: { agreed: true, text: "I agree to the privacy policy" } }

The text comes from the form, never from what the visitor sends. A site that renders the form can send the text it showed with the answer, { "agreed": true, "text": "I agree to the privacy policy" }: if the author changed the text while the form was open, the submission is refused, asking the visitor to review it and agree again, rather than recorded as agreement to terms they never saw. A plain checkbox value (on, true) is taken as agreement to the text the form shows when it arrives. A submitted consent cannot be edited: an update that would change or drop it, from the admin or the API, is refused with a validation error, and an edit of other answers keeps it as it was.

Utility Functions

Create a complete form config with defaults applied in one call:

import { createFormConfig } from "@nextlyhq/plugin-form-builder";

const contactForm = createFormConfig("contact", contactFields, {
  settings: {
    submitButtonText: "Send Message",
    confirmationType: "message",
    successMessage: "Thanks! We will get back to you within 24 hours.",
  },
});

Validate a form config before saving:

import {
  validateFormConfig,
  assertValidFormConfig,
} from "@nextlyhq/plugin-form-builder";

const result = validateFormConfig(contactForm);
if (!result.valid) {
  console.error(result.errors);
}

// Or throw on invalid config
assertValidFormConfig(contactForm);

Form Submissions

The handlers below take a { pluginContext, pluginConfig } context. pluginContext is the ctx your code already receives from the plugin system -- for example a plugin route handler's (req, ctx) => ..., or your own plugin's init(ctx). pluginConfig is the object formBuilder() returned: keep the result and use fb.config. Note that getFormBuilderConfig(ctx) is not an alternative from another plugin's context — the resolved config is written onto the form-builder's own context during its init, and initializePlugins gives every plugin a separate one, so that call returns undefined anywhere else.

Handling Submissions

Use the submitForm handler to process submissions server-side. It runs the full pipeline: fetch form, validate data, check spam, store submission, and determine redirect.

import { submitForm } from "@nextlyhq/plugin-form-builder";
import type { PluginContext } from "@nextlyhq/plugin-sdk";
import type { ResolvedFormBuilderConfig } from "@nextlyhq/plugin-form-builder";

declare const request: Request;
declare const pluginContext: PluginContext;
declare const pluginConfig: ResolvedFormBuilderConfig;

const result = await submitForm(
  {
    formSlug: "contact",
    data: { firstName: "Jane", email: "jane@example.com", message: "Hello!" },
    // The language the visitor submitted in. A picked redirect page is read in
    // it, so a page whose slug is `thanks` in English and `merci` in French
    // sends a French visitor to `/merci`. Pass whatever you resolved for the
    // page the form was on; the built-in route reads it from `?locale=`.
    locale: "fr",
    metadata: {
      // No ipAddress here on purpose: see "Where the IP has to come from"
      // below. Reading `x-forwarded-for` straight off the request is the one
      // thing not to do.
      userAgent: request.headers.get("user-agent") || undefined,
    },
  },
  { pluginContext, pluginConfig }
);

if (result.success) {
  if (result.redirect) {
    // Redirect the user
  }
  // result.submission contains the stored document
} else {
  // result.error and result.validationErrors describe what went wrong
}

Where the IP has to come from

submitForm keys two protections on metadata.ipAddress: the per-IP rate limit, and one response per network (below). It also stores the value on the submission.

That makes the header a control input, not a log field. x-forwarded-for is client-supplied on a direct request and on any proxy that forwards it verbatim, so a bot that varies it on every request gets a fresh rate-limit bucket each time and walks past a limit that looks configured. Nextly closed exactly this in its own auth and rate-limit paths, which is why getTrustedClientIp exists:

// nextly.config.ts, or anywhere the application itself runs
import { getTrustedClientIp, parseTrustedProxyIpsEnv } from "nextly";

declare const request: Request;
declare const trustProxy: boolean;

const ipAddress =
  getTrustedClientIp(request, {
    trustProxy,
    trustedProxyIps: parseTrustedProxyIpsEnv(process.env.TRUSTED_PROXY_IPS),
  }) ?? undefined;

It walks the forwarded chain from the right, skipping hops in TRUSTED_PROXY_IPS, and returns the first one you did not vouch for. It returns null when it cannot identify a client, and passing undefined on is the correct thing to do with that: the limiter skips a submission it cannot attribute rather than filing every unknown caller in one bucket.

Two consequences worth stating plainly. security.trustProxy defaults to false, so until you set it and list your proxies the resolver returns null and the rate limit does not run. And getTrustedClientIp ships from nextly, not from @nextlyhq/plugin-sdk, so a distributed plugin cannot reach it through the surface it is supposed to depend on. An application that hosts its own route, as below, can.

One response per person

A form's Settings can limit each person to one response. The server compares a keyed one-way digest of what tells people apart, never the value itself, and a unique index refuses a second submission with the same digest when it is stored, so two sent at once cannot both get in.

Setting (settings.oneResponse)ComparesNotes
offnothingThe default: anyone may respond again.
emailthe answer to the chosen Email field (settings.oneResponseField), ignoring caseThe field must be required and not hidden by a condition, so every response carries an address. Saving a form that breaks this is refused, and the builder will not delete the field, make it optional or give it a condition while it is chosen.
ipthe network addressPeople sharing an office or home network count as one. Needs the trusted IP above.
browsera token the visitor's browser keepsCounted from when it is chosen. Someone who clears their browser's data, or uses another browser, can respond again.

A second response is refused: submitForm answers outcome: "duplicate", and the built-in route answers 409 with the message "You have already submitted this form." A submission marked spam gives its place back.

One per browser needs your form's script. For a form that compares browsers, the public read of the form (GET /api/forms/:slug) says where the token goes:

{
  "oneResponse": { "by": "browser", "field": "nextly-browser-token" }
}

Keep one random token per form in the visitor's browser, and send it inside data under that field:

// One token per form, so a browser's responses to two forms cannot be linked.
function browserToken(formSlug: string): string | undefined {
  const name = `nextly-browser-token:${formSlug}`;
  try {
    const kept = window.localStorage.getItem(name);
    if (kept) return kept;
    const made = crypto.randomUUID();
    window.localStorage.setItem(name, made);
    return made;
  } catch {
    // Storage blocked: send no token.
    return undefined;
  }
}

async function send(formSlug: string, answers: Record<string, unknown>) {
  const token = browserToken(formSlug);
  return fetch(`/api/forms/${formSlug}/submit`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      data: token ? { ...answers, "nextly-browser-token": token } : answers,
    }),
  });
}

The token must be 16 to 128 letters, digits, - or _ (crypto.randomUUID() is one). It is never stored with the submission. A submission that comes without a token, or with a malformed one, is accepted without the check, as a browser that cleared its data would be, and the server logs a warning so a form whose script does not send it is noticed.

Changing the setting counts earlier responses. Choosing one per network, or changing to it from another setting, counts the submissions already stored by their stored address. Earlier responses count for one per email address too, once Settings offers it. Of several earlier submissions with the same value, the earliest keeps it. One per browser counts from when it is chosen, since no earlier token was kept.

A form with up to 200 submissions is brought up to date inside the save itself. A larger one is finished by the plugin's background sweep (form-builder:one-response-keys), which the job runner carries on. Until then each new submission is compared with the earlier ones directly, so nobody gets a second response in the meantime. Set the size with the plugin's oneResponse.keysInSave option:

formBuilder({
  oneResponse: { keysInSave: 50 },
});

When the sweep finishes it records that on the form, which moves the form's revision on. The admin's form editor saves on through that: if nothing it sends has changed, it saves again on the new revision. Your own code that saves forms with _rev should do the same: read the form again and retry.

When a response stops counting. If the submission holding a value is deleted, marked as spam, or edited to another address, the earliest other submission with the same value takes its place. A person who sent two responses before the form compared them still can't send a third.

If a form's setting changes while a submission is on its way, the submission is refused with "This form's settings changed while your response was being sent. Please send it again." and is judged by the new setting when it is sent again.

The page a submission came from

A submission through POST /api/forms/:slug/submit keeps the page it was sent from, taken from the browser's Referer header: the page's origin and path only. Its query string and fragment are dropped, since they can carry personal data, and an address that is not an http or https page is not kept. Each submission's page in the admin shows it under Details › Page. The browser reports it, so it is a hint for staff rather than proof; a site that sends no Referer keeps none. A server-side submitForm call can pass metadata.page itself.

Privacy: not keeping IP addresses

A form's Settings › Privacy › Store IP address and browser (settings.storeIpAndBrowser, on by default) decides whether a new submission keeps the address it came from and the visitor's browser. Off, it keeps neither. One per network still works on such a form: the address's keyed digest is made before the address is dropped, and only the digest is stored. Earlier submissions keep what they stored. A form that keeps no addresses cannot count its earlier responses by network after a change of setting, since it has none to count.

Privacy: deleting old submissions

Settings › Privacy › Delete submissions after (settings.keepDays: Never, 30 days, 90 days or 1 year; none keeps them) sets how long a form keeps its submissions. A pass the plugin schedules each night (the job form-builder:retention, on the @daily schedule form-builder-retention-nightly) deletes every submission older than its form keeps them for, and spam older than 30 days whatever the setting. Age is when the submission was stored (createdAt).

Each one is deleted the way any deletion is, so what it sent goes with it, and so do the files it holds (see File uploads). The pass also deletes the uploads no submission claimed within a day, and finishes any file an earlier deletion could not remove. A pass that runs out of time queues its own continuation, and the next jobs run carries on. Like every schedule, it runs only while something calls the jobs route (/admin/api/jobs/run in a scaffolded app); a night missed is caught up by the next one, which deletes everything past keeping by then.

File uploads

Upgrading: visitors' files are now private. They are kept in the plugin's own form-files collection, never in the media library, and no public address serves them. With no storage set up for that collection they are kept on your server's disk, in .nextly/private. On Vercel, Netlify, AWS Lambda or Cloud Run that disk does not keep them, so file uploads on your forms are refused until you give form-files a private storage. See Where visitors' files are kept. Files visitors sent before the upgrade move from the media library into private storage on their own, in the background: see Files sent before files were private.

A file field's answer is a file id, or a list of them for a field with multiple. The visitor's browser uploads each file first, through a route the plugin contributes, and puts the id it answers with in the submission:

POST /admin/api/forms/:slug/upload
Content-Type: multipart/form-data
PartWhat it is
fieldThe name of one of the form's file fields.
fileThe file. One per request; upload several in turn.

It answers 201 with { message, fileId, mediaId, field, filename, mimeType, size }. Put fileId in the answer. mediaId is the same id, under the name it had when visitors' files went to the media library, so a form written then keeps working; it is deprecated. The file is refused unless:

  • the form exists and takes submissions now: a form that is not published, or one that has closed, answers as submitting to it would (404, or 409 with its closed message);
  • field names one of the form's file fields (400, error path field), and file uploads are enabled (features.fileUploads and fields.file);
  • the file is one the field takes (400, error path file): a type its accept lists (.pdf, image/*, application/pdf; the plugin's uploads.allowedMimeTypes when it lists none), no larger than its maxFileSize, which can never exceed the plugin's uploads.maxFileSize (10 MB by default) and is that when the field sets none. A body larger than the limit is refused without being read whole;
  • the visitor is within the rate limit: five uploads per submission spamProtection.rateLimit allows, per visitor and form, in the same window (429). As with submissions, a visitor whose address cannot be trusted is not limited;
  • the site can keep it privately (503, see Where visitors' files are kept). Nothing is written, and the reason is in the server's log.

The file is stored as a private file in the plugin's form-files collection, and is judged there by what its bytes are: its contents against its type, and its type against the types the collection takes. Those are common images, documents, spreadsheets, slides, plain text, audio, video and zip archives, plus each type uploads.allowedMimeTypes lists exactly (not a pattern such as image/*); SVG, HTML, XML and script types are never taken. Its type is checked against the field again on what was stored.

The plugin records each upload, and a submission's file answer may only name uploads made through this route for the same form and field that no other submission has claimed. Anything else, such as another form's upload, an upload already part of another submission, or the id of a file the site uses, refuses the submission with a validation error on that field ("This file was not uploaded for this field. Please upload it again."). This holds for a visitor submitting and for staff writing through the API. An edit keeps the files a submission already holds: an update may send a field's stored ids back unchanged. A submission flagged as spam is stored without the refusal, as it is stored without validation.

A write no request produced (the Direct API from your own server code, an import, a job) is trusted, as it was before uploads were recorded: nothing it names is refused, and an upload it names for the same form and field that no submission has claimed is claimed for it, so the file stays with that submission. An upload it names that another submission already holds is recorded as this submission's too, so the file stays while either of them names it.

Deleting a submission deletes the files it holds, whichever way it is deleted: one at a time, in bulk, by the nightly pass, or with its form. The file is deleted once the deletion has committed, and only if no other submission holds it, its stored bytes with it. A file sent before visitors' files were private and not moved yet is in the media library, and is deleted only if nothing else uses it (a document's field, an avatar, a logo); a file in use is kept, and checked again each night. Its stored bytes are removed durably: a storage error is retried by the jobs queue until they are gone. An upload no submission claims within a day is deleted by the nightly pass. A file the submission names without holding it (one a trusted write named that was not uploaded through the route, and any file a submission stored before uploads were recorded names) is not deleted with it.

The plugin ships no front-end form of its own, so your site's form does the upload. For example:

/** Upload one file for `field` of the form at `slug`; answers its file id. */
async function uploadFile(slug: string, field: string, file: File) {
  const body = new FormData();
  body.append("field", field);
  body.append("file", file);
  const res = await fetch(`/admin/api/forms/${slug}/upload`, {
    method: "POST",
    body,
  });
  const json = (await res.json()) as {
    fileId?: string;
    error?: { message: string };
  };
  if (!res.ok || !json.fileId) throw new Error(json.error?.message);
  return json.fileId;
}

async function uploadThenSubmit(form: HTMLFormElement, slug: string) {
  const values = new FormData(form);
  const answers: Record<string, unknown> = {};
  for (const name of new Set(values.keys())) {
    const input = form.elements.namedItem(name);
    if (!(input instanceof HTMLInputElement && input.type === "file")) {
      answers[name] = values.get(name);
      continue;
    }
    const ids: string[] = [];
    for (const file of values.getAll(name)) {
      if (file instanceof File && file.size > 0) {
        ids.push(await uploadFile(slug, name, file));
      }
    }
    // A field with `multiple` answers with a list of ids, a single-file
    // field with one id; an empty one is left out.
    if (input.multiple) answers[name] = ids;
    else if (ids[0] !== undefined) answers[name] = ids[0];
  }
  await fetch(`/admin/api/forms/${slug}/submit`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ data: answers }),
  });
}

Where visitors' files are kept

Visitors' files are private files of the plugin's form-files collection. Which storage keeps them is decided as for every private collection:

  • A storage plugin lists form-files: they are kept there, whatever is the default. It must keep them private: with @nextlyhq/storage-s3, that means a bucket with no publicUrl, since a public URL serves every file in its bucket. On Cloudflare R2, keep public access off for that bucket.
  • A storage plugin is the default for private files (defaultForPrivateFiles): they are kept there, with no need to list form-files. A private Vercel Blob store is one by default, and an S3 or R2 bucket with no public URL can be marked as one.
  • Neither: they are kept on the server's own disk, in .nextly/private below your app's root. That suits a server with a disk that lasts, such as a VPS or a container with a volume. Back up .nextly/private with your database.

On a serverless host (Vercel, Netlify, AWS Lambda, Google Cloud Run) the server's disk is read-only or gone after each request. The site still starts, and says so in its log with the fix, but every upload is refused with 503 until a private storage takes form-files, rather than a file being lost or put where anyone could open it. The Forms admin shows the same, beside each file field. To fix it, configure a private storage as the default for private files: on Vercel, a private Blob store; elsewhere, an S3 or R2 bucket with no public URL. Or give form-files one of its own, in nextly.config.ts:

import { s3Storage } from "@nextlyhq/storage-s3";

export default defineConfig({
  plugins: [fb.plugin],
  storage: [
    // A bucket of its own, with NO publicUrl: a public URL would serve
    // every file in it.
    s3Storage({
      bucket: process.env.PRIVATE_BUCKET!,
      region: "auto",
      endpoint: process.env.R2_ENDPOINT,
      accessKeyId: process.env.R2_ACCESS_KEY_ID,
      secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
      collections: { "form-files": true },
    }),
  ],
});

A site that already keeps its media in S3 or R2 with a public URL adds this as a second s3Storage, without one. A storage that cannot keep files private, such as a public Vercel Blob store, cannot take form-files. uploads.uploadCollection is no longer read: remove it.

Opening visitors' files

A submission's page shows each file with its type, size and a Private mark. Its download is Nextly's checked download, which records who downloaded which file in the audit log. Who may download:

  • a person whose role holds both read-form-files and the permission to read submissions (read-form-submissions, or the one your renamed collection has). The Admin, Editor, Author and Viewer roles hold read-form-files from the start, so they need only read submissions, as they already do;
  • nobody else: a person without both sees the file listed but is told to ask an admin for permission to download files. A visitor never reaches it.

A custom role needs read-form-files granted beside its submissions permission; one holding only the submissions permission cannot download. The files collection's permission is not taken from the submissions' one.

Add to media library…, in a file's menu, puts a copy in the media library, for a person who may download the file and add media. The copy can be reached at a public address there, as every media file can; the original stays private with the submission.

Notifications that attach a file field attach these files as they are, read from private storage when each email is sent: see Attaching a file to an email.

Files sent before files were private

Before visitors' files were private, each was a file in the media library. After the upgrade they move into private storage on their own, in the background, a few at a time, each time Nextly's jobs run. Move now on the Submissions page moves them at once, for a person who may change forms. For each file:

  1. A copy goes into form-files, with the same name and type.
  2. The copy is read back and checked against the original, byte for byte (by its SHA-256 hash). A copy that does not match is deleted, and the file stays where it was until the next run.
  3. Each submission's answer, and the plugin's record of the upload, names the copy. Only the file's id changes: the other answers stay as they were sent, even to questions the form no longer asks.
  4. The original is deleted from the media library, unless something else on your site uses it, such as a page it was placed on, or a notification about its submission is still waiting to be sent. That original stays in the media library, and the nightly pass deletes it once nothing needs it; deleting its submission deletes it too, once nothing else uses it.

A move that stops partway, because the server restarted or a run ran out of time, carries on from where it stopped next time, with the copy it already made. Running it again moves nothing twice. Nothing moves while your site cannot keep files privately (see Where visitors' files are kept); the files stay in the media library until it can.

When the move first runs on a server with files left to move, the server's log says how many. The Submissions page shows what will move and what stays, before anything moves, and what you can do about the files that stay:

  • Used elsewhere on your site. The file moves, and the media library keeps the original for as long as something uses it. If it should not be public, remove it from where it is used, such as the page; the nightly pass then deletes it.
  • A type that is never private, such as SVG or HTML, which a browser can run. It stays in the media library, and its submission still names it. Open it from its submission, and delete it from the media library if it should not be public.
  • Larger than uploads.maxFileSize. It stays in the media library. Raise the limit to move it on the next run, or delete it from the media library if it should not be public.
  • Missing. The media library has its record but not its file, so there is nothing to move.

Only files a submission holds move. An upload no submission claimed is deleted by the nightly pass within a day, as before. The move adds a movedFrom column to form-files, which existing installations receive through their migrations: run nextly migrate:create and then nextly migrate (or nextly db:sync in development).

Validation

The plugin generates Zod schemas from form field definitions at runtime. Every submission is validated against the schema before storage, and free-text fields are sanitized by stripping HTML tags to prevent injection.

That happens on a beforeChange hook on the submissions collection, the last collection-level mutating phase before the insert, so it applies to every way a submission can be written: your own route calling submitForm, the built-in POST /admin/api/forms/:slug/submit, nextly.forms.submit(), an admin editing a stored submission, and a record created from the admin. A submission is also projected onto the fields the form declares, so a key the form does not define is dropped rather than stored. Field-level beforeChange hooks run after this one and are handed the whole record, so one you register on this collection yourself is trusted the way core trusts a field hook on any other collection.

Values are sanitized before they are validated, so every rule judges the value that will actually be stored rather than the one that arrived.

A submission flagged as spam is stored without being validated, deliberately, so a false positive stays reviewable rather than being thrown away. That exception ends when the row leaves spam: marking one "Not spam" checks the payload it is carrying against the form, so a row that never satisfied the form has to be corrected in the same edit before it can become an ordinary counted submission.

Spam protection runs on the same hook, and is decided BEFORE the payload is validated. A bot that trips the honeypot while also omitting a required field is stored flagged rather than answered with a validation error, because an error tells it which of the two it got wrong.

The honeypot and the rate limit are facts about an HTTP REQUEST rather than about a row, so they stand down when no request produced the write: a trusted server importing a thousand submissions does not rate-limit its own import, and a honeypot field means nothing without a browser to have skipped it. What separates the two is whether a request reached the hook, not which function was called.

You do not need a route of your own to get any of it. POST /admin/api/forms/:slug/submit is contributed by this plugin and calls submitForm, so a browser posting to it meets the honeypot and the rate limit exactly as one posting to a route you host yourself would. Host your own when you want a different response shape or extra work around the submission, not to obtain spam protection.

The plugin's routes sit directly under wherever your app mounts createDynamicHandlers, which a scaffolded project does at src/app/admin/api/[[...params]]/route.ts: hence /admin/api. A bare /api/forms/... is a 404 there (see Routes).

On a localized site, post to /admin/api/forms/:slug/submit?locale=fr from a French page. The locale decides which translation the redirect target is read in, so the visitor lands on that page's French URL; a submission that names none is answered in the default language. A code the site does not have reads as the default rather than refusing the submission — the visitor filled the form in, and a wrong query string is not a reason to lose it. The target is read as the visitor, so a translation that is still a draft is not where they are sent: the published default answers until the translation is published.

You can validate data without creating a submission:

import { validateSubmission } from "@nextlyhq/plugin-form-builder";
import type { PluginContext } from "@nextlyhq/plugin-sdk";
import type { ResolvedFormBuilderConfig } from "@nextlyhq/plugin-form-builder";

declare const pluginContext: PluginContext;
declare const pluginConfig: ResolvedFormBuilderConfig;

const { valid, errors } = await validateSubmission(
  "contact",
  { firstName: "Jane", email: "not-an-email" },
  { pluginContext, pluginConfig }
);

Submission Status

Each submission tracks its review state:

StatusDescription
newUnread submission
readReviewed by an admin
archivedArchived (hidden from default views)

Admins can also add internal notes to any submission -- these are not visible to the original submitter.

Deleting submissions

Deleting a submission forgets the notifications it sent, in the same transaction: one not yet sent (waiting, retrying, or failed) is cancelled and its message cleared, so nothing goes out from data that is gone, and the delivery records of one that went out are erased. This holds for deleting one submission, deleting several at once, and deleting a form, which deletes its submissions with it.

It also deletes the files the submission holds, once the deletion has committed (see File uploads).

Marking a submission as spam calls off its notifications the same way, in the transaction that marks it: one waiting to be sent or retried, or one that failed and could still be retried, is cancelled and its message cleared, so it is not sent and cannot be retried later. One that the provider is sending at that moment finishes: it ends sent if the provider takes it, and cancelled if that attempt fails. The delivery records of what already went out are kept until the submission is deleted.

The plugin keeps what each submission sent in an internal form-submission-sends collection, which no caller can read or write. Existing installations receive it through their own migrations: run nextly migrate:create and then nextly migrate (or nextly db:sync in development). A notification queued before the upgrade was not recorded, so deleting its submission does not forget it. The uploads made through the upload route are kept the same way, in an internal form-uploads collection, which existing installations receive through the same migration.

Statistics

import { getFormSubmissionStats } from "@nextlyhq/plugin-form-builder";
import type { PluginContext } from "@nextlyhq/plugin-sdk";
import type { ResolvedFormBuilderConfig } from "@nextlyhq/plugin-form-builder";

declare const pluginContext: PluginContext;
declare const pluginConfig: ResolvedFormBuilderConfig;

const stats = await getFormSubmissionStats("contact", {
  pluginContext,
  pluginConfig,
});
// { total: 42, new: 5, read: 30, archived: 7 }

Email Notifications

Notifications are configured per form in the admin UI under the Notifications tab, a list of the form's notifications with who each goes to, when it sends, its message and an Active switch. Add notification starts one from a preset: Notify your team (addresses you type, with Reply-To set to the visitor's Email field) or Confirm to the visitor (the address in one of the form's Email fields; unavailable until the form has one). Each notification opens on its own page, at the Notifications page's address with ?section=<id>, where you choose who gets it (several addresses, Cc and Bcc, Reply-To), when it sends (every submission, or when all or any of several conditions hold), its message from Settings › Email, the file fields whose files go with it, and its From and Provider, which default to the message's own. Edits are saved with the form.

Each notification specifies:

SettingDescription
templateSlugEmail template to use (from your email configuration)
recipientType"static" (fixed email) or "field" (value from a form field)
toEmail address, or {{fieldName}} reference when using field recipient
recipientsA team notification's addresses, when it sends to several
replyToReply-To: an address, or {{fieldName}} for one of the form's Email fields
conditions{ match: "all" | "any", list }: send only when all, or any, hold
attachFieldsNames of the form's file fields whose files go with this email
providerIdEmail provider to use (optional, falls back to system default)
cc / bccAdditional recipients

Template variables available in your email templates: all submitted field values, plus formName and submissionId.

A notification saved before recipients, conditions and attachFields existed reads as it always did: its single to is a list of one, its single condition is a list of one under all, and it attaches exactly the file fields whose "attach to notification emails" switch is on. An email with one recipient reaches a beforeEmail handler with to as a string, as before; one with several, as a list.

Delivery and retries

Each notification is queued in the same transaction that saves its submission, then sent as soon as that transaction commits. The submission and its queued notifications are kept together or not at all: a save that fails or is rolled back queues nothing, and a server that stops just after the save still sends them on the next jobs run. Only active notifications whose conditions the answers meet are queued. A submission flagged as spam queues none, and marking it "Not spam" later does not send them either.

A failure that a retry can help (the provider is down, or times out) is not dropped: it is tried again, with a growing wait between attempts, until it is sent or fails for good. Retries run when your site calls the jobs trigger (POST /admin/api/jobs/run, see Jobs), so schedule that call on any site that sends form notifications. A refusal no retry can change, such as an invalid address, fails at once.

A notification that fails for good is logged twice, and the two lines share the queued email's id (queuedId): the Form Builder's line names the form and the notification, and the server's own queued-email-failed line gives the reason. Neither names a recipient.

What each send did, and Resend

A submission's page lists every notification it triggered under Emails, and each recipient with what became of it and when: Waiting, Retrying, Sending, Sent, Sent after N retries, Failed, or Cancelled (in Settings › Email, by marking the submission Spam, or by erasing the address). A notification whose recipients differ reads Partly sent. A notification's own page lists its Recent sends across the form's submissions.

The plugin keeps this with the submission, in its internal form-submission-sends collection, written in the same transaction as each change of the queued email, so it never falls behind what was sent. Recipients are kept by a masked hint (j•••@acme.test) and a keyed digest, never by address. The record outlives core's delivery log, which is pruned after 90 days, does not change when the submission's answers or the notification are edited later, and is deleted with the submission.

Resend sends a notification of a submission again, to the recipients who have not received it, built from the notification and the answers as they are now. You may tick a recipient who did receive it, among those the notification can address now, to send it to them again. A recipient a send filter added is left out once it has received it. When only copied (Cc or Bcc) recipients missed it, each gets a message addressed to them alone. A failed earlier send whose message is still held is retired in the same transaction, so it cannot be retried as well. Resend is not offered while a send of the notification is waiting, retrying or sending; the page says a send is in progress. It needs both update-<submissions> and manage-email-deliveries, and records who asked.

The routes, under /admin/api/plugins/@nextlyhq/plugin-form-builder:

  • GET /submissions/:id/sends (reading submissions): each notification with its recipients and whether a send is in progress.
  • GET /notification-sends?form=&notification=&limit= (reading submissions): a notification's recent sends.
  • POST /submissions/:id/resend with { notification, tick? } (updating submissions and managing email deliveries).

Existing installations receive the new fields of form-submission-sends and the new internal form-submission-resends collection through their migrations: run nextly migrate:create and then nextly migrate (or nextly db:sync in development). A send recorded before the upgrade has no notification or recipients on record, so it is not listed.

beforeEmail Hook

Modify or filter outgoing emails before they are queued. The hook runs inside the transaction that saves the submission: a hook that throws refuses the submission, and the hook may run again if that transaction is retried, so keep it to changing the emails and do no other work in it.

const fb = formBuilder({
  beforeEmail: async ({ emails, form, submission }) => {
    return emails.map(email => ({
      ...email,
      bcc: ["archive@example.com"],
    }));
  },
});

Spam Protection

Three layers of protection: a honeypot and a rate limit, both on by default, and a bot check (Google reCAPTCHA v3 or Cloudflare Turnstile) once you configure its keys.

Honeypot Fields

Hidden form fields that bots fill in automatically. When a honeypot field contains a value, the submission is stored flagged as spam and the bot receives an ordinary success response, so the detection is not revealed.

Standard honeypot field names checked: __honeypot, _honeypot, honeypot, __hp, _hp, website, url_field, fax_number.

Rate Limiting

Limits submissions per IP address and form within a time window. Defaults to 10 submissions per 60 seconds per IP.

spamProtection: {
  rateLimit: {
    maxSubmissions: 5,
    windowMs: 120_000, // 2 minutes
  },
}

The rate limit uses the deployment's shared rate-limit store, rateLimit.store in defineConfig, which falls back to memory. With several instances and no shared store, each instance counts on its own.

Bot checks: reCAPTCHA and Turnstile

A bot check runs in the visitor's browser and gives the form a token, which the server verifies with the provider before the submission is accepted:

  • Google reCAPTCHA v3 scores each visitor in the background, with no puzzle to solve. A score below scoreThreshold (default 0.5) fails.
  • Cloudflare Turnstile checks each visitor in the background and rarely shows a puzzle.

Set each provider's keys in the plugin's options. enabled makes a provider the site default, which forms use unless their Settings choose another check or Off (reCAPTCHA wins when both are enabled):

spamProtection: {
  recaptcha: {
    enabled: true,
    siteKey: 'your-recaptcha-site-key',
    secretKey: 'your-recaptcha-secret-key',
    scoreThreshold: 0.5,
  },
  turnstile: {
    enabled: false,
    siteKey: 'your-turnstile-site-key',
    secretKey: 'your-turnstile-secret-key',
  },
}

Setting a provider's secretKey also declares its verification host in the plugin's outbound allowlist (www.google.com or challenges.cloudflare.com). A site using neither gives the plugin no network access.

Rendering the widget. For a form whose check is on, the public read of the form (GET /api/forms/:slug) includes what the widget needs:

{
  "botCheck": {
    "provider": "turnstile",
    "siteKey": "…",
    "field": "cf-turnstile-response"
  }
}

Render the provider's widget with that site key, and send its token inside data under field: g-recaptcha-response for reCAPTCHA or cf-turnstile-response for Turnstile, the names each provider's widget writes by default. It is never stored with the submission.

What happens to a submission:

  • Token passes: accepted as usual.
  • Token fails or is missing: stored flagged as spam (reason recaptcha or turnstile), as a honeypot hit is, so a false positive stays reviewable and the bot still sees a success.
  • Provider unreachable or answers something unexpected: accepted unchecked and logged, so an outage does not send every real submission to spam.
  • Check on but the provider has no secretKey: accepted unchecked, as before checks were verified. The server logs a warning at start naming the option to set, Settings says so on the form, and a check without its keys cannot be newly chosen in Settings.

The check is verified where every submission is stored, so it applies to the built-in route, submitForm, nextly.forms.submit() with a request, and the generic collection create. A server-side call with no request (an import) is not checked.

Forms saved before this change keep their protection. A form whose reCAPTCHA setting was left to the plugin follows the site default, one with reCAPTCHA on uses reCAPTCHA, and one with it off has no check. A form that stored its own reCAPTCHA site key keeps using it until the plugin's options give one, and its Settings ask to move it there.

Conditional Logic

Fields can be shown or hidden based on the values of other fields. Configure conditional logic on any field through the admin UI or in code.

import { text, select, option } from "@nextlyhq/plugin-form-builder";

const fields = [
  select({
    name: "contactMethod",
    label: "Preferred Contact Method",
    options: [option("Email"), option("Phone")],
  }),
  text({
    name: "phoneNumber",
    label: "Phone Number",
    conditionalLogic: {
      enabled: true,
      action: "show",
      operator: "AND",
      conditions: [
        { field: "contactMethod", comparison: "equals", value: "phone" },
      ],
    },
  }),
];

Supported comparison operators: equals, notEquals, contains, isEmpty, isNotEmpty, greaterThan, lessThan.

Multiple conditions can be combined with AND (all must match) or OR (any must match). The action property determines whether matching conditions show or hide the field.

Webhooks

Form submissions are delivered through Nextly's own webhooks: subscribe an endpoint to the form.submission.created event. Its payload says which form, when, and the submission's status, and its resource.id names the submission (resource.slug is the submissions collection, form-submissions unless you renamed it). It never carries the answers, the IP address or the user agent, so a receiver that needs them reads the submission by that id:

  • A receiver in another system calls the REST API: GET /admin/api/collections/form-submissions/entries/{id}, authenticated with an API key that may read submissions (read-form-submissions).
  • A receiver inside the same Next.js app can use the Direct API instead.

Verify each delivery's signature as the Webhooks page describes, before reading anything.

A form has no webhook settings of its own, and the submissions collection's default entry.* events are switched off, so an endpoint subscribed to entry.created or * does not receive the answers either.

Forms on Page Builder Pages

With the page builder installed, its Form block can place any of these forms on a page. The block lists the forms (drafts and closed ones marked, each with a link to edit it), draws the picked one on the server, and visitors send it as an ordinary HTML form post, with no JavaScript. A post arrives at the page builder's form route and is handed to this plugin, which runs the same submitForm its JSON address runs, with the visitor's request: the same validation, storage, emails, honeypot, rate limit, bot check and one-response rules.

  • A page places the form, not a copy of it. Saving the form (its fields, options, labels, settings), publishing, unpublishing, closing or deleting it shows on every page that places it, its header and footer included, at once, with no save of the pages. A form closing by its closing time or its response limit shows within about a minute.
  • The form's own confirmation applies: its message in the form's place, or its redirect (a page of this site). The block may choose its own instead.
  • A closed form shows its closed message on the page; a deleted one shows nothing.
  • Each field starts as its author set it: a dropdown or radio list on its defaultValue, checkboxes ticked, a text field filled. A consent box is never ticked for the visitor, and a hidden field's value is read from the stored form when it is sent. A dropdown's empty first choice reads its placeholder, and startEmpty: false leaves it out. An option's description is drawn under its label, in quieter text, and read by a screen reader as the choice's description. Its style parts are choice-label and choice-description.
  • A choice field's layout, pictures and Other choice all work without JavaScript. A choice with a picture is drawn as a card (style parts choice-card and choice-picture), its radio or checkbox kept in sight; the chosen card's border takes the site's primary colour, and a card with keyboard focus shows a ring. Its image is read as an Image block reads its own, and is decoration: the label names the choice. The Other box is always shown beside its choice (style part choice-other); words typed with nothing picked count as Other.
  • A second answer to a one-response form is answered as "This form isn't taking answers right now."
  • Conditional fields all show on the page, and the plugin ignores the answers to any whose condition does not hold, as it does for every submission.
  • A form with a bot check loads one small script of this plugin's own on pages that draw it, which renders the Turnstile or reCAPTCHA widget, and holds a send until its token is made. Without JavaScript no token is sent, and the submission is kept as spam, as at the JSON address.
  • A form with a file field is sent with its files in one plain post, with or without JavaScript. Each file goes through the same checks as this plugin's upload route (POST /api/forms/:slug/upload): uploads switched on, the visitor's upload limit, the field's size limit, and its accepted types, judged by the file's name, its type and Nextly's check of its contents. A field takes one file, or up to five where it takes several. The submission then claims the files as one sent to the JSON address claims its uploads. If a file or the submission is refused, every file stored for it is deleted at once, and a post kept as spam for a missing bot-check token stores none. Files are stored as private files, as the upload route stores them (see Where visitors' files are kept). On Vercel a request's body is capped at 4.5 MB, on this path and the upload route alike.
  • A form taking one response per browser gets its browser token from the same script.
  • The script's address, like the page builder's form route, assumes Nextly's handler is mounted at /admin/api, as a scaffolded project mounts it.
  • A conditional field that is required is checked by the server only while its condition holds; the page does not ask the browser to require it.
  • The words the form shows that its author didn't write follow the page's language (see Words visitors see in their language).
  • A send refused for an answer the browser can't check itself (a required set of checkboxes with none ticked, or Other picked and its box left empty) comes back with the reason beside that field, with no JavaScript.

The JSON address, POST /api/forms/:slug/submit, is unchanged. The two plugins reach each other only through the page builder's forms service and the plugin SDK's form provider contract, which is experimental.

Where a form is used

With the page builder installed, the Forms admin says where each form is placed:

  • The form editor's bar shows Used on 2 pages. It opens the list: each page's title, whether it is published or a draft, and a link to open it. A Single that places the form, such as a homepage, is listed by its name and opens the Single. A page you may not open is counted, never named.
  • A form inside a component that a header & footer set uses is shown on every page the set wraps. The set is listed apart from the pages ("Used on 2 pages + header & footer"), with a link to edit it, and marked Site default when it is the site's default.
  • The Forms list has a Pages column: how many pages place each form, "—" for none, and "+ header & footer" where a set places it.
  • Before you delete a form that is on pages or in a header & footer, or move a live one to Draft or Closed, the question names the pages (up to five, then "and N more") and the sets, says when a set is the site default (every page that follows the default shows the form), and says what the pages will show: nothing where the form was once it is deleted or while it is a draft, and its closed message once it is closed. It asks; it never stops you.

A page counts when its published version or its working draft places the form, directly or inside a component it places. Pages are named as their collection names its entries. While the page builder is still recording the pages a site had before this version, a count reads "at least N", and the list says it may be missing some. Each time you open the form or the Forms list, the answer is read again. Without the page builder, none of this is shown, and the Pages column shows "—".

Exporting Submissions

Export submissions to CSV or JSON from code or the admin UI. The examples below assume you already have form (a FormDocument) and submissions (a SubmissionDocument[]) -- for example, from ctx.services.collections in a plugin route or hook.

CSV Export

import {
  exportToCSV,
  downloadFile,
  generateExportFilename,
} from "@nextlyhq/plugin-form-builder";
import type {
  FormDocument,
  SubmissionDocument,
} from "@nextlyhq/plugin-form-builder";

declare const form: FormDocument;
declare const submissions: SubmissionDocument[];

const csv = exportToCSV(submissions, form, {
  includeMetadata: true,
  delimiter: ",",
  includeBOM: true, // Excel compatibility
  dateFormat: "iso",
});

// Browser download
const filename = generateExportFilename("contact", "csv");
// "contact-submissions-2026-03-20.csv"
downloadFile(csv, filename, "text/csv;charset=utf-8");

JSON Export

import { exportToJSON } from "@nextlyhq/plugin-form-builder";
import type {
  FormDocument,
  SubmissionDocument,
} from "@nextlyhq/plugin-form-builder";

declare const form: FormDocument;
declare const submissions: SubmissionDocument[];

const json = exportToJSON(submissions, form, {
  includeMetadata: true,
  includeFormDefinition: true,
  indent: 2,
});

One-Step Export

import { exportAndDownload } from "@nextlyhq/plugin-form-builder";
import type {
  FormDocument,
  SubmissionDocument,
} from "@nextlyhq/plugin-form-builder";

declare const form: FormDocument;
declare const submissions: SubmissionDocument[];

// In a React component
const handleExport = (format: "csv" | "json") => {
  exportAndDownload(submissions, form, format);
};

Example: Contact Form

A complete contact form setup from config to submission handling.

1. Configure the plugin:

// nextly.config.ts
import { defineConfig } from "nextly";
import { formBuilder } from "@nextlyhq/plugin-form-builder";

const fb = formBuilder({
  notifications: {
    defaultFrom: "noreply@mysite.com",
  },
  spamProtection: {
    honeypot: true,
    rateLimit: { maxSubmissions: 5, windowMs: 60_000 },
  },
});

export default defineConfig({
  plugins: [fb.plugin],
  collections: [Posts, Users, Media],
});

2. Define the form fields (code-first):

import {
  text,
  email,
  textarea,
  select,
  checkbox,
  option,
  hidden,
  createFormConfig,
} from "@nextlyhq/plugin-form-builder";

const contactForm = createFormConfig("contact", [
  text({ name: "name", label: "Full Name", required: true }),
  email({ name: "email", label: "Email", required: true }),
  select({
    name: "subject",
    label: "Subject",
    required: true,
    options: [
      option("General Inquiry"),
      option("Support"),
      option("Partnership"),
    ],
  }),
  textarea({
    name: "message",
    label: "Message",
    required: true,
    rows: 5,
    validation: { maxLength: 5000 },
  }),
  checkbox({ name: "newsletter", label: "Subscribe to updates" }),
  hidden({ name: "source", label: "Source", defaultValue: "website" }),
]);

createFormConfig builds the definition and stops there. Nothing in the plugin accepts a FormConfig: formBuilder() takes no forms option, and submitForm resolves a slug by querying the forms collection, so a form exists at submission time only as a row in that collection. Create the contact form in the admin under Forms before going further, or seed the row yourself; a submission to a slug with no row is answered as a form that does not exist, before validation or storage. Closing that gap is tracked as createFormConfig having no path to a row.

3. Handle submissions in an API route:

submitForm takes two context values: pluginContext, which is a plugin's ctx, and pluginConfig, which is the resolved form-builder config. Both are reachable from your own config file. A route contributed through contributes.routes is handed the ctx as its second argument, and formBuilder() returns its resolved config as fb.config, which is why step 1 keeps the return value rather than inlining it.

So the endpoint is a small plugin of your own, declared beside the form-builder in nextly.config.ts:

// nextly.config.ts
import {
  defineConfig,
  getTrustedClientIp,
  parseTrustedProxyIpsEnv,
} from "nextly";
import { definePlugin } from "@nextlyhq/plugin-sdk";
import { formBuilder, submitForm } from "@nextlyhq/plugin-form-builder";

const fb = formBuilder({
  notifications: { defaultFrom: "noreply@mysite.com" },
  spamProtection: {
    honeypot: true,
    rateLimit: { maxSubmissions: 5, windowMs: 60_000 },
  },
});

const contactEndpoint = definePlugin({
  name: "@acme/contact-endpoint",
  version: "1.0.0",
  nextly: ">=0.0.2-alpha.63",
  contributes: {
    routes: [
      {
        method: "POST",
        path: "/contact",
        // A visitor has no session, so the route opts out of auth. What stops
        // abuse is `submitForm` itself: the honeypot and rate limit configured
        // above run on every call, and a route that skipped it would skip them.
        public: true,
        handler: async (request, ctx) => {
          const data = await request.json();

          // Through the trust-proxy gate, never straight off the header: this
          // value keys the rate limit above, so a forgeable one hands a bot a
          // fresh bucket per request. `null` becomes `undefined`, which the
          // limiter reads as "cannot attribute" and skips.
          const ipAddress =
            getTrustedClientIp(request, {
              trustProxy: ctx.config.security?.trustProxy ?? false,
              trustedProxyIps: parseTrustedProxyIpsEnv(
                process.env.TRUSTED_PROXY_IPS
              ),
            }) ?? undefined;

          const result = await submitForm(
            {
              formSlug: "contact",
              data,
              metadata: {
                ipAddress,
                userAgent: request.headers.get("user-agent") ?? undefined,
              },
            },
            { pluginContext: ctx, pluginConfig: fb.config }
          );

          return Response.json(result);
        },
      },
    ],
  },
});

export default defineConfig({
  plugins: [fb.plugin, contactEndpoint],
  // collections: [...] as in step 1
});

The route is mounted under the contributing plugin's namespace, so the form posts to /admin/api/plugins/@acme/contact-endpoint/contact in a scaffolded app, where /admin/api is wherever createDynamicHandlers is mounted.

Next Steps

  • Plugins Overview -- how the plugin system works and how to create custom plugins
  • Email Configuration -- set up email providers and templates for form notifications
  • Collections -- understand how plugin collections work alongside your own