What we'll build
<input type="email"> and a Zod email() check stop obvious mistakes, but not jane@gmial.com, a domain that doesn't exist, or a throwaway inbox from Mailinator. We'll add a server-side check with the validateemail.io API:
- A server-only helper calls the API, so your key never reaches the browser.
- A Server Action runs it when the form is submitted.
- The form shows the error and a one-click "Did you mean …?" fix with
useActionState.
If the API is slow or down, the sign-up goes through, so a network problem never blocks real users. Every snippet was tested with Next.js 16 and React 19, including a full next build.
1. Add your API key
Get a free API key (250 lookups a day, no card) and add it to .env.local, and to your host's environment variables (on Vercel: Settings → Environment Variables):
VALIDATEEMAIL_KEY=ev_your_api_keyDon't prefix it with NEXT_PUBLIC_: that would put it in the JavaScript sent to every visitor. Install server-only, which makes the build fail if client code ever imports the helper:
npm install server-only2. Write the server-only helper
import "server-only"; // keeps the API key out of client bundles
export type EmailCheck = { ok: true; didYouMean: string | null } | { ok: false; message: string; didYouMean: string | null };
export async function checkEmail(email: string): Promise<EmailCheck> {
try {
const res = await fetch("https://validateemail.io/v1/validate", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.VALIDATEEMAIL_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ email }),
signal: AbortSignal.timeout(5000),
cache: "no-store",
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const result = await res.json();
if (result.status === "invalid") {
return { ok: false, message: "That email address can't receive mail.", didYouMean: result.did_you_mean };
}
if (result.checks?.disposable) {
return { ok: false, message: "Please use a permanent email address.", didYouMean: null };
}
return { ok: true, didYouMean: result.did_you_mean };
} catch (err) {
// Never block a sign-up because the validator is slow or unreachable.
console.warn("Email validation unavailable:", err);
return { ok: true, didYouMean: null };
}
}The policy rejects addresses that can't receive mail and disposable inboxes, and accepts everything else. cache: "no-store" stops Next.js caching the API call between different users' sign-ups.
3. Call it from a Server Action
"use server";
import { checkEmail } from "@/lib/validate-email";
export type SignupState = { error?: string; didYouMean?: string | null; done?: boolean };
export async function signup(_prev: SignupState, formData: FormData): Promise<SignupState> {
const email = String(formData.get("email") ?? "").trim();
const check = await checkEmail(email);
if (!check.ok) return { error: check.message, didYouMean: check.didYouMean };
// await db.user.create({ data: { email } });
return { done: true, didYouMean: check.didYouMean };
}Server Actions run on the server even when the form is in a client component, so checkEmail() and the key stay server-side. If you validate the rest of the form with Zod, run checkEmail() after the Zod check passes.
4. Show the result in the form
"use client";
import { useActionState, useState } from "react";
import { signup, type SignupState } from "./actions";
export default function SignupPage() {
const [state, formAction, pending] = useActionState<SignupState, FormData>(signup, {});
const [email, setEmail] = useState("");
if (state.done) return <p>Thanks! Check your inbox.</p>;
return (
<form action={formAction}>
<input name="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
{state.error && <p role="alert">{state.error}</p>}
{state.didYouMean && (
<button type="button" onClick={() => setEmail(state.didYouMean!)}>
Did you mean {state.didYouMean}?
</button>
)}
<button type="submit" disabled={pending}>
Sign up
</button>
</form>
);
}useActionState gives the form the action's return value and a pending flag. The "Did you mean …?" button fills in the suggested address so the user only has to submit again.
Test it
The action is a plain async function, so you can test it with a stubbed fetch:
// Harness: the server action against a stubbed API (node --test after tsc).
import { test } from "node:test";
import assert from "node:assert/strict";
import { signup } from "./app/signup/actions";
const api = (body: unknown, status = 200) => {
globalThis.fetch = (async () => Response.json(body, { status })) as typeof fetch;
};
const submit = (email: string) => {
const form = new FormData();
form.set("email", email);
return signup({}, form);
};
test("valid address signs up", async () => {
api({ status: "valid", did_you_mean: null, checks: { disposable: false } });
assert.deepEqual(await submit("jane@gmail.com"), { done: true, didYouMean: null });
});
test("invalid address is rejected with a suggestion", async () => {
api({ status: "invalid", did_you_mean: "joe@gmail.com", checks: { disposable: null } });
assert.deepEqual(await submit("joe@gmail.con"), { error: "That email address can't receive mail.", didYouMean: "joe@gmail.com" });
});
test("disposable address is rejected", async () => {
api({ status: "risky", did_you_mean: null, checks: { disposable: true } });
assert.equal((await submit("t@mailinator.com")).error, "Please use a permanent email address.");
});
test("API outage doesn't block sign-up", async () => {
api({}, 500);
assert.equal((await submit("jane@gmail.com")).done, true);
});We ran this with node --conditions=react-server --import tsx --test; the react-server condition lets server-only load outside Next.js. Jest or Vitest work the same way.
Using v0, Bolt or Cursor?
Using an AI coding assistant? Paste this prompt and it will wire up the API for you:
Add email validation to the sign-up form of this Next.js App Router app, using a Server Action and a server-only helper using the validateemail.io API (reference: https://validateemail.io/llms.txt).
- Call POST https://validateemail.io/v1/validate from server-side code only, with the header "Authorization: Bearer <key>" read from the VALIDATEEMAIL_KEY environment variable, and the JSON body {"email": "<address>"}. Never call it from the browser.
- Reject the address with a clear message when "status" is "invalid" or "checks.disposable" is true.
- When "did_you_mean" is set, show "Did you mean <did_you_mean>?" and let the user accept the fix.
- Use a 5-second timeout. If the API fails, times out or returns "status": "unknown", accept the address so sign-ups never break.
- Add a test that mocks the API for a valid, an invalid and a disposable address.Frequently asked questions
How do I validate an email in Next.js?
Check the format on the client for quick feedback, then check deliverability on the server: in a Server Action or Route Handler, call an email validation API (or look up the domain's MX records) and reject addresses that can't receive mail or are disposable.
Can I call the validation API from a client component?
Not with your secret key: anything in client code, including NEXT_PUBLIC_ variables, is visible to visitors. Use a Server Action as in this guide, or a browser key that only works from your domain.
Should I use a Server Action or a Route Handler?
For a form in your own app, a Server Action is simpler: no fetch call or JSON parsing on the client. Use a Route Handler (app/api/.../route.ts) if other clients, like a mobile app, also need the check.
Does this work with the Pages Router?
Yes. Call checkEmail() from an API route in pages/api/ and fetch it from your form. The helper itself doesn't depend on the App Router.