account-created-email-confirmation-nodejs-react-sendgrid

// controller
export const createUser = async (req, res) => {
  console.log("CREATE USER => ", req.body);
  try {
    const { name, email, password, role, checked, website } = req.body;
    if (!name) {
      return res.json({
        error: "Name is required",
      });
    }
    if (!email) {
      return res.json({
        error: "Email is required",
      });
    }
    if (!password || password.length < 6) {
      return res.json({
        error: "Password is required and should be 6 characters long",
      });
    }
    const exist = await User.findOne({ email });
    if (exist) {
      return res.json({
        error: "Email is taken",
      });
    }
    // hash password
    const hashedPassword = await hashPassword(password);

    // if checked, send email with login details
    if (checked) {
      // prepare email
      const emailData = {
        from: process.env.EMAIL_FROM,
        to: email,
        subject: "Account created",
        html: `
          <h2>Hi ${name},</h2>
          <p>Your CMS account has been created sucessfully</p>
          <h3>Your login details</h3>
          <h4 style="color:red;">Email: ${email}</h4>
          <h4 style="color:red;">Password: ${password}</h4>
          <p>We recommend you to change your password after login.</p>
        `,
      };

      try {
        const data = await sgMail.send(emailData);
        // console.log(data);
      } catch (err) {
        console.log(err);
      }
    }

    try {
      const user = await new User({
        name,
        email,
        password: hashedPassword,
        role,
        website,
      }).save();
      const { password, ...rest } = user._doc;
      return res.json(rest);
    } catch (err) {
      console.log(err);
    }
  } catch (err) {
    console.log(err);
  }
};