Verifying user emails is a common task for keeping data clean in Node.js applications. We will explore five different methods for email validation, complete with working code snippets. We will also examine the pitfalls of common approaches and see how Abstract API provides a more robust solution.
Email Validation with npm Packages
The Node.js ecosystem offers several packages to validate emails. These tools range from simple syntax checks to more complex verifications that involve network requests to check domain validity.
Syntax-Only Validation with validator.js
The validator.js package provides a simple function to check if a string conforms to email syntax standards. It uses a regular expression logic refined over ten years to handle edge cases found in RFC 5322.
This library has zero dependencies, is tree-shakeable, and integrates easily into projects. Its high throughput, which exceeds one million operations per second under V8, comes from its reliance on simple string mathematics.
The code imports the isEmail function and passes an email string to it. The function returns a boolean value, true if the email format is valid and false otherwise.
npm i validator
import isEmail from 'validator/lib/isEmail';
const ok = isEmail('user@example.com'); // boolean
Syntax and DNS MX Checks with node-email-verifier
The node-email-verifier package performs a two-step validation. First, it runs a pattern match against the email string based on RFC-5322 standards to confirm the syntax is correct.
Next, it executes a DNS MX record lookup to confirm that the email's domain has a mail server configured to accept mail. An optional timeout flag protects your application's event loop from slow DNS responses.
The code calls the verify function with the email address. The options object specifies that a DNS MX check should occur with a timeout of 1000 milliseconds.
npm i node-email-verifier
import verify from 'node-email-verifier';
const ok = await verify('user@example.com', { checkMx: true, timeout: 1000 });
Custom DNS and SMTP Handshake
A do-it-yourself approach offers full control over the validation process. This method involves a sequence of checks that you implement manually. The first step is a regular expression pass, where you can reuse a library like validator.js or a custom pattern.
The second step is an MX record lookup, which you can perform with Node's native dns/promises module. The final step is an SMTP probe where you connect to the mail server and issue a "RCPT TO" command to see if the server recognizes the recipient address.
This method allows you to tune parameters like retry logic, TLS, and parallelism. You can also wrap the logic in a worker pool to avoid any block on Node’s single thread.
// 1. Regex pass (reuse validator.js or your custom pattern).
// 2. MX lookup:
import {resolveMx} from 'dns/promises';
const mx = await resolveMx(domain);
// 3. SMTP “RCPT TO” probe (don’t send DATA):
import net from 'net';
const sock = net.createConnection(25, mx[0].exchange);
sock.write('HELO example.com\r\n');
sock.write('MAIL FROM:<noreply@example.com>\r\n');
sock.write('RCPT TO:<user@example.com>\r\n');
// look for 250 or 550 response codes.
Challenges with npm Email Validators
While npm packages offer convenience, they have inherent limitations and risks. These tools often struggle with complex email standards and the rapid evolution of domain management.
- Conflicting RFC specifications create predictable gaps. Regex-based tools like validator.js often fail to handle edge cases like extended-ASCII characters, even when specific flags are disabled, due to the complexity of email standards.
- Regex tweaks for edge cases often introduce new bugs. For example, validator.js rejects valid addresses with multiple periods inside quotes, which forces a constant cycle of fixes for maintainers.
- The domain landscape evolves faster than most packages. New TLDs and internationalized domain names cause slow or abandoned libraries to fail silently. This breaks user signups while automated tests continue to pass.
- The npm ecosystem contains look-alike packages with malicious code. A recent supply-chain attack used a fake email validator to install malware, a reminder that even simple dependencies pose a security risk.
Validate Emails with Abstract API
Add our email validation API to your project to maintain clean data and improve deliverability.
Get started for free
How Abstract API Handles Email Validation in npm
Abstract API addresses the core weaknesses of traditional methods. It layers multiple real-time tests that go far beyond a simple syntax check.
- Popular npm packages rely on a regular expression that only checks syntax. They cannot tell if a domain exists or if a mailbox will accept mail, which produces false positives. Abstract API layers multiple tests, from syntax and typo checks to MX record resolution and real-time SMTP handshakes.
- Because the heavy DNS and SMTP work runs in Abstract’s infrastructure, Node processes stay non-blocking. You avoid the need to open ports or manage large domain lists.
- Continuous feed updates mean the validation logic remains current without the need for frequent production redeploys.
- The normalized and versioned JSON response simplifies upgrades. You can centralize logs and alerts around deliverability or risk scores while your code remains stateless.
How to Add Abstract API to Your Project
Once you know Abstract’s capabilities, the addition of its email validator API to your project is simple.
- Install the necessary packages with the command
npm i axios dotenv
. Any HTTP client works. - Sign into your Abstract API account, create an Email Verification key, and copy it.
- Add your key to a .env file with the variable ABSTRACT_EMAIL_KEY=pk_xxxxxxxxx and load dotenv early in your application.
- Create a dedicated module like src/emailVerifier.js for the API call.
- Import your new verifyEmail function wherever you accept or batch-process emails.
- Use the response data to gate user journeys. For example, check if data.deliverability equals 'DELIVERABLE' and meets a quality_score you define.
Sample Email Validator Implementation
The function below sends a GET request to the Abstract Email Validation API with a user's email. The API returns a detailed JSON object. This object contains a final deliverability status and multiple flags you can use for more granular control.
import axios from 'axios';
export async function verifyEmail(email) {
const { data } = await axios.get('https://emailvalidation.abstractapi.com/v1/', {
params: { api_key: process.env.ABSTRACT_EMAIL_KEY, email }
});
return data;
}
For an address like “johnsmith@gmail.com”, the API provides the following response:
{
"email":"johnsmith@gmail.com",
"autocorrect":"",
"deliverability":"DELIVERABLE",
"quality_score":0.9,
"is_valid_format":{"value":true,"text":"TRUE"},
"is_free_email":{"value":true,"text":"TRUE"},
"is_disposable_email":{"value":false,"text":"FALSE"},
"is_role_email":{"value":false,"text":"FALSE"},
"is_catchall_email":{"value":false,"text":"FALSE"},
"is_mx_found":{"value":true,"text":"TRUE"},
"is_smtp_valid":{"value":true,"text":"TRUE"}
}
The response fields offer deep insight. The deliverability field combines all checks for a single allow or block decision. The quality_score lets you throttle or flag borderline cases. Other flags for disposable, role, or catch-all emails help drive segmentation or add verification steps. The autocorrect field suggests a fix for user typos to improve conversions.
Final Thoughts
Traditional npm validators often rely on syntax checks alone. This method produces false positives and fails to detect non-existent domains or temporary addresses. Abstract API overcomes these limits with a multi-layered approach that includes real-time SMTP checks and domain analysis. To reliably validate user emails, create a free Abstract API account and get your API key.
Validate Emails with Abstract API
Use our email validation API to stop fake sign-ups and protect your sender reputation.
Get started for free