For a local service business, the contact form is often the most valuable component on the whole website. It is where a homeowner asks for an HVAC quote, where someone with a legal problem asks for a consultation, and where a restaurant gets a catering request. If the form breaks, or if it fills the inbox with junk, real leads get lost.

This post walks through how we build lead forms in the Next.js App Router so they are reliable, accessible and hard for bots to abuse, without forcing every visitor through an annoying captcha. The examples use Server Actions, Zod for validation and a few simple layers of spam protection.

The goals

Before writing code, it helps to be clear about what "good" means for a lead form:

  1. It always works. The form submits even if JavaScript fails to load, and the user always gets a clear success or error message.
  2. It validates on the server. Client side checks are a convenience. The server is the only place you can trust.
  3. It keeps bots out quietly. Real people should never notice the spam protection.
  4. It is accessible. Labels, error messages and focus handling work with a keyboard and a screen reader.
  5. It delivers the lead somewhere useful. An email, a CRM, a spreadsheet, or all three, with a fallback if one fails.

Step 1: A schema shared by client and server

Start with a Zod schema. Keeping it in its own file lets you reuse it on both sides.

// lib/lead-schema.ts import { z } from "zod"; export const leadSchema = z.object({ name: z.string().trim().min(2, "Please enter your name").max(80), email: z.string().trim().email("Please enter a valid email"), phone: z .string() .trim() .max(25) .optional() .or(z.literal("")), message: z.string().trim().min(10, "Please add a few more details").max(2000), }); export type Lead = z.infer<typeof leadSchema>; 

Keep the rules realistic. A phone field that rejects valid international formats will cost you more leads than it saves you in clean data. Light validation plus a human follow up is usually the right tradeoff.

Step 2: The Server Action

A Server Action receives the FormData directly, so the form works as a normal HTML post even before hydration.

// app/contact/actions.ts "use server"; import { headers } from "next/headers"; import { leadSchema } from "@/lib/lead-schema"; import { isRateLimited } from "@/lib/rate-limit"; import { deliverLead } from "@/lib/deliver-lead"; export type FormState = { status: "idle" | "success" | "error"; message?: string; fieldErrors?: Record<string, string[]>; }; const MIN_FILL_MS = 3000; export async function submitLead( _prev: FormState, formData: FormData ): Promise<FormState> { // Layer 1: honeypot field that humans never see if (formData.get("company_website")) { return { status: "success", message: "Thanks, we will be in touch." }; } // Layer 2: time trap, bots tend to submit instantly const startedAt = Number(formData.get("started_at")); if (!startedAt || Date.now() - startedAt < MIN_FILL_MS) { return { status: "success", message: "Thanks, we will be in touch." }; } // Layer 3: simple rate limit per IP const h = await headers(); const ip = h.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown"; if (await isRateLimited(ip)) { return { status: "error", message: "Too many requests. Please try again in a few minutes.", }; } const parsed = leadSchema.safeParse(Object.fromEntries(formData)); if (!parsed.success) { return { status: "error", message: "Please fix the highlighted fields.", fieldErrors: parsed.error.flatten().fieldErrors, }; } try { await deliverLead(parsed.data); return { status: "success", message: "Thanks, we will be in touch soon." }; } catch { return { status: "error", message: "Something went wrong. Please call us or try again.", }; } } 

Notice that the honeypot and time trap return a fake success. If you return an error, a bot author can tune their script until it passes. A silent success gives them nothing to learn from.

Step 3: The form component

On the client, useActionState (React 19, used by recent Next.js versions) gives you the returned state and a pending flag.

