Tutorial

A Next.js contact form whose fields and conditions live in the CMS

A Next.js contact form CMS setup: fields, labels and show/hide conditions come from Cmssy, the submit runs on your server, and you decide who gets email.

M
Maciej Bednarczyk
6 min read

A Next.js contact form whose fields and conditions live in the CMS

A Next.js contact form CMS setup: fields, labels and show/hide conditions come from Cmssy, the submit runs on your server, and you decide who gets email.

Choose "E-bike" in this Next.js contact form and a "Battery model" field appears. Choose "Road" and it's gone. That rule isn't in the component. Spokes & Co, the repair shop in our example, added it in the Form Builder, so this is a contact form whose fields, labels and conditions come from the CMS while the markup and the submit stay in your Next.js code.

Three things decide whether a CMS-driven form works in production, and this tutorial covers each: how the form definition reaches your component, how the submit stays on your server, and where a submission goes afterwards. On that last one, be precise with your client. Cmssy stores every submission and can notify the shop's own addresses. It doesn't send the person who filled in the form anything; a confirmation email to them is your code.

Left: the contact form on cmssy.com/contact with name, email and message fields. Right: blocks/contact/actions.ts from the cmssy-web repository, a server action that collects the form data and calls submitForm.
The fields come from the form in Cmssy; the submit is a server action in your app.

Before you start

Tool Version Source
Node.js 22.13 or newer, below 23 engines in examples/next-storefront/package.json
Next.js / React 16.3.1 / 19.2.8 same file
@cmssy/core, @cmssy/react, @cmssy/next 19.33 or newer (19.36.1 current) same file; cmssy-sdk/packages/*/package.json
GraphQL Codegen @graphql-codegen/cli 7.2.0, client-preset 6.1.0, graphql 17.0.2 devDependencies in the same file

The example generates SubmitFormDocument from the delivery schema with pnpm codegen. If you'd rather not run codegen, write the mutation as a string the way the blog tutorial does.

git clone https://github.com/cmssy-io/examples
cd examples/next-storefront
pnpm install && cp .env.example .env.local && pnpm dev

1. Build the form in Cmssy

In the admin, open Forms and create one. For Spokes & Co, the repair shop in our example, that's:

  1. A name field (text, required), an email field (email, required) and a message field (textarea, required). Each label is stored per language, so the Polish site gets its own labels from the same form.
  2. A submit button label, a success message and an error message, also per language.
  3. The recipient addresses for the notification, if you want one. This is the shop's own inbox, not the customer's.
  4. Status: published. Only a published form accepts submissions.

Conditional fields are part of the form too. A field can be shown, or made required, only when another field has a certain value. Remember that for step 7.

Cmssy Form builder for the demo Contact form. Top: a required topic select with choices quote, product, order and other. Bottom: an orderNumber text field with Show this field when Topic equals order highlighted, and the same rule for Require this field when.
A conditional field defined in the form, not in the component.

2. Define the block

The block in next-storefront has a heading, an intro text and a required form picker.

// blocks/contact-form/ContactForm.tsx (schema and server component)
import { fields, type BlockProps } from "@cmssy/react";
import { ContactFormFields } from "./ContactFormFields";
import styles from "./ContactForm.module.css";

export const contactFormProps = {
  heading: fields.text({ label: "Heading" }),
  text: fields.textarea({ label: "Text" }),
  form: fields.form({ label: "Form", required: true }),
};

export default function ContactForm({
  content,
  context,
}: BlockProps<typeof contactFormProps>) {
  const form = content.form ? context?.forms?.[content.form] : undefined;
  if (!form || !context) return null;

  return (
    <section className={styles.section}>
      {content.heading ? (
        <h2 className={styles.heading}>{content.heading}</h2>
      ) : null}
      {content.text ? <p className="shop-muted">{content.text}</p> : null}
      <ContactFormFields
        form={form}
        locale={{
          locale: context.locale.current,
          defaultLocale: context.locale.default,
        }}
      />
    </section>
  );
}
// blocks/contact-form/block.ts
import { defineBlock } from "@cmssy/react";
import ContactForm, { contactFormProps } from "./ContactForm";

export const contactFormBlock = defineBlock({
  type: "contact-form",
  label: "Contact form",
  component: ContactForm,
  props: contactFormProps,
});

Notice the block never fetches the form. When the page renders, the SDK collects every form referenced on it and passes the definitions on context.forms, keyed by id. No form picked means the block renders nothing, not a placeholder.

3. Render whatever fields the form declares

ContactFormFields is the client half. Two parts of it matter here; the full file, which handles every field type, is ContactFormFields.tsx.

The form body maps over the definition. visibleFormFields and isFormFieldRequired come from @cmssy/core and evaluate the conditions you set in the Form Builder against the values typed so far:

<form
  ref={formRef}
  className={`shop-card ${styles.form}`}
  onSubmit={submit}
  onChange={() => setValues(readValues())}
>
  {visibleFormFields(fields, values).map((field) => (
    <div
      key={field.id}
      className={field.width === "half" ? styles.half : styles.full}
    >
      <FieldInput
        field={field}
        required={isFormFieldRequired(field, values)}
        locale={locale}
      />
    </div>
  ))}
  <input
    type="text"
    name="website"
    tabIndex={-1}
    autoComplete="off"
    aria-hidden
    className={styles.trap}
  />
  {/* error message and submit button */}
