Almost every business website needs a contact form, and almost every contact form ends up as a target for bots. In the Next.js App Router you no longer need a separate API route for this: a Server Action can receive the form, validate it and send the enquiry, while the page keeps working even before JavaScript loads.

This tutorial builds that form step by step:

  1. A plain form component
  2. A Server Action that receives it
  3. Validation with Zod
  4. A honeypot field and a timing check for bots
  5. Field errors and a pending state with useActionState

It assumes Next.js 15 or later (React 19) with the App Router and TypeScript. Install Zod with npm install zod.

1. The form component

Start with a normal HTML form. Every field needs a name, because the Server Action receives a FormData object.

// app/contact/contact-form.tsx 'use client'; import { useActionState } from 'react'; import { sendEnquiry, type FormState } from './actions'; const initial: FormState = { ok: false, message: '', errors: {} }; export function ContactForm() { const [state, formAction, pending] = useActionState(sendEnquiry, initial); return ( <form action={formAction} noValidate> <label htmlFor="name">Name</label> <input id="name" name="name" autoComplete="name" required /> {state.errors.name && <p role="alert">{state.errors.name[0]}</p>} <label htmlFor="email">Email</label> <input id="email" name="email" type="email" autoComplete="email" required /> {state.errors.email && <p role="alert">{state.errors.email[0]}</p>} <label htmlFor="message">How can we help?</label> <textarea id="message" name="message" rows={5} required /> {state.errors.message && <p role="alert">{state.errors.message[0]}</p>} {/* Honeypot: hidden from people, tempting for bots (step 4) */} <div aria-hidden="true" style={{ position: 'absolute', left: '-10000px' }}> <label htmlFor="company_site">Leave this empty</label> <input id="company_site" name="company_site" tabIndex={-1} autoComplete="off" /> </div> <input type="hidden" name="started_at" value={Date.now()} /> <button type="submit" disabled={pending}> {pending ? 'Sending…' : 'Send enquiry'} </button> {state.message && <p role="status">{state.message}</p>} </form> ); } 

The component is a Client Component only because useActionState is a hook. The page that renders it can stay a Server Component:

// app/contact/page.tsx import { ContactForm } from './contact-form'; export const metadata = { title: 'Contact us' }; export default function ContactPage() { return ( <main> <h1>Contact us</h1> <ContactForm /> </main> ); } 

2. The Server Action

A Server Action is an async function marked with 'use server'. When it's used with useActionState, it receives the previous state first and the FormData second, and whatever it returns becomes the new state.

// app/contact/actions.ts 'use server'; export type FormState = { ok: boolean; message: string; errors: Partial<Record<'name' | 'email' | 'message', string[]>>; }; export async function sendEnquiry(prev: FormState, formData: FormData): Promise<FormState> { // filled in over the next steps return { ok: true, message: 'Thanks, we will reply within one working day.', errors: {} }; } 

One thing to keep in mind from the Next.js docs: a Server Action is reachable by a direct POST request, just like an API route. Treat everything in formData as untrusted input, and never rely on the client-side required attributes alone.

3. Validate with Zod

Define the shape once and let Zod produce the field errors:

import { z } from 'zod'; const Enquiry = z.object({ name: z.string().trim().min(2, 'Please enter your name.').max(100), email: z.string().trim().email('Please enter a valid email address.'), message: z.string().trim().min(20, 'A little more detail helps us reply properly.').max(5000), }); 

Inside the action:

const parsed = Enquiry.safeParse({ name: formData.get('name'), email: formData.get('email'), message: formData.get('message'), }); if (!parsed.success) { return { ok: false, message: 'Please check the highlighted fields.', errors: parsed.error.flatten().fieldErrors, }; } 

safeParse never throws, so a bad submission becomes a normal return value and the form shows the errors next to each field. (The flatten() call is the Zod 3 API; Zod 4 also offers z.flattenError().)

4. Stop most bots with a honeypot and a timing check

