Search code examples
environment-variablessendgridenvironmentapi-keydotenv

Getting the API_KEY from SendGrid .env file (Node.js)


I'm using SendGrid(Node.js) for one of my personal projects. I followed the integration guide to set up my API KEY .env file as following:

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

My question is... Every time before running the backend locally, I have to first run

source ./sendgrid.env

In order for the process.env.YOUR_API_KEY be acknowledged where the key is. But after renamed the sendgrid.env file to just .env, I don't have to run source anymore.

This is how I call the API KEY

require('dotenv').config()

const { validationResult } = require('express-validator')
const Appointment = require('../models/Appointment')
const User = require('../models/User')
const sgMail = require('@sendgrid/mail')

sgMail.setApiKey(process.env.SENDGRID_API_KEY)

PS. I have set the dotenv config at the top of the file but still getting undefined until I changed the file name.

Does anyone know the reason or the logic behind this?? Thank you :)


Solution

  • If I am understanding it well enough. You have to change it to .env because by default require('dotenv').config() point to .env because the parenthesis of config are empty. To follow the sendgrid way by calling your file sendgrid.env you would have to require('dotenv').config(sendgrid.env) and maybe, just require('dotenv').config(sendgrid) would be enough. Got to try it to know for sure. But at least from my understanding this is your answer.