One Time URL Generation for Email Verification in Node.js

Creating a secure one time URL in Node.js for email verification is a common requirement for web applications to authenticate users. By following this comprehensive guide, you’ll learn how to generate an encrypted token with an expiry date using jsonwebtoken, create a unique identifier with UUID, send the URL via email with nodemailer, and verify the token. Let’s start making your application safer and more reliable!

One Time URL Generation for Email Verification in Node.js

Table of Contents

Prerequisites

Before beginning, ensure you have the following installed:

  • Node.js and npm
  • Text editor or IDE of your choice
  • Command-line interface

You will also need to install the required npm packages by running the following commands:

npm install uuid jsonwebtoken nodemailer

 

Generating a Unique ID with UUID

To create a unique identifier, we will use the UUID npm package. This UUID will be part of the encrypted token passed in the URL.

const { v4: uuidv4 } = require('uuid');
const uniqueID = uuidv4();
console.log(uniqueID);

 

Creating an Encrypted Token with jsonwebtoken

To enhance security in our application, we’ll design a function dedicated to generating an encrypted token that includes an expiration time. This function will employ cryptographic techniques to ensure that the token is secure and tamper-proof, making it ideal for sensitive operations like authentication or data protection. Additionally, by incorporating an expiry mechanism, we can further safeguard the system by limiting the token’s validity period, thus reducing the risk of unauthorized use.

const jwt = require('jsonwebtoken');

function generateToken(uniqueID) {
    const expiry = '1h'; // Token expires in 1 hour
    const secretKey = 'your_secret_key'; // Use a secure, environment-specific key
    return jwt.sign({ id: uniqueID }, secretKey, { expiresIn: expiry });
}

// Usage
const token = generateToken(uniqueID);
console.log(token);

To send this token by email, let’s next set up Nodemailer.

 

Setting up Nodemailer for Email Delivery

For sending the token via email, we will create a mailing function with Nodemailer:

const nodemailer = require('nodemailer');

async function sendMail(toEmail, token) {
    const transporter = nodemailer.createTransport({
        service: 'Gmail', // or another email service
        auth: {
            user: '[email protected]',
            pass: 'your_password'
        }
    });

    const mailOptions = {
        from: '[email protected]',
        to: toEmail,
        subject: 'Email Verification',
        html: `<p>Please use the following <a href="http://yourdomain.com/verify?token=${encodeURIComponent(token)}">link</a> to verify your email. Link expires in 1 hour.</p>`
    };

    await transporter.sendMail(mailOptions);
    console.log('Email sent successfully!');
}

// Usage
sendMail('[email protected]', token).catch(console.error);

 

Verifying the One time URL

Upon receiving the email, the user will click the link to verify their email. The server will handle the verification like this:

function verifyToken(req, res) {
    const token = req.query.token;
    const secretKey = 'your_secret_key';

    try {
        const decoded = jwt.verify(token, secretKey);
        console.log('Token verified:', decoded);
        // Proceed with user email verification logic
        res.send('Email verified successfully!');
    } catch (error) {
        console.error('Token verification failed:', error);
        res.status(400).send('Invalid or expired token');
    }
}

 

Troubleshooting Tips

If you encounter issues, consider the following:

  • Ensure your secret key is consistent when signing and verifying a token.
  • Check that the UUID package generates unique identifiers correctly.
  • Ensure your mail service credentials are correct, and that your email service provider does not block the connection.

Conclusive Summary

In this tutorial, you’ve learned to generate a one time URL in Node.js for secure email verification. We’ve covered creating unique identifiers with UUID, generating and verifying an encrypted token with an expiry using jsonwebtoken, and sending the token embedded within an email using nodemailer. These steps contribute to a robust user authentication process.

References