skip to Main Content

I’m trying to make an e-mail verification system using Node.js, Express and EJS.

Currently, when a user registers, the server will generate a link, say

https://www.website.com/verify=foo/

and then sends it to their e-mail address. How do I make it so that the generated link directs to https://www.website.com/verify/ with the context foo, and then fetch it using a POST method to /verify, so that I can execute code with the given context?

2

Answers


  1. Clicking a link usually causes a GET request. So in your server code you should listen for get

    app.get('/verify', function(req, res){
      res.send('foo: ' + req.query.foo);
    });
    

    Please pay attention your link should in this case contain a ? and look like this: https://www.website.com/verify/?foo=value

    Login or Signup to reply.
  2. What I understood from your question is you want to send verification link to the user via email, and you want to include that link in the mail.

    Here is one possible solution with demo code using nodemailer package.

    const express = require('express');
    const nodemailer = require('nodemailer');  // Package used for sending mail to users
    const app = express();
    
    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '[email protected]',
            pass: 'test123' // This should be an App password generated from your Gmail account settings
        }
    });
    
    // Function to send verification email
    function sendVerificationEmail(email, verificationLink) {
        // Email options
        const mailOptions = {
            from: '[email protected]',
            to: email,
            subject: 'Email Verification',
            html: `<p>Please click <a href="${verificationLink}">here</a> to verify your email address.</p>`
        };
    
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                console.error('Error sending email:', error);
            } else {
                console.log('Email sent:', info.response);
            }
        });
    }
    
    // Register route
    app.post('/register', (req, res) => {
        const { email } = req.body;
    
        // without token
        // const verification = `https://www.website.com/verify?value=foo`;
    
        // using token , first generate token based on the stored user information
        const verificationLink = `https://www.website.com/verify?token=foo`; // Modified to use a token in the query parameter
        // We want that when a user simply clicks on that link, technically they are essentially making a GET request. Therefore, it's better to pass it as a query parameter.
    
    
        // Send verification email
        sendVerificationEmail(email, verificationLink);
    
        res.send('Verification email sent successfully!');
    });
    
    app.get("/verify", (req, res) => {
        const { token } = req.query; // Fetching value from query parameter
    
        // Now this token can be verified against the one previously sent to the user
    
        // Generally, in the userModel, we create a field named isVerified which has a default value of 0. At the time of registration, when we create a user, we use JWT to generate a token containing user information in encrypted format.
        // Now, when a new user receives the verification email and clicks the link (in our case /verify?token=tokenValue), we decode the token and fetch user information from the database, updating the isVerified field.
        // Now, when the user tries to log in, we check the isVerified field in the database. If it is 1, the user can log in; otherwise, the user can't log in.
    
        console.log(token);
        res.send("Verified");
    });
    
    // Start the server
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search