</form>

FieldInput switches on field.fieldType: a textarea, a select or multiselect with the form's options, radio buttons, a checkbox for boolean, a hidden input, and a plain <input> with the right type for email, phone, URL, number and dates. Labels, placeholders and help texts go through a localizedText helper, because translatable values arrive either as a string or as a { en, pl, ... } map.

The website input is a honeypot. People never see it; simple bots fill it in. Its value goes to the server with the submission.

4. Submit on the server

The click handler calls a server action and shows the form's own success or error message:

function submit(event: React.FormEvent<HTMLFormElement>) {
  event.preventDefault();
  const entries = new FormData(event.currentTarget);
  const data = formValues(fields, entries);
  const website = String(entries.get("website") ?? "");
  startTransition(async () => {
    const result = await submitFormAction(form.id, data, website);
    if (result.ok && result.redirectUrl) {
      router.push(result.redirectUrl);
      return;
    }
    setOutcome({
      ok: result.ok,
      message: result.ok
        ? text(form.settings.successMessage) || result.message || ""
        : result.message || text(form.settings.errorMessage),
    });
    if (result.ok) formRef.current?.reset();
  });
}

The action itself is short:

// lib/actions/forms.ts
"use server";

import { CmssyGraphqlError } from "@cmssy/core";
import { submitForm } from "@/services/forms";

export interface FormActionResult {
  ok: boolean;
  message: string | null;
  redirectUrl: string | null;
}

export async function submitFormAction(
  formId: string,
  data: Record<string, unknown>,
  website: string,
): Promise<FormActionResult> {
  try {
    const result = await submitForm(String(formId), data, String(website));
    return {
      ok: result.success,
      message: result.message || null,
      redirectUrl: result.redirectUrl ?? null,
    };
  } catch (error) {
    if (error instanceof CmssyGraphqlError) {
      return { ok: false, message: error.message, redirectUrl: null };
    }
    throw error;
  }
}

submitForm in services/forms.ts sends the SubmitForm mutation (public.form.submit) with { data, website } as input. The mutation answers with success, message, submissionId and an optional redirectUrl, which is set when the form is configured to redirect after submit. In the storefront it also signs the request as the logged-in member when there is one; for a plain marketing site, the anonymous path is all you need.

5. Register and deploy

// cmssy/blocks.ts
import { contactFormBlock } from "@/blocks/contact-form/block";

export const blocks = [/* your other blocks */ contactFormBlock];

Deploy the app as usual. There's no separate step for blocks; they ship with the app. Open your contact page in the editor, add "Contact form", pick the form, and publish.

6. See where a submission goes

Submit the form on the live site. The submission lands under the form in the admin, with each answer next to its field. If you set recipients on the form, Cmssy sends them a notification. For anything else, such as a ticket in your helpdesk, a row in a CRM or an auto-reply to the customer, subscribe a webhook to form.submitted and do it in your own code; the webhooks guide covers verifying it and handling retries.

7. Let the owner add the e-bike rule

Now the owner edits the form in the admin:

  1. Renames the message label from "Message" to "What's wrong with the bike?".
  2. Adds a bikeType select with City, Road, Cargo and E-bike.
  3. Adds a batteryModel text field that shows only when bikeType is E-bike.
  4. Publishes.

Your component didn't change. It mapped over three fields before and maps over five now, and the battery field appears only when someone chooses E-bike, because visibleFormFields reads the condition from the form definition. The page shows the new form on its next render; to make that the next request after publishing, wire the cache route from the landing page tutorial.

What it can't do (yet)

  • Cmssy doesn't email the person who sent the form. It notifies the recipient addresses on the form; a "thanks, we got your message" email is your code, triggered by form.submitted.
  • Cmssy doesn't render the form. Your component does, so accessibility and styling are yours too.
  • This example skips two field types. renderableFields filters out file and password; if you need an upload, that's extra code.
  • A honeypot filters simple bots, not determined ones. Add rate limiting or a captcha in your action if spam gets through.

Read the code and the docs