What we'll build
A regular expression or z.email() can tell you an address looks right. Neither can tell you whether the domain exists, whether it accepts mail, or whether it's a throwaway inbox. In this guide we'll build a typed validateEmail() function that checks all of those and returns one of four statuses:
| Status | Meaning | Typical action |
|---|---|---|
valid | Well formed, and the domain accepts mail | Accept |
invalid | Bad syntax, no such domain, or no mail server | Reject and ask the user to fix it |
risky | Disposable, a likely typo, a role account, or no MX records | Your call: block, warn, or flag |
unknown | DNS failed temporarily | Accept and check again later |
You'll need Node.js 22 or later and TypeScript 5.5 or later. DNS lookups use Node's built-in node:dns module, so the validator itself needs no packages. The sign-up endpoint in step 7 uses Express and Zod:
npm install express zod
npm install -D typescript @types/node @types/expressThe code uses ES modules ("type": "module" in package.json, "module": "nodenext" in tsconfig.json), which is why imports end in .js. Every snippet was tested with Node.js 22, TypeScript 7, Express 5 and Zod 4. Want to see the end result first? The free email checker runs the same checks. Using plain JavaScript? See the Node.js guide.
1. Check the syntax
Start with the check that needs no network. Instead of one huge regular expression, split the address at the last @ and check each part separately. A discriminated union for the result means TypeScript only lets you read domain after you've checked ok:
// RFC 5322 "atext": the characters allowed in each dot-separated part of the local part.
const ATOM = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+$/i;
// A DNS label: letters, digits and hyphens, not starting or ending with a hyphen.
const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
export type SyntaxResult =
| { ok: true; local: string; domain: string; normalized: string }
| { ok: false; reason: string };
/** Lower-cases a domain and converts international names to punycode, or returns null. */
function toAsciiDomain(domain: string): string | null {
try {
// The URL parser applies the same IDNA rules browsers use ("münchen.de" → "xn--mnchen-3ya.de").
return new URL(`http://${domain.trim().replace(/\.$/, "")}`).hostname || null;
} catch {
return null;
}
}
export function checkSyntax(input: string): SyntaxResult {
const email = input.trim();
if (email.length > 254) return { ok: false, reason: "too_long" };
const at = email.lastIndexOf("@");
if (at <= 0 || at === email.length - 1) return { ok: false, reason: "missing_at_or_part" };
const local = email.slice(0, at);
if (new TextEncoder().encode(local).length > 64) return { ok: false, reason: "local_part_too_long" };
// Splitting on "." also rejects leading, trailing and doubled dots (they create empty atoms).
if (!local.split(".").every((atom) => ATOM.test(atom))) return { ok: false, reason: "invalid_local_part" };
const rawDomain = email.slice(at + 1);
const domain = /[\s/\\?#:@%[\]]/.test(rawDomain) ? null : toAsciiDomain(rawDomain);
const labels = domain?.split(".") ?? [];
if (labels.length < 2 || /^\d+$/.test(labels.at(-1)!) || !labels.every((l) => LABEL.test(l))) {
return { ok: false, reason: "invalid_domain" };
}
return { ok: true, local, domain: domain!, normalized: `${local.toLowerCase()}@${domain}` };
}Notes on the code:
- The
URLparser converts international domains to punycode (münchen.debecomesxn--mnchen-3ya.de), which is the form DNS needs. It's built into Node, so there's nopunycodepackage to install. The character check before it stopsURLfrom accepting things like ports or paths as part of a "domain". - Splitting the local part on dots means
.jane,jane.andja..neall produce an empty part that fails, with no extra rules. - The local part limit is 64 bytes (RFC 5321), so the length is measured with
TextEncoder, not.length, which counts UTF-16 units.
Only lower-case the local part when comparing addresses, to stop duplicate sign-ups. Store what the user typed, because a few mail servers still treat Jane and jane as different mailboxes.
2. Check the domain's MX records
A well-formed address is no use if its domain doesn't exist or doesn't accept mail. The domain's MX (mail exchanger) records name the servers that receive its mail. Node's Resolver reports a missing domain (ENOTFOUND) separately from a domain with no MX records (ENODATA) and from DNS trouble, so each case gets the right status:
import { Resolver } from "node:dns/promises";
// A dedicated resolver with a short timeout, so a slow DNS server can't stall a sign-up.
export const resolver = new Resolver({ timeout: 3000, tries: 2 });
export type DomainCheck =
| { status: "ok"; mx: string[] }
| { status: "risky"; reason: "no_mx_records" }
| { status: "invalid"; reason: "domain_not_found" | "domain_rejects_mail" | "no_mail_server" }
| { status: "unknown"; reason: "dns_error" };
export async function checkDomain(domain: string): Promise<DomainCheck> {
try {
const mx = await resolver.resolveMx(domain);
// RFC 7505 "null MX": a single record pointing at "." means "this domain accepts no mail".
if (mx.length === 1 && (mx[0]!.exchange === "" || mx[0]!.exchange === ".")) {
return { status: "invalid", reason: "domain_rejects_mail" };
}
if (mx.length > 0) {
return { status: "ok", mx: mx.sort((a, b) => a.priority - b.priority).map((r) => r.exchange) };
}
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code === "ENOTFOUND") return { status: "invalid", reason: "domain_not_found" };
// ENODATA = the domain exists but has no MX records; handled below.
// Anything else (ESERVFAIL, ETIMEOUT, ECONNREFUSED…) is temporary: don't blame the user.
if (code !== "ENODATA") return { status: "unknown", reason: "dns_error" };
}
// No MX records: mail servers fall back to the domain's own A/AAAA record ("implicit MX").
const hasAddress = await Promise.any([resolver.resolve4(domain), resolver.resolve6(domain)]).then(
() => true,
() => false,
);
return hasAddress ? { status: "risky", reason: "no_mx_records" } : { status: "invalid", reason: "no_mail_server" };
}| Result | Meaning | Status |
|---|---|---|
| MX records returned | The domain accepts mail | ok |
| One MX record with an empty name | "Null MX" (RFC 7505): the domain accepts no mail | invalid |
Error with code ENOTFOUND | The domain doesn't exist | invalid |
Error with code ENODATA | The domain exists but has no MX records, so check A/AAAA | risky or invalid |
| Any other error code | SERVFAIL or a timeout: DNS trouble, not the user's fault | unknown |
Keep the resolver's timeout short, so a slow DNS server can't hold up a sign-up, and never treat a timeout as "invalid", or you'll turn away real users whenever DNS has a bad moment. The DomainCheck type lists every reason, so the compiler tells you if a caller forgets one.
3. Cache DNS lookups
Most of your users share a handful of domains like gmail.com and outlook.com. A Node process lives across many requests, so an in-memory map saves most lookups:
import { checkDomain, type DomainCheck } from "./dns-check.js";
const TTL_MS = 60 * 60 * 1000; // 1 hour
const cache = new Map<string, { promise: Promise<DomainCheck>; expires: number }>();
// Caches the promise, not the result, so concurrent sign-ups on the same domain share one lookup.
export function checkDomainCached(domain: string): Promise<DomainCheck> {
const hit = cache.get(domain);
if (hit && hit.expires > Date.now()) return hit.promise;
const promise = checkDomain(domain);
cache.set(domain, { promise, expires: Date.now() + TTL_MS });
// Don't remember temporary failures.
promise.then((result) => {
if (result.status === "unknown") cache.delete(domain);
});
return promise;
}Caching the promise rather than the result means ten sign-ups arriving at once for the same new domain share one DNS query. If you run several processes or serverless functions, each keeps its own cache; that's fine for this. Don't cache failed lookups.
4. Detect disposable domains
Temporary inboxes from services like Mailinator pass every check so far: the syntax is fine and the domains have working mail servers. The only way to catch them is a list. Download the community-maintained disposable-email-domains list next to your code:
curl -fsSo disposable_email_blocklist.conf https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.confimport { readFileSync } from "node:fs";
// One domain per line. A Set makes each lookup instant.
const blocklist = new Set(
readFileSync(new URL("../disposable_email_blocklist.conf", import.meta.url), "utf8")
.split("\n")
.map((line) => line.trim())
.filter(Boolean),
);
/** True for a listed domain or any subdomain of one ("x.mailinator.com" matches "mailinator.com"). */
export function isDisposable(domain: string): boolean {
const labels = domain.split(".");
return labels.slice(0, -1).some((_, i) => blocklist.has(labels.slice(i).join(".")));
}Checking parent domains matters because many disposable services hand out addresses on random subdomains. New disposable domains appear every week, so download the list again from a daily job and restart, or reload the set.
The list also contains some typo domains, such as gmial.com and hotmial.com. Someone registered them to collect mail meant for Gmail and Hotmail users, which is why step 6 still returns a didYouMean suggestion for a disposable address. Read more about how disposable email detection works.
5. Flag role accounts and suggest typo fixes
Flag role accounts and typos too. Role accounts like info@ and support@ reach a shared inbox rather than a person, and typos like gamil.com are one of the commonest reasons a sign-up email never arrives:
const ROLE_ACCOUNTS = new Set([
"admin", "billing", "contact", "help", "hello", "info", "marketing", "no-reply",
"noreply", "office", "postmaster", "sales", "support", "team", "webmaster",
]);
export function isRoleAccount(local: string): boolean {
// Ignore "+tag" sub-addressing: "support+billing" is still "support".
return ROLE_ACCOUNTS.has(local.toLowerCase().split("+")[0]!);
}
// Real providers people mistype. Include close neighbours (mail.com, ymail.com, gmx.com…)
// too, or they'd be "corrected" to the provider one letter away.
const POPULAR_DOMAINS = [
"gmail.com", "googlemail.com", "yahoo.com", "ymail.com", "yahoo.co.uk", "hotmail.com",
"hotmail.co.uk", "outlook.com", "live.com", "msn.com", "icloud.com", "me.com", "mac.com",
"aol.com", "mail.com", "gmx.com", "gmx.de", "proton.me", "protonmail.com",
];
/** Levenshtein distance: the number of single-character edits between two strings. */
function editDistance(a: string, b: string): number {
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
const row = [i];
for (let j = 1; j <= b.length; j++) {
row[j] = Math.min(prev[j]! + 1, row[j - 1]! + 1, prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1));
}
prev = row;
}
return prev[b.length]!;
}
/** "gmial.com" → "gmail.com"; null when the domain is fine or nothing is close. */
export function suggestDomain(domain: string): string | null {
if (POPULAR_DOMAINS.includes(domain)) return null;
let best: string | null = null;
let bestDistance = Infinity;
for (const candidate of POPULAR_DOMAINS) {
const distance = editDistance(domain, candidate);
if (distance < bestDistance) [best, bestDistance] = [candidate, distance];
}
// Short domains only get one edit's leeway: two letters off "me.com" is a different domain.
return bestDistance <= (domain.length <= 6 ? 1 : 2) ? best : null;
}The Levenshtein distance counts two swapped letters (gmial → gmail) as two edits, which the two-edit limit for longer domains still allows. Short domains only get one edit's leeway, because a two-letter difference on me.com is a different domain.
Choose the list of domains carefully. Real providers that sit one letter apart, like mail.com and gmail.com, must both be in it, or users of one get "corrected" to the other. Even then, some genuine domains will look like typos, so show the result as a suggestion and let the user decide.
6. Put it together
Now run the checks from cheapest to most expensive and return a single verdict:
import { checkSyntax } from "./syntax.js";
import { checkDomainCached } from "./dns-cache.js";
import { isDisposable } from "./disposable.js";
import { isRoleAccount, suggestDomain } from "./extras.js";
export type Status = "valid" | "invalid" | "risky" | "unknown";
export interface EmailVerdict {
status: Status;
reason: string;
email: string | null;
didYouMean: string | null;
}
export async function validateEmail(input: string): Promise<EmailVerdict> {
const syntax = checkSyntax(input);
if (!syntax.ok) return { status: "invalid", reason: syntax.reason, email: null, didYouMean: null };
const { local, domain, normalized } = syntax;
const suggestion = suggestDomain(domain);
const base = { email: normalized, didYouMean: suggestion ? `${local}@${suggestion}` : null };
const dns = await checkDomainCached(domain);
if (dns.status === "invalid" || dns.status === "unknown") return { ...base, status: dns.status, reason: dns.reason };
// The domain can receive mail. Now look for risk signals, most serious first.
if (isDisposable(domain)) return { ...base, status: "risky", reason: "disposable" };
if (suggestion) return { ...base, status: "risky", reason: "possible_typo" };
if (dns.status === "risky") return { ...base, status: "risky", reason: dns.reason };
if (isRoleAccount(local)) return { ...base, status: "risky", reason: "role_based" };
return { ...base, status: "valid", reason: "mail_server_found" };
}It returns these results for a range of inputs:
| Input | status | reason | didYouMean |
|---|---|---|---|
jane@gmail.com | valid | mail_server_found | null |
joe@gamil.com | risky | possible_typo | joe@gmail.com |
test@mailinator.com | risky | disposable | null |
support@acme.io | risky | role_based | null |
x@no-such-domain.example | invalid | domain_not_found | null |
not-an-email | invalid | missing_at_or_part | null |
7. Use it in an Express endpoint with Zod
A typical sign-up policy is to reject invalid and disposable addresses, accept everything else, and pass the typo suggestion back so the front end can ask "Did you mean …?". With Zod, the format check is z.email() and the rest goes in an async refinement:
import express from "express";
import { z } from "zod";
import { validateEmail } from "./validate-email.js";
// z.email() checks the format; the refinement adds the DNS and disposable checks.
const SignupBody = z.object({
email: z
.email()
.superRefine(async (email, ctx) => {
const result = await validateEmail(email);
if (result.status === "invalid") ctx.addIssue({ code: "custom", message: "That email address can't receive mail." });
else if (result.reason === "disposable") ctx.addIssue({ code: "custom", message: "Please use a permanent email address." });
}),
});
export const app = express();
app.use(express.json());
app.post("/signup", async (req, res) => {
const parsed = await SignupBody.safeParseAsync(req.body);
if (!parsed.success) {
res.status(422).json({ error: parsed.error.issues[0]!.message });
return;
}
const { email, didYouMean } = await validateEmail(parsed.data.email); // cached: no second DNS lookup
// "unknown" means DNS had a hiccup: accept the address and check it again later.
// await createUser(email);
res.status(201).json({ ok: true, email, didYouMean });
});Because the refinement is async, use safeParseAsync(); the synchronous safeParse() throws on async refinements. The second validateEmail() call is cheap, because the domain is already cached. Start the server from another file with app.listen(3000). Adjust the policy to your product: a B2B form might also reject free providers, while a newsletter might accept role accounts.
8. Test it
The syntax check has no side effects, so it's easy to test with Node's built-in test runner:
import { test } from "node:test";
import assert from "node:assert/strict";
import { checkSyntax } from "./syntax.js";
test("accepts normal addresses", () => {
for (const email of ["jane@example.com", "jane.doe+news@example.co.uk", "user@münchen.de"]) {
assert.equal(checkSyntax(email).ok, true, email);
}
});
test("rejects malformed addresses", () => {
for (const email of ["", "jane", "@example.com", "jane@", "a..b@example.com", "jane@example", "jane@-example.com"]) {
assert.equal(checkSyntax(email).ok, false, email);
}
});Compile with tsc and run node --test dist/. For the DNS checks, point the resolver at a local test DNS server with resolver.setServers(["127.0.0.1:5353"]). Then your test suite doesn't depend on the internet. That's how we tested every result on this page.
What about checking that the mailbox exists?
You could go further with node:net: connect to the domain's mail server on port 25 and ask whether a specific mailbox exists with RCPT TO. We don't recommend doing that inside a request. Many hosting providers block outbound port 25, large providers often accept every recipient at that stage, and catch-all domains and greylisting make the answer inconclusive.
For most sign-up forms, the checks above plus a confirmation email are the best balance of accuracy and speed.
Or use an email validation API
Everything above works, but you have to maintain it: the disposable list goes stale, the typo list needs tuning, and DNS edge cases keep turning up. The validateemail.io API runs all of these checks in one request:
const API = "https://validateemail.io/v1";
const headers = {
Authorization: `Bearer ${process.env.VALIDATEEMAIL_KEY}`,
"Content-Type": "application/json",
};
export interface ApiResult {
email: string;
status: "valid" | "invalid" | "risky" | "unknown";
reason: string;
did_you_mean: string | null;
score?: number;
}
export async function validateWithApi(email: string): Promise<ApiResult> {
try {
const res = await fetch(`${API}/validate`, {
method: "POST",
headers,
body: JSON.stringify({ email }),
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as ApiResult;
} catch (err) {
// Never block a sign-up because the validator is slow or unreachable.
console.warn("Email validation unavailable:", (err as Error).message);
return { email, status: "unknown", reason: "validator_unavailable", did_you_mean: null };
}
}
/** Validates any number of addresses, 100 per request. */
export async function validateList(emails: string[]): Promise<ApiResult[]> {
const results: ApiResult[] = [];
for (let i = 0; i < emails.length; i += 100) {
const res = await fetch(`${API}/validate/batch`, {
method: "POST",
headers,
body: JSON.stringify({ emails: emails.slice(i, i + 100) }),
signal: AbortSignal.timeout(30_000),
});
if (!res.ok) throw new Error(`Batch failed: HTTP ${res.status}`);
results.push(...((await res.json()) as { results: ApiResult[] }).results);
}
return results;
}If the API is slow or unreachable, validateWithApi() returns unknown instead of throwing, so a network problem never blocks a sign-up. The response has the same status and reason fields used in this guide (as did_you_mean rather than didYouMean), plus a score and the result of every individual check.
Using an AI coding assistant? Paste this prompt and it will wire up the API for you:
Add email validation to the sign-up endpoint of this TypeScript (Express) app 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
Is z.email() enough to validate an email in TypeScript?
z.email() is a good format check. It can't tell you whether the domain exists or accepts mail, or whether the address is disposable or mistyped, so pair it with an MX lookup and the other checks in this guide, as the async refinement in step 7 does.
How do I check if an email domain exists in Node.js with TypeScript?
Look up its MX records with resolveMx() from node:dns/promises. An error with code ENOTFOUND means the domain doesn't exist, ENODATA means it exists but has no MX records, and anything else is a temporary DNS problem you should retry rather than reject.
Does this code run in the browser or on edge runtimes?
The syntax check and typo suggestions run anywhere. The DNS lookups need node:dns, which browsers don't have and edge runtimes often don't either. On those, call a DNS-over-HTTPS endpoint or an email validation API from your server code.
Can TypeScript check that a mailbox exists without sending an email?
You can try by opening a connection to the domain's mail server on port 25 and sending RCPT TO. In practice port 25 is often blocked, large providers accept every recipient at that stage, and catch-all domains accept anything, so the answer is often unreliable. A confirmation email is still the only definitive test.