Skip to content

Contact Form

This example builds a /contact page in a Next.js App Router site. The browser reads the form’s definition from Plenary with getForm, renders an input for each field, and submits with submitForm using your public API key. It shows Plenary’s per-field validation errors next to the right input and includes both anti-spam fields.

Because the markup is generated from the definition, adding or changing a field in the console changes the form on your site with no code change.

Submitting from the browser is the recommended pattern for public forms:

  • Each visitor has their own rate limit. Plenary allows 10 submits per minute per form, per client IP. A browser submit counts against the visitor’s IP; a submit from your server would count every visitor against your server’s single IP.
  • Entries record the visitor. Each entry’s source holds the visitor’s IP address and user agent, not your server’s.
  • The page stays cacheable. The definition, with its fresh anti-spam ts token, is read when the form loads in the browser, so the page itself can be statically generated or served from a CDN.

The trade-off is that the form needs JavaScript. A public key is designed for browser code: it can read form definitions and submit forms, and nothing else.

  • Node.js 20 or later and a Next.js 16 App Router project with TypeScript and the default @/* import alias (npx create-next-app@latest sets this up).
  • @plenary/client 1.0.x: npm install @plenary/client.
  • A Plenary instance, and a public API key assigned to your site (Access Management → API Keys). Set its Allowed origins to your site’s origins (for example https://www.example.com and http://localhost:3000) so other sites cannot borrow your quota. See API keys.
  • A form with the key contact, active and assigned to your site. Create it under Forms → New form with these fields, then Save form:
Key Name Type Required Settings
name Name text yes Validation max_length 80
email Email email yes
topic Topic select no Options Sales / sales, Support / support
message Message text yes UI control textarea; validation min_length 10, max_length 2000

The code handles any form field type except object, list, and json, so you can add fields later without editing it.

.env.local
# Your instance's origin, without /api/v1. Placeholder: replace with your host.
NEXT_PUBLIC_PLENARY_BASE_URL=https://your-instance.plenarycms.io
# The public API key (starts with pln_pub_). Safe in the browser.
NEXT_PUBLIC_PLENARY_PUBLIC_KEY=pln_pub_YOUR_PUBLIC_KEY
# The key of the site the form belongs to.
NEXT_PUBLIC_PLENARY_SITE_KEY=default

The NEXT_PUBLIC_ prefix makes Next.js include these values in the browser bundle, at build time. Only ever do that with a public key; a private key must never have this prefix.

lib/plenary-browser.ts Plenary client for browser code, and the form key
app/contact/fields.ts Helpers: reading field settings, converting values, error messages
app/contact/ContactForm.tsx Client Component: loads the definition, renders fields, submits
app/contact/page.tsx The page, statically generated
lib/plenary-browser.ts
import { createClient } from "@plenary/client";
/** The key of the form in Plenary (Forms → your form → Settings → Key). */
export const CONTACT_FORM_KEY = "contact";
/**
* A Plenary client for browser code, using the public key. Next.js inlines
* NEXT_PUBLIC_ variables at build time, so they must be referenced literally.
*/
export const plenaryBrowser = createClient({
baseUrl: process.env.NEXT_PUBLIC_PLENARY_BASE_URL!,
apiKey: process.env.NEXT_PUBLIC_PLENARY_PUBLIC_KEY!,
siteKey: process.env.NEXT_PUBLIC_PLENARY_SITE_KEY!,
locale: "en-us",
});

Real inputs are named field.<key> so that a form field can never collide with the reserved website and ts names, even if your form defines its own website field.

readValue converts each field’s FormData entries to the JSON type the field expects. fieldMessage turns one of Plenary’s field error codes into a readable message.

