Article
Email Validation in Next.js Forms: Zod, DNS, and Mailbox Checks
By Unlimited Verifier Team ·

Summary
To validate email in a Next.js form, run one Zod schema in the browser for instant feedback and again in a Server Action, then check MX records with Node's dns module and call a server-side verification API. Only server-side checks should decide whether a signup is accepted, since client checks can be bypassed.To validate email in a Next.js form, run one Zod schema in the browser for instant feedback, repeat it inside a Server Action, check the domain's MX records with Node's dns module, and call a verification API for mailbox-level results. Only server-side checks should decide whether a signup is accepted, because anyone can bypass the browser.
Each layer answers a different question. A browser check catches jane@gmail but not jane@gmai1.com, which can have valid DNS records. Only a mailbox-level check can tell you whether anyone receives mail there. For the strategy behind these checks, read our real-time email validation guide. This page covers the Next.js implementation.
Quick answer
- Validate twice. Use one Zod schema in the browser for instant feedback and again in the Server Action, because client checks can be bypassed.
- Check DNS on the server. Look up MX records with Node's
dnsmodule. It needs the Node runtime, not the Edge runtime. - Verify the mailbox through an API, server-side only. Keep the key out of
NEXT_PUBLIC_variables and put a hard timeout on the call. Three seconds is a reasonable starting budget, which you should tune to your own measured latency. - Never let a slow check block signup. If the verifier times out, accept the signup as unverified and confirm ownership with an email.
What does email validation in a Next.js form need to check?
A complete check has five layers, and each one catches failures the others miss. Most forms stop at the first, which is why bad addresses still reach the database.
| Layer | What it catches | What it misses | Where it runs |
|---|---|---|---|
Browser type="email" |
Missing @, stray spaces |
user@localhost passes; no domain check |
Browser |
| Zod schema | Malformed input, length limits, trimming | Domains and mailboxes that don't exist | Server (and browser for feedback) |
| MX / DNS lookup | Domains that cannot receive mail | A real domain with a missing mailbox | Node server |
| Mailbox check via API | Nonexistent mailboxes; disposable, role and catch-all flags | Intent and consent | Server, calling a verifier |
| Confirmation email | Ownership and intent | Nothing before the send | Your email system |
Order the checks cheapest first, so expensive ones only see addresses that passed the cheap ones:
- Trim and length-check on the server. This needs no network call.
- Validate syntax with Zod.
- Look up MX records. This is a single DNS query.
- Check the mailbox through the API, with a timeout and rate limiting.
- Send a confirmation email. This is the only step that proves the person controls the inbox.
Don't use a regular expression for syntax. The grammar in RFC 5322 allows quoted strings and comments, so a fully compliant regex is unreadable, and simpler ones reject legal addresses. Enforce the practical limits instead. RFC 5321 caps the local part (before the @) at 64 characters and the full forward path at 254.
Bottom line: Syntax checks are cheap and necessary, but they only prove an address is well formed. Only a mailbox-level check tests whether mail can be delivered.
Why isn't client-side validation enough?
Client-side validation exists for user experience, not protection. Anyone can send a request to your endpoint with curl and skip the browser entirely.
The HTML type="email" check is also loose by design. The WHATWG HTML standard defines a simplified address format that accepts values such as user@localhost. Treat the browser's result as a hint.
Server Actions need particular care. Next.js's security guidance treats them like public HTTP endpoints, so each action should validate its own inputs, even if the form already did. The browser decides what the user sees. The server decides what gets stored.
Bottom line: Validate in the browser for speed, then validate again on the server, where the decision is made.
How do you validate email format on the server in Next.js?
Define one Zod schema in a shared file, then import it in both the form and the Server Action. The schema below trims input, enforces the 254-character limit, and checks the format.
// lib/email-schema.ts
import { z } from "zod";
export const emailSchema = z
.string()
.trim()
.max(254, "Email is too long")
.email("Enter a valid email address");
Three details matter here:
- Keep the address as typed. The RFC allows case-sensitive local parts, although most mailbox providers in practice treat them case-insensitively. Store the value as entered, and compare a normalised copy for duplicate checks.
- Share the schema with the form. Pairing it with react-hook-form and zodResolver keeps browser and server rules from drifting apart. If you're writing plain TypeScript, the TypeScript validation guide covers the typing side.
- Check the Zod version. Zod 4 prefers the top-level
z.email(). The chained.email()still works in current releases, but check your version's docs before you copy the pattern.
| Option | Strength | Limitation |
|---|---|---|
| Zod | Types inferred from one schema; shared between client and server | Syntax and shape only |
| Yup | Mature schema API that works with react-hook-form | Same scope; you keep server and client rules in sync |
validator.js isEmail() |
Simple standalone string check | No schema, normalisation or error mapping |
Bottom line: A shared Zod schema gives consistent syntax rules, but it is only the first gate. The rest run on the server.
Should your Next.js app check DNS and MX records?
Yes. A DNS lookup is cheap and rejects domains that cannot receive mail at all. Node's dns module provides resolveMx for this.
// lib/dns.ts
import { resolveMx } from "node:dns/promises";
export async function domainAcceptsMail(domain: string): Promise<boolean> {
try {
const records = await resolveMx(domain);
return records.length > 0;
} catch {
return false; // ENOTFOUND, ENODATA, or a resolver error
}
}
Missing MX records need care. RFC 5321 describes falling back to the domain's A record when no MX record exists, so a domain with no MX but an A record can still receive mail. Treat "no MX and no A record" as invalid, and treat "no MX but an A record" as a warning rather than a rejection.
Two practical points:
- Wrap the lookup in a timeout. DNS can hang, and a hung lookup should not hold a signup open.
- Cache results. MX records change rarely, so caching domain results for a day, as a recommendation rather than an industry rule, avoids repeated lookups for popular providers.
A live MX record shows only that the domain runs a mail server. It says nothing about whether a specific mailbox exists.
Bottom line: MX checks are fast and worth doing, but they test the domain, not the person.
How do you check the mailbox without blocking the signup?
Call a verification API from your server rather than running your own SMTP probe. An SMTP handshake from an app looks simple, but many cloud hosts restrict outbound port 25 by default, and mail providers throttle or block repeated probes. Our SMTP check guide explains those trade-offs.
When you compare best email verification tools for this job, check three things: how results are categorised, whether the same API serves single and bulk checks, and whether the engine's checks are documented. Unlimited Verifier sorts every address into Valid, Risky or Invalid. Its email verification API accepts single-email checks and bulk batches of up to 10,000 emails per request. It also publishes an open-source verification engine on GitHub, which you can read before relying on it for an audit. Confirm how that engine relates to the hosted service. If latency is a deciding factor, the fastest email validation APIs compared guide is the place to start.
Wrap the call so it can never block signup:
// lib/verify-mailbox.ts
import "server-only";
export type Verdict = "valid" | "risky" | "invalid" | "unknown";
export async function verifyMailbox(email: string): Promise<Verdict> {
try {
// Pseudo-code: take the endpoint, auth header and response fields
// from the API documentation. The structure is what matters.
const result = await callVerifierApi(email, {
apiKey: process.env.VERIFIER_API_KEY!,
signal: AbortSignal.timeout(3000),
});
return result.category; // Valid | Risky | Invalid, mapped to lowercase
} catch {
return "unknown"; // timeout or outage: never block signup
}
}
The server-only package makes the build fail if this module is imported into client code, which protects your key. The unknown verdict is an application status, not one of the verifier's three categories. Set the 3-second timeout from your own data. Measure p95 latency for a week, then set the timeout comfortably above it.
Bottom line: Call the verifier from the server, put a hard timeout on it, and let an outage degrade to "unverified" instead of "rejected."
What should the form do with each verification result?
Map each result to a specific action. Blocking every "risky" address is the most common mistake, and it turns away real customers, because the Risky label covers very different situations.
| Result | Form action | Why |
|---|---|---|
| Valid | Accept; send confirmation | The check found a mailbox that accepts mail |
| Risky, catch-all flagged | Accept; send confirmation; tag as unconfirmed | Catch-all domains accept any address, so the mailbox can't be confirmed |
| Disposable flag | Block with "please use a permanent address" | Throwaway addresses rarely convert and consume quota |
Role flag (info@, sales@) |
Accept for B2B; tag as role | Shared inboxes are often legitimate |
| Invalid | Block with a neutral message | Specific errors let anyone probe which addresses exist |
| Unknown (timeout) | Accept as unverified; re-check in background | Don't penalise users for your outage |
The neutral message matters. If the form says "this mailbox does not exist," anyone can use it to test whether an address is registered. Use wording like "We couldn't deliver to that address. Please check it."
Bottom line: Give each result its own action. Blanket blocking costs signups and gives no security benefit that a confirmation email doesn't already provide.
Where should the verification call run in Next.js?
Run the call on the server, in one of four places.
| Pattern | Best for | Watch out for |
|---|---|---|
| Server Action called by the form | Standard signup forms; simplest path | Verifier latency lands on the user, so use a timeout |
Route Handler (app/api/.../route.ts) |
Forms outside Next.js, mobile apps, third-party posts | You must add authentication and rate limiting yourself |
| Background job after submit | Imports, sync jobs, very high volume | You can't reject on the spot; needs a confirmation flow |
| Client component calling the API | Nothing | Exposes your API key to every visitor |
Middleware is a poor fit. It runs before matched requests, so it's the wrong place for slow network calls.
Bottom line: Use a Server Action for most signup forms, a Route Handler when the form lives elsewhere, and a background job for bulk work.
How do you handle typos, disposable and role addresses?
Suggest corrections; never apply them silently. Keep a short map of common misspellings, such as gmial.com → gmail.com or hotnail.com → hotmail.com, and show a "Did you mean…?" prompt. Silent rewrites send confirmations to addresses the user never typed, which is hard to debug.
Disposable and role addresses should be handled by the verifier's flags plus your own policy. Disposable domain lists change often, so a static list you maintain by hand goes stale quickly. For catch-all domains, the verifier can flag the domain but can't confirm the specific mailbox. Treat those signups as unconfirmed until the confirmation email arrives. The catch-all email verification page explains how those results are handled.
Bottom line: Correct typos with the user's consent, block throwaway domains, and treat catch-all results as unconfirmed until ownership is proven.
How much does real-time validation cost at signup volume?
Cost depends on how many submissions reach the API. Cheap local checks reject bad input before any API call, so staging the checks reduces billable calls. The numbers below are illustrative.
Scenario: A SaaS company receives 12,000 signup attempts a month. The syntax check rejects 1,800 entries, and the MX check rejects 300 more. That leaves 9,900 addresses for the API.
- API emails used: 9,900 of the 100,000 included on Pro, or 9.9% of quota.
- Plan cost: $29 a month, or $25 a month on annual billing.
- Cost per 1,000 signup attempts: $29 ÷ 12 × 1,000 ... more precisely, $29 ÷ 12,000 × 1,000 = $2.42 ($2.08 on annual billing).
- Cost per 1,000 API emails at full quota: $29 ÷ 100,000 × 1,000 = $0.29.
Bots change this quickly. Suppose a bot spike of 40,000 fake attempts lands in one day, and most pass syntax checks. Usage would jump to 49,900 emails, nearly half the monthly quota. Two defences stop this before the verifier:
- A honeypot field. Add a hidden input that humans never fill in. If it has a value, reject the request silently.
- Rate limiting by IP and by domain. An in-memory limiter fails on serverless hosts because each instance keeps its own counter. Use a shared store such as Redis, or your platform's rate-limiting service.
For an existing list, the arithmetic changes. Pro lists are capped at 25,000 emails each, so a 60,000-contact database needs three uploads: 25,000 + 25,000 + 10,000. Deep verifications are capped at 25,000 a month, so spend them on the riskiest addresses, such as old imports, not the whole list. Teams that run both live checks and backlog cleaning usually need to compare email verification pricing on quotas, not just headline prices.
Bottom line: Real-time validation costs cents per thousand submissions when you filter early and rate-limit bots.
How do you add mailbox validation to a Next.js signup form?
Follow these steps in order. The form and Server Action are the only new files you write in the app router.
- Create an account. Sign up for an account. The Free plan has no API access, so choose Pro for form integration: $29 a month, or $25 a month billed annually.
- Create an API key. Generate one from the API keys page.
- Store the key server-side. Add
VERIFIER_API_KEY=...to.env.local. Don't prefix it withNEXT_PUBLIC_, because those variables are bundled into client JavaScript. - Install the packages. Run
npm install zod server-only. - Create the schema in
lib/email-schema.ts, as shown above. - Create the DNS helper in
lib/dns.ts, as shown above. - Create the verifier wrapper in
lib/verify-mailbox.ts, with a timeout and anunknownfallback. - Write the Server Action. It parses the input, checks MX records, calls the verifier, and returns a generic result.
// app/signup/actions.ts
"use server";
import { emailSchema } from "@/lib/email-schema";
import { domainAcceptsMail } from "@/lib/dns";
import { verifyMailbox } from "@/lib/verify-mailbox";
const NEUTRAL = "We couldn't deliver to that address. Please check it.";
export async function signUp(
_prev: { error?: string; ok?: boolean },
formData: FormData
): Promise<{ error?: string; ok?: boolean }> {
const parsed = emailSchema.safeParse(formData.get("email"));
if (!parsed.success) return { error: parsed.error.issues[0].message };
const email = parsed.data;
const domain = email.split("@")[1];
if (!(await domainAcceptsMail(domain))) return { error: NEUTRAL };
const verdict = await verifyMailbox(email);
if (verdict === "invalid") return { error: NEUTRAL };
// Store the email and the verdict, then send the confirmation email.
return { ok: true };
}
- Wire the form. In React 19,
useActionStatereturns[state, formAction, isPending]. Older Next.js versions useuseFormStatefromreact-dom.
// app/signup/page.tsx
"use client";
import { useActionState } from "react";
import { signUp } from "./actions";
export default function SignupForm() {
const [state, action, pending] = useActionState(signUp, {});
return (
<form action={action}>
<input name="email" type="email" required />
<button disabled={pending}>Sign up</button>
{state.error && <p>{state.error}</p>}
</form>
);
}
- Test five inputs before shipping: a valid address, a typo domain, a disposable domain, a catch-all domain, and a forced timeout (set the timeout to 1 ms for one test run). Each should produce the action in the table above.
- Keep your own record. Store the category and timestamp. Results on the platform are kept for 24 hours on Free and 30 days on Pro, so your database should hold the outcome you need.
- Spot-check addresses. Use the free single-email checker for individual addresses during development.
Bottom line: Twelve steps give you a validated signup flow with a clear fallback. The test in step 10 shows whether the fallback actually works.
How do you clean the emails you already collected?
Run a bulk clean alongside the live check. Export your contacts as CSV, then upload and verify the list. Uploads accept CSV or Excel files up to 10MB and detect the email column automatically. Export the results as CSV, Excel or JSON, and re-import only the Valid contacts. The platform has no native ESP, CRM or Zapier integrations, so the export, verify, re-import loop is how existing data moves. You can also call the API from a script.
Plan limits shape the workflow. Free allows 25 lists a month of up to 150 emails each, which suits spot tests. Pro allows lists of up to 25,000 emails each. If you're running large batches through the API, the webhook vs polling comparison explains how to collect results without hammering the endpoint. For scheduling, the list maintenance practices guide covers the cadence. Sales teams with purchased data face the same problem, and email verification for sales prospecting covers that case.
Fix the source too. A clean list decays if the form keeps adding unverified contacts, so review your acquisition channels with the email list growth strategies guide.
Bottom line: Clean the backlog with bulk verification, keep the live check on the form, and fix the sources that keep feeding bad addresses in.
What mistakes break email validation in Next.js?
- Trusting the browser check. Client validation is for user experience. Always repeat it on the server.
- Shipping the API key in a
NEXT_PUBLIC_variable. Anyone can read it from the bundle. - Blocking every Risky result. Catch-all and role addresses are often real customers.
- Leaving the verifier call without a timeout. One slow response can stall signups for everyone.
- Revealing mailbox existence. Specific error messages let people probe your user base.
- Running DNS checks on the Edge runtime.
node:dnsisn't available there. - Treating MX records as proof of a mailbox. They show only that the domain accepts mail.
- Auto-correcting emails silently. Confirmations go to addresses the user never typed.
- Skipping rate limiting or a honeypot. Bot spikes consume quota and budget.
- Treating verification as consent. A valid mailbox isn't an opt-in. Keep a confirmation step, as described in email verification compliance and hygiene.
- Logging raw email addresses. Log categories and outcomes, and keep personal data to what you need.
Bottom line: Most failures come from trusting one layer too much or letting one slow dependency take down the whole form.
How we compared (and limitations)
This guide is based on public documentation: the Next.js and Zod documentation, Node's dns module, the RFCs cited above, and the WHATWG HTML standard. We haven't benchmarked any verifier's latency or accuracy. The code examples are sketches to adapt, not drop-in production code, and the verifier call is pseudo-code until you copy the endpoint and response fields from the API documentation.
Unlimited Verifier's 99.5% accuracy figure for deep verification is the company's own stated number, not an independent benchmark. The 3-second timeout, the cost arithmetic, and the 40,000-attempt bot scenario are recommendations or illustrative examples. Replace them with your own latency, traffic and category data before making budget decisions. Pricing and plan limits can change, so check current plans before you commit.
Bottom line: Use the layered approach and the decision tables as a framework, then set the final numbers from your own measurements.
Order of checks, cheapest first
- Trim and length-check on the server (no network).
- Validate syntax with Zod.
- Look up MX records with Node's dns module (one DNS query).
- Check the mailbox via API, with a timeout and rate limiting.
- Send a confirmation email to prove ownership.
| Result | Action |
|---|---|
| Syntax or length fails | Reject with inline error |
| No MX records | Reject, domain cannot receive mail |
| Mailbox API says invalid | Reject or flag for review |
| API times out or is uncertain | Accept as unverified, require confirmation |
Frequently asked questions
Can I use regex to validate email in Next.js?
You can, but avoid a full RFC 5322 regex. The grammar allows quoted strings and comments, so compliant patterns are unreadable and simpler ones reject legal addresses. Use Zod for syntax and enforce practical length limits: 64 characters for the local part and 254 for the full address.
Does dns.resolveMx work in Next.js Edge runtime?
No. Node's dns module requires the Node.js runtime. Set export const runtime = 'nodejs' on the route or Server Action that performs the MX lookup, and keep it off the Edge runtime.
Where should I store the email verification API key?
Store it in a server-only environment variable without the NEXT_PUBLIC_ prefix. Variables with that prefix are inlined into the client bundle, which exposes the key to anyone who loads the page.
What timeout should I use for a mailbox verification call?
Three seconds is a reasonable starting budget. Measure your verifier's real latency under load and tune the timeout from that data. If the call times out, accept the signup as unverified rather than blocking the user.
Should I block signups when the email check fails?
Block only on clear syntax or hard DNS failures. For slow or uncertain mailbox results, accept the signup as unverified and require confirmation by email. This keeps signups working when the verifier is slow or down.
What is a catch-all domain and why does it matter?
A catch-all domain accepts mail for any address, so a mailbox check cannot confirm that a specific mailbox exists. Treat catch-all results as lower confidence and rely on a confirmation email to prove ownership.
Are disposable email addresses worth blocking?
It depends on your risk. Blocking disposable domains reduces throwaway signups and abuse, but it can also reject legitimate users. Many teams flag them for review or apply stricter confirmation instead of rejecting outright.
Why is a confirmation email the only real proof of ownership?
Every other check tests the address, not the person. Only a confirmation link clicked by the recipient shows they control the inbox and intend to sign up.
Should I run validation in middleware?
Generally no. Keep validation in the Server Action or route handler closest to the write, so every path that creates an account goes through the same checks.
Cut Bounces and Protect Your Sender Reputation With Unlimited Email Verification
Every invalid address you send to hurts your sender reputation and your inbox placement. Verifying your list before each send means fewer bounces, healthier deliverability, and a predictable cost. With Unlimited Verifier, standard verification is unlimited on every plan, with no per-email fees.
Unlimited Verifier checks syntax, domain, MX records and the SMTP mailbox. It also detects catch-all domains and flags disposable and role-based addresses. Export a CSV from your email platform or CRM, upload and verify the list, then re-import the clean results. You can also automate checks with the email verification API.
| Free | Pro | |
|---|---|---|
| Price | $0 | $29/month ($25/month billed annually) |
| Lists | 25 a month, up to 150 emails each | Unlimited, up to 25,000 emails each |
| Deep verifications | 750 a month | 25,000 a month |
| API access | No | Yes (100,000 emails a month) |
| Result retention | 24 hours | 30 days |
Why teams choose Unlimited Verifier
- Unlimited standard verification on all plans, including Free, with no per-email fees.
- Catch-all detection so you know which domains accept every address.
- Clear Valid / Risky / Invalid results, exportable as CSV, Excel or JSON.
- An open-source verification engine you can inspect on GitHub.
Unlimited Verifier states 99.5% accuracy for deep verification.
Create a free account and verify your next list before you hit send.
Want to test a single address first? Try the free email checker.