Email Verification in JavaScript

Email Verification in JavaScript

In the digital age, ensuring that a user's email address is valid and active is crucial for web developers. This practice not only enhances user experience but also secures platforms from spam and unauthorized access.

Email verification can seem daunting at first, but with JavaScript, it becomes an accessible task for developers at all levels. In this article, we'll explore why email verification is essential, how it can be implemented using JavaScript, and the benefits it brings to your web applications.

Why Email Verification?

Before we dive into the "how," let's discuss the "why." Email verification serves several important purposes:

  1. Accuracy: It ensures that users enter a correct email address, which is vital for communication, password recovery, and notifications.
  2. Security: Verifying emails helps to prevent bots and spammers from registering on your site, enhancing its overall security.
  3. User Engagement: Confirmed email addresses can improve user engagement rates since your communications reach the intended audience.

How Does Email Verification Work?

Email verification in JavaScript typically occurs in two steps: format validation and verification through an email confirmation link.

Format Validation (Front-end)

This initial step involves checking if the entered email address follows a standard email format (e.g., user@example.com). JavaScript provides a straightforward way to perform this validation using Regular Expressions (RegEx).

Example Code Snippet:

function validateEmail(email) {
 var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
 return re.test(email);
}

if (validateEmail("user@example.com")) {
 console.log("Email is valid");
} else {
 console.log("Email is invalid");
}


Email Verification Through Confirmation Link

After the format check, the next step involves sending a confirmation link to the user's email. When the user clicks on this link, it verifies that the email address is active and accessible.

Implementing this step involves backend support, but let's understand its essence:

  1. Send a Verification Email: Upon registration, trigger an email to the user's address with a unique verification link.
  2. User Clicks the Link: The link redirects the user to your website, where the backend marks the email as verified.

Increase your productivity by using ChatGPT and stay ahead of the competition, Click here to get ChatGPT Guide

Let's write the code for above logic using Node.js

Backend Setup with Node.js

First, ensure you have Node.js installed on your machine. Then, you can set up a new Node.js project and install the necessary packages:

mkdir email-verification-project
cd email-verification-project
npm init -y
npm install express nodemailer dotenv mongoose uuid


Environment Configuration

Create a .env file in your project root to store sensitive information like your email service credentials:

# SMTP config
EMAIL_HOST=your_smtp_host
EMAIL_PORT=your_smtp_port
EMAIL_USER=your_email_address
EMAIL_PASS=your_email_password
FRONTEND_URL=http://localhost:3000

#mongodb
MONGODB_URI=your_mongodb_connection_string


Logic for email verification

require('dotenv').config();
const express = require('express');
const nodemailer = require('nodemailer');
const mongoose = require('mongoose');
const { v4: uuidv4 } = require('uuid');

const app = express();
app.use(express.json());

// MongoDB setup
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
 .then(() => console.log('MongoDB Connected'))
 .catch(err => console.log(err));

const UserSchema = new mongoose.Schema({
 email: String,
 verificationToken: String,
 verified: Boolean,
});

const User = mongoose.model('User', UserSchema);

// Nodemailer setup
const transporter = nodemailer.createTransport({
 host: process.env.EMAIL_HOST,
 port: process.env.EMAIL_PORT,
 secure: true, // true for 465, false for other ports
 auth: {
  user: process.env.EMAIL_USER,
  pass: process.env.EMAIL_PASS,
 },
});

app.post('/send-verification-email', async (req, res) => {
 const { email } = req.body;
 const verificationToken = uuidv4();

 try {
  let user = await User.findOne({ email });
  if (!user) {
   user = new User({ email, verificationToken, verified: false });
   await user.save();
  }

  const verificationLink = `${process.env.FRONTEND_URL}/verify-email?token=${verificationToken}`;

  await transporter.sendMail({
   from: process.env.EMAIL_USER,
   to: email,
   subject: 'Verify Your Email',
   html: `<p>Please click the link to verify your email: <a href="${verificationLink}">${verificationLink}</a></p>`,
  });

  res.json({ message: 'Verification email sent.' });
 } catch (error) {
  console.error('Error sending verification email', error);
  res.status(500).json({ message: 'Error sending verification email' });
 }
});

app.get('/verify-email', async (req, res) => {
 const { token } = req.query;

 try {
  const user = await User.findOne({ verificationToken: token });
  if (!user) {
   return res.status(400).send('Invalid token.');
  }

  user.verified = true;
  await user.save();

  res.send('Email verified successfully.');
 } catch (error) {
  console.error('Error verifying email', error);
  res.status(500).send('Error verifying email');
 }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));


You can take required code from the above code, As I have combined all logic of database, email server setup, sending email link and email verification.

Increase your productivity by using ChatGPT and stay ahead of the competition, Click here to get ChatGPT Guide

Frontend Integration

On the frontend, ensure you have a route that matches /verify-email?token=UNIQUE_TOKEN_HERE, which should make a GET request to your backend's /verify-email endpoint with the token. After verification, you can display an appropriate message to the user.

This example provides a foundational approach to implementing email verification with MongoDB in a Node.js application.

Remember to replace placeholders with your actual data and expand upon this code based on your application's specific requirements and security considerations.


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Are you looking for Front-end Developer Job?

Get Front-end Interview Kit Now, And Be Prepared to Get Your Dream Job

Get Front-end Interview Kit

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates