Email Verification - GeeksforGeeks

30 Nov, 2021
Email verification is a technique in node.js which is used to ensure whether the provided email corresponds to an existing user or not because otherwise the database will become filled up with unnecessary users. 
The process goes like that we send some kind of token to email and the user sends get request along with that token, now if the get request consists of the exact token we earlier sent from the server then email is considered as verified.  
Prerequisite: nodemailer, jwt, basic working of node and express.  
Step 1: Create a node project & Initialize code with installation
npm init            // To initialize the package
npm install jsonwebtoken // To generate token 
npm install express      // To create server
npm install nodemailer   // To send email
This would be our folder structure after installation and creating two empty files namely app.js and tokenSender.js
Step 2: Create a route to generate tokens and send an email   
After installation, we can proceed to generate a token with jwt and send an email with nodemailer here we are using Gmail as a service for simplification but the fundamental concepts remain the same.   
Explanation: In the first line we have imported the nodemailer package which will later be used for sending mail, and then we have created a transporter object which is used to send mail and it contains some configurations about the email service and sender. And then we have created another object which will contain information about mail like the receiver, sender, text of the email, etc. In the end, the sendMail method of the transporter object simply sends the mail to the given address. 
tokenSender.js
const nodemailer = require('nodemailer');const jwt = require('jsonwebtoken');  const transporter = nodemailer.createTransport({    service: 'gmail',    auth: {        user: secure_configuration.EMAIL_USERNAME,        pass: secure_configuration.PASSWORD    }});  const token = jwt.sign({        data: 'Token Data'  .    }, 'ourSecretKey', { expiresIn: '10m' }  );      const mailConfigurations = {      // It should be a string of sender/server email    from: 'mrtwinklesharma@gmail.com',      to: 'smtwinkle451@gmail.com',      // Subject of Email    subject: 'Email Verification',          // This would be the text of email body    text: `Hi! There, You have recently visited            our website and entered your email.           Please follow the given link to verify your email           http://localhost:3000/verify/${token}            Thanks`      };  transporter.sendMail(mailConfigurations, function(error, info){    if (error) throw Error(error);    console.log('Email Sent Successfully');    console.log(info);});
Output:We are executing the file with node command and as expected our email is being sent successfully.
Step 3: Create a route to receive get request along with the token and verify email  
After we have sent the token to the user the next step is to set up a route on the server, and the user will send the get request with the token in the parameter because the browser can send only data with URL. 
Explanation: Here we have created a simple express server and there exists a get route. Inside that, we are extracting the information i.e. token from URL, and then we are verifying it with jwt like whether the token being sent is exactly the one which was generated from our server or not. Finally, the route is sending the appropriate response according to the verification of the token.
Filename:
app.js
const express = require('express');const jwt = require('jsonwebtoken');  const app = express();const PORT = 3000;  app.get('/verify/:token', (req, res)=>{    const {token} = req.params;      // Verifing the JWT token     jwt.verify(token, 'ourSecretKey', function(err, decoded) {        if (err) {            console.log(err);            res.send("Email verification failed,                     possibly the link is invalid or expired");        }        else {            res.send("Email verifified successfully");        }    });});  app.listen(PORT, (error) =>{    if(!error)        console.log("Server is Successfully Running,                   and App is listening on port "+ PORT)    else        console.log("Error occured, server can't start", error);    });
Output: Run the server with node command.
In the inbox, we will have our email sent by the server. After this, we are making a get request on the server by clicking on the link given and as expected the server will respond as email verified. Later we are changing the URL a little bit to make the URL invalid and correspondingly server is responding that email verification failed because of the invalid token. 
Conclusion: This was the entire code and workflow of verifying email in nodejs. You can check out linked geeksforgeeks articles in the prerequisite section, to know more about these libraries. In some other examples the terms, libraries, techniques, design patterns may change a little bit but the general concept will remain the same. 
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript