NodeJS app on Heroku can't access Mailgun API key

I’m stuck with a problem in my Node.js app on Heroku. The Mailgun API key isn’t being recognized even though I’ve set up the environment variables and added dotenv to my code. Here’s what I’ve done:

In my server.js:

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const pug = require('pug');
const app = express();

// Email service setup
const emailApiKey = process.env.EMAIL_SERVICE_API_KEY;
const emailDomain = process.env.EMAIL_DOMAIN;
const emailClient = require('email-service-js')({apiKey: emailApiKey, domain: emailDomain});

// App config
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.set('view engine', 'pug');

My .env file has the right credentials. But when I check the Heroku logs, I see an error saying the API key isn’t defined. Any ideas on what might be causing this? I’m really stuck and could use some help!

I encountered a similar issue when deploying my Node.js app on Heroku. In my experience, the problem was not with the code but with how Heroku handles environment variables. Unlike local development where the .env file works as expected, Heroku requires you to manually set these variables through its dashboard. I resolved it by going to my app’s settings, revealing the configuration variables, and entering the EMAIL_SERVICE_API_KEY and EMAIL_DOMAIN values there. After redeploying and restarting the dynos, the API key was recognized correctly. Also, ensure that your .env file is not causing conflicts by being committed inadvertently.

From what you’ve described, it seems the issue lies in how Heroku handles environment variables. Unlike local development, Heroku doesn’t automatically read from a .env file. You need to manually set these variables in the Heroku dashboard.

To resolve the issue, log into your Heroku dashboard, navigate to your app’s settings, and locate the ‘Config Vars’ section. There, add your EMAIL_SERVICE_API_KEY and EMAIL_DOMAIN variables. After updating these variables, redeploy your app and restart the dynos. Additionally, ensure that your .env file has not been accidentally committed to your repository to avoid any conflicts.

hey, i had this issue too. make sure ur not committing the .env file to git. heroku doesnt read it. u gotta set the vars in heroku dashboard. go to settings, find config vars, add ur EMAIL_SERVICE_API_KEY and EMAIL_DOMAIN there. then redeploy. that shud fix it