Email verification with Node.js and Nodemailer

Hussain Safwan
3 min readSep 10, 2020

Heard of the saying ‘in internet no one knows if you’re a dog’? Yep, a painfully true statement. Internet is a place where anyone can and given enough scope will pose as anyone else.. and so we need to validate the email address our users provide😅 Philosophy aside. In this writing, we learn to confirm that the email address provided actually belongs to(or at least is accessible to) the user. And node.js has a pretty nice and legit ways to do so. Let’s beign, shall we?

https://media.giphy.com/media/3f8A9DkZ2Ii6OCIxC6/giphy.gif

Here’s what I’ll be using in this tutorial

  1. Nodemailer for email services
  2. MongoDB as database and it’s mongoose framework
  3. Gmail as the email service provider.

The key concept here is to store two more parameters in the user object during registration, one is the unique random string provided and other is a boolean to determine if the email has been validated.

Here’s a typical post handler for registration. A req.body containing the user provided details is being save into the mongoose object along with our validation intended parameters. Let’s define a trivial function to generate a random string.

Now’s the bread and butter of this tutorial, send an actual email to the respective email address the user provided. We’re gonna use your gmail account to accomplish this. For this you’ve got to enable your google less secure apps settings, visit this page to get further instructions by google.

The way it works is via creating a transport variable with the name and auth credentials of your email service in it. Then set up mail options to pack the from/to destinations, subject and actual mail body for the email. Inside the body is an anchor tag hyperlinked to the verification route in your app. As soon as the user presses this link, a get request issues to the given route with the uniqueString as a parameter.

Now as you can see, it’s not gonna work on the production, because the route is directed to http://localhost:3000 .

This is the verify route handler, once the verify request arrives, extracts the attached uniqueString and checks if such an user exists, if so — marks it validated else responds with an error message.

Quite simple, no? If you’ve read all the way down here, do consider putting your hands together for a clap.

CHEERS!

--

--