You can add a CAPTCHA later if you need one, but two cheap checks remove a large share of automated spam without bothering real visitors:

  • Honeypot: the company_site field is moved off-screen and removed from the tab order. People never fill it; simple bots fill every input they find.
  • Timing: started_at records when the form was rendered. A human takes more than a couple of seconds to type a message; many bots submit instantly.
const honeypot = String(formData.get('company_site') ?? ''); const startedAt = Number(formData.get('started_at') ?? 0); const tooFast = Date.now() - startedAt < 3000; if (honeypot !== '' || tooFast) { // Pretend it worked, so the bot learns nothing. return { ok: true, message: 'Thanks, we will reply within one working day.', errors: {} }; } 

The value is set by the client, so a determined attacker can fake it. That's fine: these checks are a filter, not a security boundary. For forms that get targeted heavily, add rate limiting per IP address (for example with your hosting platform's firewall or a small Redis counter) and, if needed, a CAPTCHA such as Cloudflare Turnstile.

5. Send the enquiry and return a result

Put it together and hand the clean data to whatever delivers your leads: your email provider's API, your CRM, or a queue.

'use server'; import { z } from 'zod'; const Enquiry = z.object({ name: z.string().trim().min(2, 'Please enter your name.').max(100), email: z.string().trim().email('Please enter a valid email address.'), message: z.string().trim().min(20, 'A little more detail helps us reply properly.').max(5000), }); export type FormState = { ok: boolean; message: string; errors: Partial<Record<'name' | 'email' | 'message', string[]>>; }; const THANKS = 'Thanks, we will reply within one working day.'; export async function sendEnquiry(prev: FormState, formData: FormData): Promise<FormState> { const honeypot = String(formData.get('company_site') ?? ''); const tooFast = Date.now() - Number(formData.get('started_at') ?? 0) < 3000; if (honeypot !== '' || tooFast) return { ok: true, message: THANKS, errors: {} }; const parsed = Enquiry.safeParse({ name: formData.get('name'), email: formData.get('email'), message: formData.get('message'), }); if (!parsed.success) { return { ok: false, message: 'Please check the highlighted fields.', errors: parsed.error.flatten().fieldErrors }; } try { await deliverLead(parsed.data); // your email API, CRM or queue } catch { return { ok: false, message: 'Sorry, something went wrong. Please email us instead.', errors: {} }; } return { ok: true, message: THANKS, errors: {} }; } async function deliverLead(data: z.infer<typeof Enquiry>) { // e.g. POST to your email provider or CRM; keep API keys in server-only env vars } 

Because the API keys are only used inside the action, they never reach the browser bundle.

What you get

  • The form submits even if JavaScript hasn't loaded yet, because it is a real <form> posting to a Server Action.
  • Once hydrated, useActionState gives you inline field errors and a pending button without writing a fetch call.
  • Validation lives on the server, where it can't be skipped.
  • Most bot traffic is dropped quietly before it reaches your inbox or CRM.

Two production notes: Server Actions have a default request body limit of 1 MB (configurable with serverActions.bodySizeLimit in next.config), which is plenty for text forms but matters if you add file uploads; and if you log submissions, strip or mask personal data according to your privacy policy.

FAQ

Do I still need an API route for forms in Next.js?
Not for forms used by your own pages. A Server Action covers it. Keep an API route if other systems (a mobile app, a partner) need to post to the same endpoint.

Is a honeypot enough to stop spam?
It stops a lot of simple bots. Pair it with rate limiting, and add a CAPTCHA only if spam still gets through, since every extra step costs some genuine enquiries.

Can I use this with React Hook Form?
Yes. Many teams keep React Hook Form for instant client-side feedback and still validate again in the Server Action with the same Zod schema.

Does this work in the Pages Router?
Server Actions are an App Router feature. In the Pages Router, post the form to an API route and validate there.

We build business websites and web apps in Next.js at Dzimark, and forms like this one are part of most projects. If you'd rather have a team handle the build, here is the Dzimark Next.js development team.