Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS environment variables undefined

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 
like image 620
Patricio Vargas Avatar asked Jun 29 '19 22:06

Patricio Vargas


People also ask

Do we need to set environment variables for node JS?

You really do not need to set up your own environment to start learning Node. js. Reason is very simple, we already have set up Node.

Why is process env port undefined?

When trying to access process. env. PORT it'll return undefined if you've not setup that environment variable in the shell that you're trying to run your system. You can set the environment variable up before you run node app.

What is .env file in node JS?

The dotenv package for handling environment variables is the most popular option in the Node. js community. You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables.


Video Answer


3 Answers

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()
like image 76
Kris Burke Avatar answered Sep 20 '22 05:09

Kris Burke


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.

like image 33
Jack Bashford Avatar answered Sep 20 '22 05:09

Jack Bashford


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"
  }
}
like image 43
Patricio Vargas Avatar answered Sep 21 '22 05:09

Patricio Vargas