javascriptnode.jstwilio-api

SendGrid API Key evaluating to "undefined"?


I'm following the integration guide for Node.js with sendgrid. My environment variable folder looks like :

[removed api key]

And my 'index.js' looks like :

console.log(process.env.SENDGRID_API_KEY)
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'evan.dickinson.flinn@gmail.com',
  from: 'improvedpts@improvedpts.com', // Use the email address or domain you verified above
  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(() => {}, error => {
    console.error(error);

    if (error.response) {
      console.error(error.response.body)
    }
  });

I also have a package.json file, but besides that those are the only three files in my folder. The error message I keep getting is:

API key does not start with "SG.".

And when I checked with console.log, my API key was apparently undefined? Can someone explain this to me? I've been scouring the internet but I haven't figured it out.

I want the API to send a email. I've tried importing 'dotenv', but that did not work so I went back to what the tutorial said. None of the online solutions have worked.


Solution

  • You can set up your Nodejs project with "dotenv" library to create and access environment variables.

    1. Install the lib using npm i dotenv
    2. Create a file in the root project with the name .env
    3. Put your variables on the file
    SENDGRID_API_KEY='SG.XXXXX'
    
    1. Now you can get this variable easily in your code
    
    const { config } = require('dotenv');
    config();
    
    console.log(process.env.SENDGRID_API_KEY)
    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: 'evan.dickinson.flinn@gmail.com',
      from: 'improvedpts@improvedpts.com', // Use the email address or domain you verified above
      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(() => {}, error => {
        console.error(error);
    
        if (error.response) {
          console.error(error.response.body)
        }
      });
    
    

    I hope that it can help you :D.

    Don't put API keys in questions.