Search code examples
node.jssmtpmailgunapi-key

Unable to access mailgun credentials with process.env in a node app


I have a node app, and in the .env file, I've stored the credentials- api_key and domain. Now, I can't access the credentials anywhere in my application, let alone the part where I need them. I tried process.env.api_key and process.env.domain, and got the following error resulting in my app getting crashed even before compiling.

Error: apiKey value must be defined!

Here's my auth object:

const auth = {
  auth: {
    api_key: process.env.api_key,
    domain: process.env.domain  
  }
}

.env

api_key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
domain="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.org"

When I try to use the credentials directly, everything works fine, but doing that is not a good idea, I suppose.


Solution

  • Having a .env alone won't do anything, since Node.js doesn't handle that file. You need to load it, you may want to use: dotenv package for that.

    require('dotenv').config(); // very beginning of the file
    
    // process.env.api_key will have a value now.
    // rest of your code.
    
    

    dotenv require must be before any other require.