app/contact/fields.ts
import type { PublicFormField } from "@plenary/client";
/** Inputs are named `field.<key>` so a form field can never collide with `website` or `ts`. */
export const FIELD_PREFIX = "field.";
export interface SelectOption {
label: string;
value: string;
}
/** The options of a select or multi_select field, from `settings.options`. */
export function optionsOf(field: PublicFormField): SelectOption[] {
const options = field.settings?.options;
if (!Array.isArray(options)) return [];
return options.filter(
(o): o is SelectOption =>
typeof o === "object" &&
o !== null &&
typeof (o as SelectOption).label === "string" &&
typeof (o as SelectOption).value === "string",
);
}
/** Reads a string from `ui`, e.g. `placeholder`, `control`, `help_text`. */
export function uiString(field: PublicFormField, name: string): string | undefined {
const value = field.ui?.[name];
return typeof value === "string" ? value : undefined;
}
/** Reads a number from `validation`, e.g. `min_length`, `max_length`, `min_val`. */
export function ruleNumber(field: PublicFormField, name: string): number | undefined {
const value = field.validation?.[name];
return typeof value === "number" ? value : undefined;
}
/** Turns one field's FormData entries into the JSON value Plenary expects, or undefined for "not answered". */
export function readValue(field: PublicFormField, formData: FormData): unknown {
const raw = formData
.getAll(FIELD_PREFIX + field.key)
.filter((v): v is string => typeof v === "string");
const first = raw[0] ?? "";
switch (field.type) {
case "boolean":
return raw.length > 0;
case "number":
return first === "" ? undefined : Number(first);
case "multi_select":
return raw.length > 0 ? raw : undefined;
case "tags": {
const tags = first
.split(",")
.map((t) => t.trim())
.filter((t) => t !== "");
return tags.length > 0 ? tags : undefined;
}
case "object":
case "list":
case "json":
// This example does not render structured fields.
return undefined;
default:
return first === "" ? undefined : first;
}
}
/** A readable message for one of Plenary's field error codes. */
export function fieldMessage(code: string, vars: Record<string, unknown>): string {
switch (code) {
case "entry_field_required":
case "entry_field_required_nonempty":
case "entry_field_value_required":
return "This field is required.";
case "entry_field_value_taken":
return "This value has already been used.";
case "entry_field_rule_violation":
if (vars.rule === "min_length") return `Use at least ${vars.min_length} characters.`;
if (vars.rule === "max_length") return `Use at most ${vars.max_length} characters.`;
return "This value is not in the expected format.";
default:
return "This value is not valid.";
}
}

The component loads the definition when it mounts, then submits with submitForm, passing the honeypot and the ts token as options. A PlenaryError becomes either a per-field message (when vars.field names a field) or a form-level message. The inputs are uncontrolled, so a failed attempt keeps what the visitor typed.

app/contact/ContactForm.tsx
"use client";
import { useEffect, useState } from "react";
import { PlenaryError, type PublicFormDefinition, type PublicFormField } from "@plenary/client";
import { plenaryBrowser, CONTACT_FORM_KEY } from "@/lib/plenary-browser";
import { FIELD_PREFIX, fieldMessage, optionsOf, readValue, ruleNumber, uiString } from "./fields";
type Status = "loading" | "unavailable" | "ready" | "sending" | "sent";
const INPUT_TYPES: Record<string, string> = {
email: "email",
url: "url",
phone: "tel",
number: "number",
date: "date",
time: "time",
color: "color",
};
/** Off-screen rather than display:none, so simple bots still see and fill it. */
const honeypotStyle: React.CSSProperties = {
position: "absolute",
left: "-10000px",
width: "1px",
height: "1px",
overflow: "hidden",
};
function FieldInput({ field }: { field: PublicFormField }) {
const name = FIELD_PREFIX + field.key;
const id = `contact-${field.key}`;
const placeholder = uiString(field, "placeholder");
switch (field.type) {
case "boolean":
return <input id={id} name={name} type="checkbox" required={field.required} />;
case "select": {
const options = optionsOf(field);
if (uiString(field, "control") === "radio") {
return (
<span>
{options.map((o) => (
<label key={o.value}>
<input type="radio" name={name} value={o.value} required={field.required} />
{o.label}
</label>
))}
</span>
);
}
return (
<select id={id} name={name} defaultValue="" required={field.required}>
<option value="">{placeholder ?? "Choose…"}</option>
{options.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
);
}
case "multi_select":
return (
<span>
{optionsOf(field).map((o) => (
<label key={o.value}>
<input type="checkbox" name={name} value={o.value} />
{o.label}
</label>
))}
</span>
);
case "text":
if (uiString(field, "control") === "textarea") {
return (
<textarea
id={id}
name={name}
placeholder={placeholder}
required={field.required}
minLength={ruleNumber(field, "min_length")}
maxLength={ruleNumber(field, "max_length")}
rows={6}
/>
);
}
break;
case "object":
case "list":
case "json":
// Structured fields need a custom input; this example skips them.
return null;
}
return (
<input
id={id}
name={name}
type={INPUT_TYPES[field.type] ?? "text"}
placeholder={placeholder ?? (field.type === "tags" ? "Comma-separated" : undefined)}
required={field.required}
minLength={ruleNumber(field, "min_length")}
maxLength={ruleNumber(field, "max_length")}
min={ruleNumber(field, "min_val")}
max={ruleNumber(field, "max_val")}
step={field.type === "number" ? "any" : undefined}
autoComplete={uiString(field, "autocomplete") ?? (field.type === "email" ? "email" : undefined)}
/>
);
}
export function ContactForm() {
const [form, setForm] = useState<PublicFormDefinition | null>(null);
const [status, setStatus] = useState<Status>("loading");
const [message, setMessage] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
// Read the definition in the browser, so every visitor gets a fresh `ts` token.
useEffect(() => {
plenaryBrowser.getForm(CONTACT_FORM_KEY).then(
(definition) => {
setForm(definition);
setStatus("ready");
},
() => setStatus("unavailable"),
);
}, []);
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!form) return;
const formData = new FormData(event.currentTarget);
const data: Record<string, unknown> = {};
for (const field of form.fields) {
const value = readValue(field, formData);
if (value !== undefined) data[field.key] = value;
}
const website = formData.get("website");
setStatus("sending");
setMessage(null);
setFieldErrors({});
try {
await plenaryBrowser.submitForm(CONTACT_FORM_KEY, data, {
website: typeof website === "string" ? website : "",
ts: form.ts,
});
setStatus("sent");
} catch (err) {
setStatus("ready");
const vars = err instanceof PlenaryError ? (err.vars ?? {}) : {};
if (err instanceof PlenaryError && typeof vars.field === "string") {
setFieldErrors({ [vars.field]: fieldMessage(err.code, vars) });
} else if (err instanceof PlenaryError && err.code === "form_entry_rate_limited") {
setMessage("Too many messages from this address. Try again in a minute.");
} else {
setMessage("Something went wrong. Please try again.");
}
}
}
if (status === "loading") return <p>Loading the form…</p>;
if (status === "unavailable" || !form) return <p role="alert">The contact form is not available right now.</p>;
if (status === "sent") {
return <p role="status">Thanks — your message was sent. We will be in touch soon.</p>;
}
return (
<form onSubmit={onSubmit}>
{message && <p role="alert">{message}</p>}
{form.fields.map((field) => {
const helpText = uiString(field, "help_text");
return (
<div key={field.key}>
<label htmlFor={`contact-${field.key}`}>
{field.name}
{field.required && " *"}
</label>
<FieldInput field={field} />
{helpText && <small>{helpText}</small>}
{fieldErrors[field.key] && <p role="alert">{fieldErrors[field.key]}</p>}
</div>
);
})}
{/* Anti-spam: a honeypot that must stay empty. The `ts` token is sent from the definition. */}
<div aria-hidden="true" style={honeypotStyle}>
<label htmlFor="contact-website">Leave this field empty</label>
<input id="contact-website" name="website" type="text" tabIndex={-1} autoComplete="off" defaultValue="" />
</div>
<button type="submit" disabled={status === "sending"}>
{status === "sending" ? "Sending…" : "Send"}
</button>
</form>
);
}

