Validating email addresses is a key step for data integrity in any npm project. We will walk through three common methods for building an email validator, providing working code for each. Then, we'll examine the shortcomings of these approaches and see how Abstract API offers a more robust solution.
How to Implement an Email Validator in npm
Here are three common methods to build an email validator in your npm project. Each approach has a different level of complexity and provides a distinct type of validation.
Syntax-Only Check with validator.js
The validator.js package offers a straightforward way to check email syntax. It relies on regular expressions that the library refines for over a decade to stay current with RFC 5322 edge cases.
This package has zero dependencies and is tree-shakeable, which makes it simple to integrate into any project. Because it performs simple string mathematics, it achieves a high throughput of over one million operations per second under V8.
The code imports the "isEmail" function from the library. It then passes an email address to this function, which returns a boolean value that indicates if the syntax is correct.
npm i validator
import isEmail from 'validator/lib/isEmail';
const ok = isEmail('user@example.com'); // boolean
Syntax and DNS MX Verification with node-email-verifier
The node-email-verifier package performs a two-step validation. First, it runs a pattern match based on RFC-5322 standards to check the email's format.
Next, it executes a "dns.resolveMx" command. This action confirms that the domain has a mail exchange record and can actually accept mail. An optional "timeout" flag protects your event loop from slow DNS responses. The package also provides a fast path with "checkMx:false" if you only need a syntax check.
The code imports the "verify" function. It then calls this function with the email address and an options object to check for an MX record with a one-second timeout.
npm i node-email-verifier
import verify from 'node-email-verifier';
const ok = await verify('user@example.com', { checkMx: true, timeout: 1000 });
A Custom Build with DNS and SMTP
This do-it-yourself method provides full control over the validation process. It involves a sequence of checks. First, you perform a regex pass on the email address. You can reuse validator.js for this or implement a custom pattern.
The second step is an MX lookup. The code uses "dns/promises" to resolve the domain's MX records. The final step is an SMTP probe to the mail server. The code connects to the server and sends a sequence of commands like "HELO", "MAIL FROM", and "RCPT TO".
It does not send any actual email data. Instead, it listens for a response code from the server, such as "250" for success or "550" for failure, to determine if the recipient is valid. This approach can be wrapped 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 of Email Validation in npm
Despite the availability of several methods, developers face significant hurdles. These range from complex email standards and evolving domain names to security risks within the npm ecosystem.
- Email standards like RFC 5322 are complex and sometimes conflict. Libraries such as validator.js simplify this with a single regex, which creates gaps. For example, it may incorrectly handle extended-ASCII characters even with specific flags disabled.
- Regex-based tools like validator.js struggle with edge cases such as dotted local parts or quoted strings. A small tweak to the regex can break other valid formats, which forces maintainers to constantly patch the code to fix new issues.
- The internet constantly evolves with new top-level domains and international characters. Packages that perform DNS checks, like node-email-verifier, can become outdated. They may silently fail on new domains, which breaks user signups while all tests still pass.
- The npm ecosystem contains malicious look-alike packages that mimic legitimate validators. These packages can hide preinstall hooks to execute supply-chain attacks. A compromised validator dependency can expose your entire continuous integration environment to significant security threats.
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 Improves npm Email Validation
Unlike regex-only packages, Abstract API addresses the core weaknesses of traditional validation. It layers multiple real-time checks to confirm an email address actually exists and can receive mail.
- It layers multiple tests that include syntax checks, typo autocorrect, and lookups for disposable, free, or role-based domains. It also adds MX record resolution, a real-time SMTP handshake, and catch-all detection.
- The heavy DNS and SMTP work runs on Abstract’s infrastructure. This keeps Node processes non-blocking and removes the need to open ports or manage large domain lists.
- Continuous daily and weekly feed updates mean the validation logic remains current. This process reduces the frequency of production redeploys.
- The normalized and versioned JSON response simplifies upgrades. It also lets you centralize logs and alerts around deliverability or risk scores.
How to Add Abstract API to Your Dev Environment
Once you understand Abstract’s capabilities, the addition of its email validator API to your project is simple.
- Use npm to install an HTTP client like Axios and the dotenv package.
- Sign in at Abstract API, create an Email Verification key, and copy it.
- Add your API key to a .env file and ensure you load dotenv early in your application.
- Create a dedicated module to contain the API call logic.
- Import the new verification function wherever your application accepts emails.
- Use the response data to gate user journeys based on deliverability and a quality score you define.
Sample Email Validator Implementation with Abstract API
The following function demonstrates a call to the Abstract API email validation endpoint. It accepts an email address as a parameter, sends it to the API along with your key, and returns a structured JSON object. This response contains a comprehensive breakdown of the email’s validity.
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 a valid address like "johnsmith@gmail.com", the API returns a detailed 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 "deliverability" field provides a clear allow or block signal. You can use "quality_score" to flag borderline cases for review. The various "is_*_email" flags permit deeper segmentation or trigger additional verification steps. Finally, the "autocorrect" field suggests a fix for common user typos to improve conversions.
Final Thoughts
Simple regex checks often fail to detect invalid domains or disposable addresses, which leads to high bounce rates. Abstract API solves this with a multi-layered approach that includes real-time SMTP handshakes and domain checks. To reliably validate user emails, you can create an Abstract API account and get your free 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