Advanced Email Validation using ApyHub’s API in NodeJS
Tags: oauth, applicationsecurity, webdev, node
Published: 2023-05-12 14:51:51

Email authentication has become increasingly important in recent years for the overall security of online communication, by ensuring authenticity, and protection against email fraud, phishing and other malicious activities.

Email validation can help address the issue; here are some advantages of using email validation:

- It can help detect syntax errors, typos, and invalid email addresses that can cause email delivery failures
- Network issues and over-aggressive blacklists can also result in email delivery failures, but email validation can help ensure reliable email delivery
- By implementing email validation, businesses can ensure that their email campaigns reach their intended recipients, improve their sender reputation, and maintain a positive brand image
- Additionally, email validation can help prevent potential data breaches and protect sensitive information that could be compromised through fraudulent emails

[ApyHub’s Email Validation API](https://apyhub.com/utility/validator-dns-email) is a cloud-based API service that allows developers to easily integrate email validation functionality into their applications. This API is designed to validate email addresses in real-time, providing accurate and reliable results that can help organisations reduce email bounce rates, prevent fraud, and improve their email marketing efforts.

## How does it work?

ApyHub Email Validation API uses a multi-step process to validate email addresses. Here is an overview of how the API works:

1. **Syntax check:** The API first checks the syntax of the email address to ensure that it conforms to the standard format. This includes checking for missing "@" or "." symbols and ensuring that the address does not contain any invalid characters.
2. **Standard Response:** The API is a RESTful API that delivers data in JSON format.
3. **Domain verification**: The API then verifies the email address domain by checking its DNS records. This helps ensure that the domain is valid and active and can receive email. 
4. **Spam trap and disposable email check:** Finally, the API checks the email address against known spam traps and disposable email address providers. This helps prevent fraudulent or invalid email addresses from being used. This list gets updated from a wide variety of sources daily basis to make sure you get the most up-to-date and accurate information to protect your system from potential threats related to spam and fraud.

(Looking for other ways to ensure security for your website or application? [Here’s why and how you can use Secure Archives to share files](https://apyhub.com/blog/Secure-archives-to-share-files))

## Quick tutorial

In this tutorial, we will be going to build an authentication app using Mongoose for storing emails in a database. While the user signup, we will check whether the email is valid or not.

## **Prerequisites**

- Node.js v16+
- An ApyHub account
- Git CLI

1. To get started with ApyHub you first need to register for a free account to get an API Key (apy-token). You can use Google Authentication or GitHub Authentication as well.

![auth.png](https://i.postimg.cc/DZ7fYHvP/auth.png)

Once your signup is successful, ApyHub creates a default application with APY-TOKEN. You can find the token by navigating to **Dashboard →  API Keys → Default Application** 
Eg. **APY*************************************************CZR**

2. Clone the starter project from the repository:

```bash
git clone https://github.com/iamspathan/apyhub-email-validation-tutorial.git
```

3. Install dependencies

```bash
npm install
```

4. Add your Secret APY-TOKEN in server.js

```jsx
app.post('/signup', async (req, res) => {
  try {
    const { email, password } = req.body;

    //validate email using ApyHub API
    const response = await axios.post('https://api.apyhub.com/validate/email/dns', { email }, {
      headers: {
        'apy-token': 'ADD-YOUR-APY-TOKEN-HERE',
        'Content-Type': 'application/json'
      }
    });
   
    if (!response.data.data) {
      return res.status(400).json({ message: 'Invalid email address' });
    }

    // Check if user already exists
    const user = users.find(u => u.email === email);
    if (user) {
      return res.status(409).json({ message: 'User already exists' });
    }

    // Hash password
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // Save user
    users.push({ email, password: hashedPassword });
    res.status(201).json({ message: 'User created' });

  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal server error' });
  }
});
```

5. Start the app

```bash
node server.js
```

6. Finally, Navigate to [http://localhost:3000](http://localhost:3000), You will able to see the Signup page.

![account-signup.png](https://i.postimg.cc/HnCN21TT/account-signup.png)

*Note: The authentication module mentioned in this project is provided solely as a recommendation for the project structure. While we highly encourage its use and integration according to your architecture pattern.*

## Use Cases:

1. **Bulk email verification**: Enterprises may have large email lists that need to be validated for accuracy and deliverability. An email validation API can be used to check the validity of each email address in the list, ensuring that emails are sent only to valid addresses.
2. **Fraud prevention**: Email validation APIs can also be used to detect fraudulent email addresses used in phishing attacks, preventing unauthorised access to enterprise systems.
3. **Marketing campaigns**: Email validation APIs can help enterprises ensure that their marketing emails reach the intended recipients by verifying the email addresses in their lists and removing invalid addresses.
4. **Compliance**: Email validation APIs can help enterprises comply with data protection regulations by ensuring that emails are sent only to users who have provided valid consent.
5. **Customer support:** Email validation APIs can be used to verify the email addresses of customers who submit support requests, ensuring that the enterprise is communicating with the correct customer.

So, if you're looking to improve email deliverability, reduce bounce rates and avoid spam accounts, [sign up for ApyHub's email validation](https://apyhub.com/utility/validator-dns-email) API today.