Plenary validates one field at a time and reports the first failure, so a submit returns at most one field error. The browser’s own checks (required, minLength, maxLength, which the form sets from the definition) catch most problems before the request is sent.

Plenary checks two anti-spam values:

  • website is a honeypot. People never see it; bots that fill every input do. A non-empty value stores the entry as spam.
  • ts is the token from the definition. A submit less than 3 seconds after the definition was read stores the entry as spam.

In both cases the visitor still sees the success message, so a bot cannot tell it was caught.

app/contact/page.tsx
import { ContactForm } from "./ContactForm";
export default function ContactPage() {
return (
<main>
<h1>Contact us</h1>
<ContactForm />
</main>
);
}

The page has no server-side data, so Next.js generates it statically. The anti-spam check still works on a cached page, because each visitor’s browser reads the definition, and with it a fresh ts token, when the form loads.

Terminal window
npm run dev

Open http://localhost:3000/contact, fill in the form, wait a few seconds, and click Send. The page shows the success message. In the console, Forms → Open entries on the Contact card lists the new form entry with status New, and its source shows your own IP address and browser.

To see a server-side field error, temporarily remove the minLength prop from the <textarea> in ContactForm.tsx and send a five-character message. The form shows “Use at least 10 characters.” under Message, keeping your other values.

If the form shows “not available”, open the browser’s developer tools. A 403 api_key_origin_not_allowed means the key’s Allowed origins do not include the page’s origin.

Situation What the visitor sees What Plenary stores
Valid submit Success message Form entry, status new; notifications and form.submitted webhooks fire
Honeypot filled, or submitted within 3 seconds Success message Form entry, status spam; nothing fires
A field fails validation Message under that field, values kept Nothing
More than 10 submits per minute from the visitor’s IP “Too many messages…” Nothing
Form inactive, not on this site, or the key’s origin not allowed “The contact form is not available right now.” Nothing