16

I'm trying to create some envrioment variables but when I create the file and run the server the seem to be undefined. I'm using nodemon. I have restarted my server and no luck.

UPDATED

.env

MONGO_ATLAS_PW = "xxxx";
JWT_KEY = "secret_this_should_be_longer";

package.json

...
  "scripts": {
    ...
    "start:server": "nodemon ./server/server.js"
  }

app.js

 require('dotenv').config();
 ...
 console.log(process.env.JWT_KEY); //undefined 
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100

4 Answers4

15

I believe the nodemon.json file is only for setting nodemon specific configuration. If you look at the nodemon docs for a sample nodemon.json file, the only env variable they mention setting is NODE_ENV.

Have you considered putting these environment variables for your app in a .env file instead? There is a package called dotenv that is helpful for managing env variables in Node.

First, install dotenv using the command npm install dotenv

Then, create a file called .env in the root directory with the following:

MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret_this_should_be_longer

Finally, inside your app.js file after your imports add the following line:

require('dotenv').config()
Kris Burke
  • 401
  • 5
  • 8
  • What does your directory structure look like? Where is .env located in your project and where is app.js? .env should be in the root directory. Also, you haven't exactly copied the syntax for the .env file -- it should not be JavaScript syntax (though this wouldn't cause the variable to be undefined). – Kris Burke Jun 30 '19 at 21:40
10

I believe you're referring to the dotenv package. To configure it, first create a file called .env with your keys and values stored like so:

MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret_this_should_be_longer

Then, in your server.js, add this near the top:

require("dotenv").config();

Then the process.env variable will be an object containing the values in .env.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • See the syntax - it needs to be that *exactly*. Try copy/pasting the `.env` in my answer into your file and see if that works @PatricioVargas. – Jack Bashford Jun 30 '19 at 21:57
4

This needed to be in the root directory of my project.

nodemon.json

{
  "env": {
    "MONGO_ATLAS_PW": "xxxx",
    "JWT_KEY": "secret_this_should_be_longer"
  }
}
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
2

The env variable do not contain the trailing white spaces and also remove the quotes

MONGO_ATLAS_PW = "xxxx"; 
JWT_KEY = "secret_this_should_be_longer";

to

MONGO_ATLAS_PW=xxxx 
JWT_KEY=secret_this_should_be_longer

and restart the server

or you can also try using the nodemon.json - create a new file called nodemon.json in your root directory

{
    "env": {
        "MONGO_ATLAS_PW" : "xxxx",
        "JWT_KEY" : "secret_this_should_be_longer"
    }
}

and restart the server

for accessing the variable

process.env.MONGO_ATLAS_PW 
process.env.JWT_KEY
gopinath krm
  • 69
  • 1
  • 8