Next.js contact form that sends email
Formgong team ·
A Next.js contact form can send email without your own mail server. Use a client component and fetch to post the fields to Formgong, with your public access key. That works in the App Router, the Pages Router, and a static export. Telegram is instant. Email arrives for each submission, on the free plan too.
App Router client component
Save this file as app/contact-form.tsx. It is a client component because it uses state.
The handler calls preventDefault, checks the fields, and posts FormData. It does not set Content-Type.
It treats the send as a failure unless response.ok and result.success are both true. The button stays disabled while the request runs.
Leave botcheck empty. That honeypot is how simple bots are caught.
Every plan emails each submission right away. On the free plan it goes to up to 3 addresses.
Telegram is instant on every plan, including Free. Free emails up to 3 recipients, Pro up to 5. There is no auto-reply on Free.
// app/contact-form.tsx
"use client";
import { useState } from "react";
// Paste your key: replace fk_your_access_key with the key from your Formgong form.
const ACCESS_KEY = "fk_your_access_key";
export default function ContactForm() {
const [status, setStatus] = useState("idle");
const [notice, setNotice] = useState("");
async function onSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
if (!(form instanceof HTMLFormElement) || !form.reportValidity()) return;
const body = new FormData(form);
body.set("access_key", ACCESS_KEY);
body.set("_lang", "en");
setStatus("sending");
setNotice("");
try {
const response = await fetch("https://formgong.com/submit", {
method: "POST",
headers: { Accept: "application/json" },
body,
});
const result = await response.json();
if (!response.ok || !result.success) {
setStatus("error");
setNotice(result.message || "Could not send. Please try again.");
return;
}
form.reset();
setStatus("success");
setNotice(result.message || "Sent. Thank you!");
} catch {
setStatus("error");
setNotice("Connection failed. Please try again.");
}
}
const sending = status === "sending";
return (
<form onSubmit={onSubmit}>
<label>{"Name"} <input name="name" autoComplete="name" placeholder={"Your name"} required /></label>
<label>{"Email"} <input name="email" type="email" autoComplete="email" placeholder={"you@example.com"} required /></label>
<label>{"Message"} <textarea name="message" placeholder={"How can we help?"} required /></label>
<div aria-hidden="true" style={{ position: "absolute", insetInlineStart: 0, top: 0, width: 1, height: 1, overflow: "hidden", clipPath: "inset(50%)" }}>
<input name="botcheck" tabIndex={-1} autoComplete="off" />
</div>
<button type="submit" disabled={sending}>{sending ? "Sending…" : "Send"}</button>
<p role={status === "error" ? "alert" : "status"}>{notice}</p>
</form>
);
}App Router page that renders the form
// app/contact/page.tsx
import ContactForm from "../contact-form";
export default function ContactPage() {
return (
<main>
<h1>Contact</h1>
<ContactForm />
</main>
);
}Pages Router: the same component, without use client
// components/ContactForm.js
// Pages Router files are client components. Do not add "use client".
import { useState } from "react";
// Paste your key: replace fk_your_access_key with the key from your Formgong form.
const ACCESS_KEY = "fk_your_access_key";
export default function ContactForm() {
const [status, setStatus] = useState("idle");
const [notice, setNotice] = useState("");
async function onSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
if (!(form instanceof HTMLFormElement) || !form.reportValidity()) return;
const body = new FormData(form);
body.set("access_key", ACCESS_KEY);
body.set("_lang", "en");
setStatus("sending");
setNotice("");
try {
const response = await fetch("https://formgong.com/submit", {
method: "POST",
headers: { Accept: "application/json" },
body,
});
const result = await response.json();
if (!response.ok || !result.success) {
setStatus("error");
setNotice(result.message || "Could not send. Please try again.");
return;
}
form.reset();
setStatus("success");
setNotice(result.message || "Sent. Thank you!");
} catch {
setStatus("error");
setNotice("Connection failed. Please try again.");
}
}
const sending = status === "sending";
return (
<form onSubmit={onSubmit}>
<label>{"Name"} <input name="name" autoComplete="name" placeholder={"Your name"} required /></label>
<label>{"Email"} <input name="email" type="email" autoComplete="email" placeholder={"you@example.com"} required /></label>
<label>{"Message"} <textarea name="message" placeholder={"How can we help?"} required /></label>
<div aria-hidden="true" style={{ position: "absolute", insetInlineStart: 0, top: 0, width: 1, height: 1, overflow: "hidden", clipPath: "inset(50%)" }}>
<input name="botcheck" tabIndex={-1} autoComplete="off" />
</div>
<button type="submit" disabled={sending}>{sending ? "Sending…" : "Send"}</button>
<p role={status === "error" ? "alert" : "status"}>{notice}</p>
</form>
);
}
// pages/contact.js
import ContactForm from "../components/ContactForm";
export default function ContactPage() {
return (
<main>
<h1>Contact</h1>
<ContactForm />
</main>
);
}Server Action with Zod, when you already have a server
// app/contact/actions.ts
"use server";
import { z } from "zod";
const schema = z.object({
name: z.string().trim().min(1, "Name is required").max(200),
email: z.string().trim().email("Enter a valid email").max(200),
message: z.string().trim().min(1, "Message is required").max(5000),
botcheck: z.string().max(0).optional(),
});
export type ContactState = {
ok: boolean;
message: string;
fieldErrors?: Partial<Record<"name" | "email" | "message", string>>;
};
export async function submitContact(_prev: ContactState, formData: FormData): Promise<ContactState> {
const parsed = schema.safeParse({
name: formData.get("name"),
email: formData.get("email"),
message: formData.get("message"),
botcheck: String(formData.get("botcheck") ?? ""),
});
if (!parsed.success) {
const flat = parsed.error.flatten().fieldErrors;
// A filled honeypot looks like success. The bot learns nothing.
if (flat.botcheck?.length) return { ok: true, message: "Thanks. We have your message." };
return {
ok: false,
message: "Check the fields and try again.",
fieldErrors: {
name: flat.name?.[0],
email: flat.email?.[0],
message: flat.message?.[0],
},
};
}
try {
const response = await fetch("https://formgong.com/submit", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({
access_key: process.env.FORMGONG_ACCESS_KEY,
_lang: "en",
name: parsed.data.name,
email: parsed.data.email,
message: parsed.data.message,
}),
});
const result = await response.json();
if (!response.ok || !result.success) {
return { ok: false, message: result.message || "Could not send. Try again." };
}
return { ok: true, message: result.message || "Thanks. We have your message." };
} catch {
return { ok: false, message: "Could not send. Try again." };
}
}
// React 19 exports useActionState from "react".
// Older docs import useFormState from "react-dom". That import fails on React 19.
"use client";
import { useActionState } from "react";
import { submitContact, type ContactState } from "./actions";
const initial: ContactState = { ok: false, message: "" };
export function ContactForm() {
const [state, action, pending] = useActionState(submitContact, initial);
return (
<form action={action}>
<label>
Name
<input name="name" autoComplete="name" required aria-invalid={state.fieldErrors?.name ? true : undefined} />
</label>
{state.fieldErrors?.name ? <p id="name-error">{state.fieldErrors.name}</p> : null}
<label>
Email
<input name="email" type="email" autoComplete="email" required aria-invalid={state.fieldErrors?.email ? true : undefined} />
</label>
{state.fieldErrors?.email ? <p id="email-error">{state.fieldErrors.email}</p> : null}
<label>
Message
<textarea name="message" required aria-invalid={state.fieldErrors?.message ? true : undefined} />
</label>
{state.fieldErrors?.message ? <p id="message-error">{state.fieldErrors.message}</p> : null}
<div aria-hidden="true" style={{ position: "absolute", insetInlineStart: 0, top: 0, width: 1, height: 1, overflow: "hidden", clipPath: "inset(50%)" }}>
<input name="botcheck" tabIndex={-1} autoComplete="off" />
</div>
<button type="submit" disabled={pending}>{pending ? "Sending…" : "Send"}</button>
{state.message ? <p role={state.ok ? "status" : "alert"}>{state.message}</p> : null}
</form>
);
}Static export: output export
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "export",
};
module.exports = nextConfig;Turnstile, after you turn it on
// Inside the <form>, after the message field. The site key is public.
// Load the script once, from app/layout.tsx or pages/_document.js:
// <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<div className="cf-turnstile" data-sitekey="YOUR_TURNSTILE_SITE_KEY" data-language="en" />
// Keep the fetch body as FormData. Do not set Content-Type.
// The widget writes cf-turnstile-response, and FormData sends it.
const body = new FormData(form);
body.set("access_key", process.env.NEXT_PUBLIC_FORMGONG_KEY ?? "");
body.set("_lang", "en");
await fetch("https://formgong.com/submit", {
method: "POST",
headers: { Accept: "application/json" },
body,
});.env.local
# .env.local # Public access key. NEXT_PUBLIC_ is inlined into the browser bundle. NEXT_PUBLIC_FORMGONG_KEY=fk_your_access_key # Server Action only. No NEXT_PUBLIC_ prefix, so the value stays on the server. FORMGONG_ACCESS_KEY=fk_your_access_key
Read the public key in the component
const ACCESS_KEY = process.env.NEXT_PUBLIC_FORMGONG_KEY ?? "";
Environment variables
NEXT_PUBLIC_ names are inlined into the browser bundle at build time. The access key is public, so NEXT_PUBLIC_FORMGONG_KEY is the right name for the client component.
Restart next dev after you change .env.local. A static export bakes the value in when you run next build.
A Server Action can read FORMGONG_ACCESS_KEY with no prefix. That value is not shipped to the browser. It is still a public access key, not a secret.
Never put RESEND_API_KEY, an SMTP password, or a Turnstile secret key behind NEXT_PUBLIC_. Anyone can read the bundle.
The Turnstile secret stays in Formgong, under Protection. The page only gets the site key.
Common errors
These are the failures that show up after the form looks finished.
Missing use client
The form uses useState. In the App Router the file needs the client directive at the top.
Without it, Next.js treats the file as a Server Component and the build fails. The page that renders the form can stay a Server Component.
Server Action with a static export
Next.js lists Server Actions as unsupported when output is export. The same list includes route handlers that read the request.
The client fetch still works, because the POST leaves the browser. Do not add an API route for this form.
The key is undefined
NEXT_PUBLIC_FORMGONG_KEY is empty until you restart next dev, or until you rebuild a static export.
A name without the NEXT_PUBLIC_ prefix is undefined in client code. The browser never sees it.
Content-Type on FormData
If you set Content-Type yourself, the browser cannot add the multipart boundary. The server then cannot read the fields.
Send Accept: application/json and leave Content-Type unset. Use a JSON body only when you build the object yourself.
Success before the response
Show thanks only after response.ok and result.success are both true. A network error and a 400 are not a sent lead.
Read result.message for the reason. turnstile_missing means the widget did not run, or Turnstile is on and the token was not posted.
CORS and allowed domains
The submit route sends Access-Control-Allow-Origin: *. A page on your domain, including localhost, may call it.
On every plan you can limit the form to your domains. If that list is on and the page host is missing, the lead is refused. Free has the domain list too.
Double submit
Each successful POST is a new lead. The sample disables the button while status is sending.
React Strict Mode runs some setup twice in development. It does not submit the form by itself.
CSP connect-src
If the page sets a Content-Security-Policy, fetch is blocked unless connect-src includes https://formgong.com.
Turnstile also needs the Cloudflare challenges host in script-src and frame-src. Add those only when the widget is on.
Resend or a form backend
Resend is an email API. A contact form on top of it is a Server Action, a secret, and DNS on a domain you own.
Pick Resend when the mail must leave from your domain at once, or when the same account also sends password resets and receipts.
Pick Formgong when the page is a contact form, a static export, or a site with no domain of its own yet.
| Resend | Formgong | |
|---|---|---|
| What you add | An API key, a verified domain, and a Server Action or route handler. | One public access key in the client component. |
| Domain and DNS | You verify a domain you own. Resend gives DKIM and SPF records (TXT, and MX or CNAME). | No domain and no DNS records. Mail is sent from noreply@formgong.com. |
| Where the key lives | RESEND_API_KEY stays on the server. A NEXT_PUBLIC_ prefix would publish it. | The access key is public. It can submit this form. It cannot read the inbox. |
| Free quota | 3,000 transactional emails a month, and 100 a day (UTC). Up to 3 domains. | 250 submissions a month. Up to 3 email recipients. |
| When email arrives | When Resend accepts the message, it is sent then. | Right away for each submission, on every plan. |
| Telegram | Not part of Resend. It sends email. | Instant on every plan, including Free. |
| Static export | Server Actions are unsupported with output: 'export'. You need a server. | The client component still posts. The host only serves HTML, CSS and JavaScript. |
| Spam | You build the filter, or you add a CAPTCHA and a rate limit. | botcheck is always checked. A filled honeypot is stored as spam and is not emailed or sent to Telegram. Turnstile is optional. |
| Where data sits | Resend's pricing page lists 30-day data retention on Free. It does not say EU-only. | In the EU, on Cloudflare D1. Free retention is 30 days. |
Resend figures are from its pricing page and domain docs on 6 October 2026. The free plan there is 3,000 transactional emails a month, 100 a day, and 3 domains. Formgong's free plan is 250 submissions a month. That number is the plan limit in the product code.
Honest limits
Free stores 250 submissions a month and keeps them for 30 days. Up to 3 verified recipients get an email for each submission. There is no auto-reply on Free.
A lead scored as spam is stored and is not emailed and is not sent to Telegram. Open the inbox if a test seems missing, then check the spam folder for noreply@formgong.com.
A Server Action that posts to Formgong sends every lead from your server's IP. That weakens rate limits and spam signals. The client component does not have that problem.
Proxying the public key through an action does not hide anything useful. The key cannot read the inbox. On every plan you can limit the allowed domains instead.
This sample uses Zod 3: z.string().email() and error.flatten(). On Zod 4 those names are z.email() and flattenError(). The rest of the action stays the same.
A contact form is one of the ways to collect a lead without a backend of your own. The same fetch pattern is on the React contact form and the JavaScript contact form. After a successful post, use a thank-you page after form submission or the message in this component. Quotas are on the pricing page.
How forms work in Next.js
In the App Router, the native way to handle a form is a Server Action or a route handler. It usually calls an email API with a secret key and DNS records on your domain. That needs a server runtime, and Server Actions are not supported when you export the site with output: 'export'.
A client component that posts to https://formgong.com/submit needs none of that. It works on Vercel, on any Node host, and as a static export. Telegram and email arrive right away, on the free plan too. The lead is also stored in the Formgong inbox.
Set it up in Next.js
- Create a form in Formgong and copy the access key.
- Add the component below. It starts with
"use client"because it handles a browser event. - Replace the key, or read it from a
NEXT_PUBLIC_variable; only those reach browser code. - Render the component on your page, run
next devand send a test. - Prefer a package?
@formgong/reactgives you a ready<ContactForm>, and the Next.js starter on GitHub is a complete project.
Ready starter on GitHub: github.com/formgong/nextjs-starter. MIT license: click “Use this template” or copy the files.
New project in one command: npm create formgong@latest -- --template nextjs (npm: create-formgong)
Component package: npm install @formgong/next (npm: @formgong/next)
Add to an existing project: npx formgong init (npm: formgong)
Formgong or a Server Action?
Write a Server Action when the submission has to change your data or check a signed-in user.
Use Formgong for contact, quote and lead forms. You skip the email provider, the secret and the spam code. On the free plan, Telegram and email both arrive for each lead.
Questions and answers
How do I send email from a Next.js contact form?
Paste the client component on this page. It posts the fields to Formgong. Telegram is instant on every plan. Every plan emails each submission. Free sends to up to 3 addresses, Pro to up to 5.
Does it work with static export?
Yes. A client component that posts to Formgong needs no server. Server Actions are not supported in a static export. The browser still sends the POST.
Pages Router or App Router?
Both. In the Pages Router, drop the "use client" line. The Pages Router sample on this page shows the files. A Server Action needs a server, so it is not part of a static export.
Do I need Resend or a Server Action?
Not for a contact form. Resend needs a verified domain and DNS records, and the API key stays on a server. Write a Server Action when the submit must change your database or check a signed-in user.
How do I stop spam on a Next.js form?
Leave botcheck empty. Formgong marks a filled honeypot as spam and does not email it or send it to Telegram. Turnstile is optional. Add the widget only after you turn it on in the form settings. The secret stays on Formgong.
Articles on this topic
Related pages
Guides
- Formgong for agencies
- Static website contact form
- Netlify Forms alternative
- GDPR-compliant contact form
- Formspree alternatives
- Formcarry alternatives
- Formspark alternatives
- Splitforms alternatives
- Formgrid alternatives
- FormBackend alternatives
- Formbold alternatives
- Formester alternatives
- HeroTofu alternatives
- KwesForms alternatives
- Sheet Monkey alternatives
- Slapform alternatives
- Static Forms alternatives
- ShipMyForm alternatives
- Contact Form 7 alternatives
- WPForms alternatives
- Zapier Forms alternatives
- Forminit alternatives
- Fillout alternatives
- Formstack alternatives
- Microsoft Forms alternatives
- Paperform alternatives
- Freedback alternatives
- Pageclip alternatives
- EmbedSocial alternative
- Trustindex alternative
- Senja alternative
- Shapo alternative
- Junip alternative
- Famewall alternative
- FormKeep alternatives
- Jotform alternatives
- Basin alternatives
- Getform alternatives
- FormSubmit alternatives
- Typeform alternatives
- Tally alternatives
- Wufoo alternatives
- Google Forms alternatives
- Formgong alternatives
- Formsite alternatives
- Form for photographers
- Form for restaurants
- Form for clinics
- Form for real estate
- Form for lawyers
- Best form backend services
- Form endpoint services tested
- Contact form APIs tested
- Web3Forms alternatives
- EmailJS alternatives
- Formspree vs Web3Forms
- Formspree vs EmailJS
- Formspree vs Getform (Forminit)
- Formspree vs Basin
- Formspree vs FormSubmit
- Web3Forms vs Netlify Forms
- Netlify Forms vs Formspree
- Jotform vs Typeform
- Judge.me vs Yotpo
- Judge.me vs CusRev: the WooCommerce question
- Best free form backends
- Free website templates
- Testimonial and rating widget
- Judge.me alternative
- Yotpo alternative
- Loox alternative
- Stamped alternative
- Okendo alternative
- Fera alternative
- CusRev alternative
- Trustpilot alternative
- Testimonial.to alternative
- Elfsight alternative
- Trustmary alternative
- Boast alternative
- REVIEWS.io alternative
- Endorsal alternative
- AI builder prompts
- Form checker
- AI form generator
- Form builder
- Tailwind form generator
- Bootstrap form generator
- Booking form generator
- Order form generator
- Registration form generator
- Contact form generator
- HTML form generator
- HTML form builder
- Survey form generator
- Feedback form generator
- Newsletter signup form generator
- RSVP form generator
- Job application form generator
- T-shirt order form
- Cake order form
- Custom order form
- Rental application form
- Time off request form
- Donation request form
- Volunteer form
- Daycare registration form
- Maintenance request form
- Prayer request form
- Emergency contact form
- Review schema generator
- Google review link generator
- Contact form examples
- HTML contact form code
- React contact form component
- Next.js contact form template
- Tailwind contact form template
- Shopify contact form Liquid
- Webflow contact form code
- Framer contact form component
- Astro contact form component
- Vue contact form component
- Ghost contact form
- WordPress contact page template
- Agent rules files
- Tools