0

I'm following the setup guide for Sendgrid on Node.js (https://app.sendgrid.com/guide/integrate/langs/nodejs), but I keep getting an API key error.

This is my code:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Sending with Twilio 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('send mail success'))
  .catch(console.log);

My API key is setup correctly in my .env file:

SENDGRID_API_KEY=SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o

This is the error message I'm getting:

API key does not start with "SG.".
ResponseError: Unauthorized
    at BE-KeyCon/node_modules/@sendgrid/client/src/classes/client.js:133:29
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: 401,
  response: {
    headers: {
      server: 'nginx',
      date: 'Fri, 12 Jun 2020 21:31:08 GMT',
      'content-type': 'application/json',
      'content-length': '116',
      connection: 'close',
      'access-control-allow-origin': 'https://sendgrid.api-docs.io',
      'access-control-allow-methods': 'POST',
      'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
      'access-control-max-age': '600',
      'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html'
    },
    body: { errors: [Array] }
  }
}

If I set the API key as a string, like so:

sgMail.setApiKey('SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o')

Then it works. But obviously I can't leave it like this for security reasons. Any idea why it's behaving this way and how I might fix it?

Rasha
  • 23
  • 1
  • 6
  • What does `process.env.SENDGRID_API_KEY` evaluate to? – maiorano84 Jun 12 '20 at 21:46
  • undefined! I tried all of my environement variables and they all returned undefined. That's weird... The .env file is in my root directory and I am requiring the dotenv library. – Rasha Jun 12 '20 at 22:30
  • If I run `node -r dotenv/config util/sendgrid.js` then it evaluates correctly to the api key. – Rasha Jun 12 '20 at 22:40
  • How early are you running `require('dotenv').config()`? Are you making sure it's happening before your call to `process.env.SENDGRID_API_KEY`? – maiorano84 Jun 13 '20 at 01:26
  • It's in my index.js file, where I initialize the server: ```require('dotenv').config();``` ```const server = express();``` – Rasha Jun 14 '20 at 15:20
  • And is your Sendgrid script also loaded somewhere through an `import` or `require` statement that your Express process knows about? Or is it a separate script? The only thing I can think of is that if you're running Sendgrid as a separate process from Express, then it's operating on another thread that wouldn't have access to what Dotenv is providing. If so, you may need to also drop another `require('dotenv').config();` call to your Sendgrid entry script. – maiorano84 Jun 14 '20 at 16:11
  • Good point, it was not! However, I added `require('dotenv').config();` to the top of my sendgrid.j file, and I still get the exact same error. – Rasha Jun 15 '20 at 17:37
  • Hmmmm. I'm fresh out of ideas. Double check the name and location of your .env file, and make sure the contents of your file match the format expected of environment variables. [See the answers here](https://stackoverflow.com/questions/26973484/how-do-i-setup-the-dotenv-file-in-node-js) for more ideas and debugging help. – maiorano84 Jun 15 '20 at 19:45
  • 1
    I just ran a `console.log(require('dotenv').config());`, and turned out it couldn't find the .env file. I have two main folders in my project, one for frontend and one for backend, and I had the .env file in the BE folder thinking that was my root. I had to move it out to the actual root, and now it's working fine. Thanks everyone! – Rasha Jun 16 '20 at 02:52
  • Glad you got it all figured out! Feel free to drop in an answer and accept it in case others stumble upon this problem. – maiorano84 Jun 16 '20 at 02:57

5 Answers5

0

The issue was the location of the .env file. I had my backend folder nested inside another folder, so I had to move it out to the actual root.

Rasha
  • 23
  • 1
  • 6
0

install dotenv package from npm and use this piece of code to make sure that it takes the .env file:

if (process.env.NODE_ENV !== 'production') require('dotenv').config();

console log the process.env.SENDGRID_API_KEY to check whether the program is getting the api key.

Mabedan
  • 857
  • 8
  • 30
0

Used to encounter this problem but simply updating the files didn't quite work out in my case.

Here is how I solve it eventually:
Include require('dotenv').config in the file that integrates the SendGrid API.
Go to Heroku app. Click on the "Settings" page and look for "Config Vars". "Find 'Config Vars' in the 'Settings' page"

Press the "Reveal the Config" button and add another key pair.
Set "SENDGRID_API_KEY" as the KEY & set your SG.xxxxxxYourAPIxxx as the value. Add the key pair and rerun the app.

0

Single quote the value in your .env file:

SENDGRID_API_KEY='SG.oqKbQHcNxxxxxxxxxxxxxkY5B4o'
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
Todd Eagle
  • 13
  • 3
0

I had the same issue I realized my .env.local file was named wrong by missing . in the beginning so make sure your file name is correct and if it still dont work try installing dot dev by this commandnpm install dotenv