javascriptnode.jssendgrid

NodeJS Sendgrid 401 unauthorized


After registering a user in my node express server, I would like to send a verification email. If the user is created I use this function to send the email:

import dotenv from 'dotenv'
import sgMail from '@sendgrid/mail'

sgMail.setApiKey(process.env.SENDGRID_API_KEY)

const sendEmail = (to, token) => {
    const msg = {
        to,
        from: process.env.SENDGRID_SENDER,
        subject: 'Email Verification',
        text: `Please click the following link: http://localhost:5000/${token}`
    }
    
    sgMail
     .send(msg)
     .then((response) => {
        console.log(response[0].statusCode)
        console.log(response[0].headers)
    })
     .catch((error) => {
        console.error(error)
    })
}

export { sendEmail }

It is called here:

const registerUser = asyncHandler(async (req, res) => {
  const { name, email, password } = req.body

  const userExists = await User.findOne({ email })

  if (userExists) {
    res.status(400)
    throw new Error('User already exists')
  }

  const user = await User.create({
    name,
    email,
    password
  })

  if (user) {
    sendEmail(user.email, user.token) //HERE
    res.status(201).json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      isVerified: user.isVerified,
      token: generateToken(user._id),
    })
  } else {
    res.status(400)
    throw new Error('Invalid user data')
  }
})

The problem I am having is I get a ResponseError Unauthorized (code 401) when the request is made. The user does get created in the system. On my sendgrid account, I have verified the sender email with full access and I am storing my API Key in my .env file.

I have used 10 minute mail accounts to test this and real email accounts.


Solution

  • If the 401 status is coming from sendgrid then probably your env variable is not resolved. try this line after you import the dotenv package

    dotenv.config()
    

    If it didn't work, try to console.log the process.env.SENDGRID_API_KEY before u use it to make sure it's there.