// app/contact/lead-form.tsx "use client"; import { useActionState, useEffect, useRef, useState } from "react"; import { submitLead, type FormState } from "./actions"; const initial: FormState = { status: "idle" }; export function LeadForm() { const [state, action, pending] = useActionState(submitLead, initial); const [startedAt, setStartedAt] = useState(""); const statusRef = useRef<HTMLParagraphElement>(null); useEffect(() => setStartedAt(String(Date.now())), []); useEffect(() => { if (state.status !== "idle") statusRef.current?.focus(); }, [state]); const err = (field: string) => state.fieldErrors?.[field]?.[0]; return ( <form action={action} noValidate> <div aria-hidden="true" style={{ position: "absolute", left: "-9999px" }}> <label htmlFor="company_website">Leave this empty</label> <input id="company_website" name="company_website" tabIndex={-1} autoComplete="off" /> </div> <input type="hidden" name="started_at" value={startedAt} /> <label htmlFor="name">Name</label> <input id="name" name="name" autoComplete="name" required aria-invalid={!!err("name")} aria-describedby="name-error" /> <p id="name-error">{err("name")}</p> <label htmlFor="email">Email</label> <input id="email" name="email" type="email" autoComplete="email" required aria-invalid={!!err("email")} aria-describedby="email-error" /> <p id="email-error">{err("email")}</p> <label htmlFor="phone">Phone (optional)</label> <input id="phone" name="phone" type="tel" autoComplete="tel" /> <label htmlFor="message">How can we help?</label> <textarea id="message" name="message" rows={5} required aria-invalid={!!err("message")} aria-describedby="message-error" /> <p id="message-error">{err("message")}</p> <button type="submit" disabled={pending}> {pending ? "Sending..." : "Send request"} </button> <p ref={statusRef} tabIndex={-1} role="status" aria-live="polite"> {state.message} </p> </form> ); } 

A few details that matter more than they look:

  • autoComplete attributes let mobile browsers fill the name, email and phone in one tap. On a phone, that alone can make the form noticeably easier to finish.
  • type="tel" and type="email" bring up the right keyboard on mobile.
  • The honeypot is hidden with positioning, not display: none. Some bots skip fields that are not displayed. Keeping it out of the tab order and marked aria-hidden means keyboard and screen reader users never land on it.
  • The status message receives focus after submit, so screen reader users hear the result immediately.
  • The time trap value is set in an effect. If JavaScript never runs, started_at stays empty and the submission is treated as a bot. If you need the form to work fully without JavaScript, render a server timestamp into the page instead, ideally signed, so it cannot be faked easily.

Step 4: Rate limiting

You do not need a heavy service for a small site. A fixed window counter in Redis or a key value store is plenty. Here is a version using Upstash Redis, which works well on serverless hosts:

// lib/rate-limit.ts import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); const WINDOW_SECONDS = 600; const MAX_REQUESTS = 5; export async function isRateLimited(ip: string) { const key = `lead-rl:${ip}`; const count = await redis.incr(key); if (count === 1) await redis.expire(key, WINDOW_SECONDS); return count > MAX_REQUESTS; } 

Five submissions per IP every ten minutes will never bother a real customer, but it stops a script from flooding the inbox. Remember that offices and mobile carriers can share IP addresses, so do not set the limit too low.

Step 5: Deliver the lead with a fallback

The worst failure is a form that shows "Thanks" while the lead goes nowhere. Treat delivery as something that can fail, and make it observable.

// lib/deliver-lead.ts import type { Lead } from "./lead-schema"; export async function deliverLead(lead: Lead) { const results = await Promise.allSettled([ sendEmail(lead), // your email provider saveToCrm(lead), // CRM, database or sheet ]); const delivered = results.some((r) => r.status === "fulfilled"); if (!delivered) { console.error("Lead delivery failed", { email: lead.email }); throw new Error("Lead delivery failed"); } } 

As long as one channel succeeds, the lead is safe. Log every failure so you notice when an API key expires or a provider changes something. A weekly test submission is a cheap habit that catches silent breakage.

When to add a captcha

The three layers above stop most automated spam we see on small business sites. If a form is still being targeted, add a privacy friendly, mostly invisible challenge such as Cloudflare Turnstile and verify its token inside the Server Action before anything else runs. Add it only when you actually need it, because every extra step costs some real submissions.

Track the conversion

A lead form that works is only half the job. If the business runs paid ads, fire a conversion event after a real success, not on button click. With Server Actions, the natural place is an effect that runs when state.status becomes "success". That keeps ad platforms optimizing for actual leads instead of failed attempts or bot traffic.

A quick checklist

Before shipping a lead form, we check:

  • Submits correctly with JavaScript disabled, or degrades in a way you have chosen on purpose
  • Server side validation with clear, friendly messages
  • Honeypot, time trap and rate limit in place
  • Labels, aria-invalid and a focused status message
  • Correct input types and autoComplete values for mobile
  • At least two delivery channels, with failures logged
  • Conversion tracking fires only on real success
  • A real test submission arrives where the business expects it

Small details like these are a big part of how we approach Next.js development for business websites. A form is not just UI, it is the point where a visitor becomes a customer.

If you want to know whether your own site's forms and pages are holding up, you can request a free website audit. And if you are trying to explain to a client why this matters, our article on what missed calls and lost inquiries cost a local business is a useful starting point.

Thanks for reading.

CodeHunterz Team