How to send a link in the sendgrid email message body?

Viewed 605

I am implementing password reset functionality in a MERN app. Whenever a user enters the email for which they want to reset the password and clicks on the "Send Password Link" button, a POST request is made to "/account/forgot". In the route handler function, I want to send them a password reset link in the body of the email message sent through sendgrid. How can I achieve this?

Code snippet is given below:

server/routes/passwordResetRoutes

const express = require("express");
const crypto = require("crypto");
const asyncHandler = require("express-async-handler");
const User = require("../models/userModel");

// const sgMail = require("@sendgrid/mail");
// sgMail.setApiKey(process.env.SENDGRID_API_KEY);


const router = express.Router();

router.post(
  "/forgot",
  asyncHandler(async (req, res, next) => {
    const user = await User.findOne({ email: req.body.email });

    if (user) {
      user.passwordResetToken = crypto.randomBytes(20).toString("hex");
      user.passwordResetExpires = Date.now() + 3600000;
      await user.save();

      res.json({
        message: "You have been emailed a password reset link",
      });

      // I WANT TO SEND THE passwordResetUrl in the email message
      const passwordResetUrl = `http://${req.headers.host}/password/reset/${user.passwordResetToken}`;

      const msg = {
        to: user.email,
        from: "rawgrittt@gmail.com",
        subject: "PASSWORD RESET LINK",
        html:
          "<p>Click on the following link to reset your password.</p>",
      }
(async () => {
        try {
          await sgMail.send(msg);
        } catch (error) {
          console.error(error);

          if (error.response) {
            console.error(error.response.body);
          }
        }
      })();
    } else {
      const err = new Error("No account with that email exists");
      err.status = 404;
      next(err);
    }
  })
);

module.exports = router;

When I send the link in the message body as shown below and click on the link (received in my mailbox), I get an error as follows:

      const msg = {
        to: "pgcim14.hemant@spjimr.org",
        from: "rawgrittt@gmail.com",
        subject: "PASSWORD RESET LINK",
        html:
          "<p>Click on this <a href=`http://${req.headers.host}/password/reset/${user.passwordResetToken}`>link</a> to reset your password.</p>",
      };

enter image description here

1 Answers

Try adding

<a href="resetPasswordLink">Click on the following link to reset your password</a>

in html property of msg object.

Related