Email validation in Node.js
On a Node.js server you can go further than the browser: after a syntax check, look up the domain's MX records with dns.promises.resolveMx and reject domains that can't receive mail. To know whether the mailbox itself exists, call a verification API, with a timeout and a plan for slow answers.
Three checks, cheapest first
Run the checks in order of cost and stop at the first failure. A syntax check takes microseconds and catches malformed input. An MX lookup takes milliseconds, can be cached, and catches domains that don't exist or don't take mail, which covers most domain typos. A mailbox check takes seconds and is the only one that tells you whether dana@ is a real person.
Each step answers a narrower question, and none replaces the next. A domain with healthy MX records can still host a dead mailbox, accept everything as a catch-all, or belong to a disposable-inbox provider.
1. Syntax and length
A loose pattern plus the length limits from RFC 5321: 64 characters before the @ and 254 in total. domainToASCII converts internationalised domains to the form DNS expects, and returns an empty string for invalid ones.
// validate.js
import { domainToASCII } from "node:url";
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export function parseEmail(input) {
const email = String(input ?? "").trim();
const at = email.lastIndexOf("@");
if (!EMAIL_RE.test(email) || at > 64 || email.length > 254) return null;
const domain = domainToASCII(email.slice(at + 1).toLowerCase());
if (!domain) return null;
return { email, domain };
}2. MX lookup with dns.promises
resolveMx from node:dns/promises returns the domain's mail servers as { exchange, priority } objects. A Resolver instance has the same methods plus a timeout, which matters on a request path. Treat DNS errors other than "not found" and "no data" as unknown, never as a reason to reject.
// mx.js
import { Resolver } from "node:dns/promises";
const resolver = new Resolver({ timeout: 2000, tries: 2 });
const cache = new Map(); // domain -> { ok, expires }. Use an LRU or Redis in production.
export async function domainAcceptsMail(domain) {
const hit = cache.get(domain);
if (hit && hit.expires > Date.now()) return hit.ok;
let ok;
try {
const records = await resolver.resolveMx(domain);
// Null MX (RFC 7505): a lone "0 ." record means the domain takes no mail
ok = records.some((r) => r.exchange !== "" && r.exchange !== ".");
} catch (err) {
if (err.code === "ENOTFOUND") {
ok = false; // the domain doesn't exist
} else if (err.code === "ENODATA") {
ok = await hasAddressRecord(domain); // no MX: RFC 5321 falls back to A/AAAA
} else {
return true; // ETIMEOUT, ESERVFAIL...: a DNS problem, not an answer
}
}
cache.set(domain, { ok, expires: Date.now() + 10 * 60 * 1000 });
return ok;
}
async function hasAddressRecord(domain) {
const results = await Promise.allSettled([resolver.resolve4(domain), resolver.resolve6(domain)]);
return results.some((r) => r.status === "fulfilled" && r.value.length > 0);
}Reading the MX result
| Outcome | What it means | What to do |
|---|---|---|
| Records returned | The domain publishes mail servers | Continue to the mailbox check |
ENOTFOUND | The domain doesn't exist | Reject; it's usually a typo |
ENODATA | The domain exists but has no MX records | Check A/AAAA records; real mail domains rarely work this way, so treat it with suspicion |
Only a 0 . record | Null MX: the domain states it accepts no mail | Reject |
ETIMEOUT, ESERVFAIL and others | A resolver problem, yours or theirs | Don't reject; let it through or retry later |
Falling back to the A record is defined in RFC 5321; null MX in RFC 7505.
3. Mailbox check with the MailVet API
fetch is built into Node 18 and later. AbortSignal.timeout() caps the whole request, timeout=5 asks the API to answer with pending rather than make the user wait, and a 429 is retried after Retry-After.
// mailvet.js
import { setTimeout as sleep } from "node:timers/promises";
export async function verifyMailbox(email, { waitSeconds = 5 } = {}) {
const url = new URL("https://api.mailvet.app/v1/verify");
url.searchParams.set("email", email);
url.searchParams.set("timeout", String(waitSeconds)); // 3 to 15
for (let attempt = 1; attempt <= 3; attempt++) {
const res = await fetch(url, {
headers: { Authorization: "Bearer " + process.env.MAILVET_KEY },
signal: AbortSignal.timeout((waitSeconds + 3) * 1000),
});
if (res.status === 429) {
await sleep(Number(res.headers.get("retry-after") ?? 1) * 1000);
continue;
}
if (!res.ok) throw new Error("MailVet " + res.status + ": " + (await res.text()));
return res.json(); // 200 with status "done", or 202 with status "pending"
}
throw new Error("MailVet: still rate limited after 3 attempts");
}Put the three checks in the signup route
Cheapest first, stopping at the first definite failure. If MailVet can't answer in time, the user still gets in and the address is stored as unchecked or pending, to be settled later.
// server.js (Express 5, which passes rejected promises to the error handler)
import express from "express";
import { parseEmail } from "./validate.js";
import { domainAcceptsMail } from "./mx.js";
import { verifyMailbox } from "./mailvet.js";
const app = express();
app.post("/signup", express.json(), async (req, res) => {
const parsed = parseEmail(req.body?.email);
if (!parsed) return res.status(422).json({ error: "Enter a valid email address." });
if (!(await domainAcceptsMail(parsed.domain))) {
return res.status(422).json({ error: "That domain can't receive email. Check for typos." });
}
let check = null;
try {
check = await verifyMailbox(parsed.email);
} catch (err) {
console.warn("mailbox check skipped:", err.message); // timeout or outage: let them in
}
if (check?.result === "undeliverable" || check?.reason === "disposable") {
return res.status(422).json({ error: "Please use an address that can receive email." });
}
const user = await createUser({ // your own persistence
email: parsed.email,
emailStatus: check ? (check.status === "pending" ? "pending" : check.result) : "unchecked",
emailCheckId: check?.id ?? null,
});
res.status(201).json({ id: user.id });
});4. Finish pending checks with a webhook
Slow catch-all checks finish within minutes and arrive as a verification.completed event. Check the MailVet-Signature header against the raw body (so mount express.raw on this route, not express.json), update the record, then answer with a 2xx within 10 seconds. Events can arrive more than once, so make the update idempotent.
// webhook.js (same Express app)
import crypto from "node:crypto";
function isFromMailVet(raw, header, secret) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const expected = Buffer.from(
crypto.createHmac("sha256", secret).update(parts.t + "." + raw).digest("hex"),
);
const given = Buffer.from(parts.v1 ?? "");
const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
return fresh && given.length === expected.length && crypto.timingSafeEqual(given, expected);
}
app.post("/hooks/mailvet", express.raw({ type: "application/json" }), async (req, res) => {
const raw = req.body.toString("utf8");
if (!isFromMailVet(raw, req.get("MailVet-Signature") ?? "", process.env.MAILVET_WEBHOOK_SECRET)) {
return res.sendStatus(401);
}
const { event, data } = JSON.parse(raw);
if (event === "verification.completed") {
// Idempotent: writing the same result twice is harmless
await updateUserEmailCheck(data.id, { emailStatus: data.result, emailReason: data.reason });
}
res.sendStatus(200);
});Node.js email validation questions
How do I check if an email domain exists in Node.js?
Call resolveMx from node:dns/promises. An ENOTFOUND error means the domain doesn't exist; ENODATA means it exists but has no MX records, in which case mail falls back to its A or AAAA record. A list of records means the domain is set up to receive mail.
Can Node.js check whether an email address really exists?
Only by connecting to the domain's mail server on port 25 and asking about the recipient. Most cloud hosts block outbound port 25, catch-all domains accept every address, and repeated probes can get your server's IP blocklisted. A verification API does that part for you.
Should I cache MX lookups?
Yes. MX records rarely change, and a handful of domains make up most signups. Caching results for a few minutes removes most of the DNS latency from your request path.
Which npm package should I use for email validation?
For syntax, the validator package's isEmail() is widely used and configurable, and a simple regex works too. No package can confirm a mailbox exists without contacting the mail server, so pair the syntax check with an MX lookup and a verification API.
Ship the mailbox check today
2,000 requests a second per account, webhooks for slow checks, and unknown results never charged. 100 free credits, no card.
Related
Last updated November 13, 2026