Sandz
Sandz

Reputation: 109

email verification in mern stack

please tell me how to verify the email when signing up to a new account in MERN Stack??I want to send an email with a link to redirect to the page to the user's email.. this is my node.js code for sign up...please tell how to add verfication part here?

router.post('/abc',function(req,res,next){
User.find({email:req.body.email}).then(function(details){
if(details.length>0){
    return res.status(400).json({
        message:"email exist"
    });

}

else{

    bcrypt.hash(req.body.pass,10,(err,hash)=>{
        if(err){
            return res.status(500).json({
                error:err
            });
        }
        else{  

              var det = new User({

                email:req.body.email,
                password:hash,
                name:req.body.name,
                address:req.body.address,
                mobile:req.body.mobile,
                type:req.body.type


                  });
                 det.save((err,doc)=>{
                if(!err){
                    res.status(200).send(doc);
                    console.log("signed")
                    console.log(doc);
                }
                else{
                    console.log('Error in sending Employees :'+ JSON.stringify(err,undefined,2));
                    return res.status(500).json({
                        error:err
                    });
                }
                });
            }

            });

}
});

  }); 

Upvotes: 0

Views: 2802

Answers (2)

williamcodes
williamcodes

Reputation: 338

Generally, you'd want some kind of emailing api; I personally use Twilio's SendGrid api (very easy to set up and implement). Using this api, you'd construct and send a url (the email verification url) from the back end register route. The implementation is as simple as:

const sgMail = require('@sendgrid/mail');


sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const link = 'http://'+req.headers.host+'/api/users/register/verifyEmail/'+token;

const htmlContent = 'some html content';

const msg = {
    to: newUser.email,
    from: process.env.VALIDATION_EMAIL_SENDER,
    subject: 'Some email subject',
    html: htmlContent,
};

sgMail.send(msg, (err) => {
    if(Object.entries(err).length > 0) {
            return res.status(500).json({success: false, msg: "Something went wrong; can't send validation email.", err});
    }

    res.status(200).json({success: true, msg: "Check your email and verify account to 
    proceed.", user: {newUser});
});

then you'll have another backend route which verifies the validity of the link by which ever criteria you decide.

Upvotes: 2

Ujjual
Ujjual

Reputation: 998

Outside router function

function validateEmail(email) {

 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

Inside router function

if (validateEmail(req.body.email)) {
   console.log('valid email');
  } else {
   console.log('invalid email');
  }

You can use alternative libraries like express validator that do the same job.

Upvotes: 1

Related Questions