BranOIE
BranOIE

Reputation: 430

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.

Upvotes: 2

Views: 8909

Answers (4)

Nevada
Nevada

Reputation: 173

https://app.sendgrid.com/guide/integrate/langs/nodejs

require('dotenv').config();
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
       
const msg = {
  to: '[email protected]', // Change to your recipient
  from: '[email protected]', // Change to your verified sender
  subject: 'Sending with SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
}
sgMail
  .send(msg)
  .then(() => {
    console.log('Email sent')
  })
  .catch((error) => {
    console.error(error)
  })

Upvotes: 0

Michael
Michael

Reputation: 1183

I had the same issue. It was misleading because their SENDGRID_API_KEY matches up with the nomenclature of the smaller string. I figured the longer one was the secret. Use the longer string for the key. That one worked for me.

Upvotes: 1

evaawan
evaawan

Reputation: 11

import sgMail from '@sendgrid/mail' and set your api key sgMail.setApiKey('your api key is here')

Upvotes: 0

MoSwilam
MoSwilam

Reputation: 944

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.

Upvotes: 2

Related Questions