64

I'm using environment variables on my mac to store some sensitive credentials, and trying to access them through Node. I added them into my environment profile with

export VARIABLE_NAME=mySensitiveInfo

When I use echo $VARIABLE_NAME I receive the correct output (my sensitive info).

However, when I am trying to access this same variable in Node with process.env.VARIABLE_NAME and try to print it out on the console, I get an undefined.

Other environment variables appear to be okay though. For example, when I console.log(process.env.FACEBOOK_CALLBACK_URL), it prints the correct value to my console. I added FACEBOOK_CALLBACK_URL a few days ago.

Do I have to restart my machine or something? Does it take a certain time before environment variables become available in Node? The closest answer I've seen on SO is this post, but nobody was able to figure out why it was happening.

Yu Chen
  • 6,540
  • 6
  • 51
  • 86

9 Answers9

58

nodemon.json file is only for setting nodemon specific configuration So for create custom environment variables we can use dotenv package

First , Install dotenv package

npm install dotenv --save

after that create .env file in root and include environment variables as bellows

MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret

Finally, inside your app.js file insert following after your imports.

require('dotenv').config()

Then you can use environment varibale like this

process.env.MONGO_ATLAS_PW
process.env.JWT_KEY
Sumith Ekanayake
  • 1,741
  • 17
  • 13
  • 3
    this straightforwardly worked for me. thanks. – Heila Al-Mogren Jan 29 '22 at 02:06
  • 2
    Note:- By "after that create .env file in root" OP means that you have to create the .env file in the same folder where you have your package.json. This worked for me :) – catGPT Feb 05 '22 at 20:13
  • 1
    Note: when sending .env files over discord the "." drops off leaving an "env" file. Make sure there is a dot at the start! Also I wouldn't recommend sending over discord anyway. try usb or other secure methods – billy bud Feb 17 '22 at 06:46
  • Well, absolutely thanks for the exact answer. works like a charm – Aman Jha Aug 13 '23 at 15:02
49

process.env.VARIABLE_NAME returns undefined because the Node.js execution environment does not know the newly added VARIABLE_NAME yet. To fix the issue, the Node.js execution environment (e.g. IDE) need to restart.

The following steps can be used to reproduce this issue:

  1. Open IDE such as WebStorm and write a simple Node.js program: console.log(process.env.VARIABLE_NAME). It will print undefined as expected, as VARIABLE_NAME is not defined yet. Keep the IDE running, don't close it.
  2. Open environment profile such as .bash_profile and add export VARIABLE_NAME=mySensitiveInfo in it.
  3. Open system console and run source .bash_profile, so that the above export statement will be executed. From now on, whenever system console is opened, VARIABLE_NAME environment variable exists.
  4. In system console, execute the Node.js program in step 1, it will print mySensitiveInfo.
  5. Switch to IDE and execute Node.js program, it will print undefined.
  6. Restart the IDE and execute Node.js program, this time, it will print mySensitiveInfo
shaochuancs
  • 15,342
  • 3
  • 54
  • 62
11

For everyone who might have this issue in the future and none of the solutions above are working, it may also be because you're running the node <filename>.js in a subfolder or subdirectory, and since your .env file is in the root folder, processs.env.<variable> will always return undefined.

A simple way to check is to try the following code

const test = require('dotenv').config()
console.log(test)

In the console we get the following error

{   error: Error: ENOENT: no such file or directory, open 'C:\Users\vxcbv\Desktop\voisascript-auth\model\.env'
      at Object.openSync (node:fs:585:3)
      at Object.readFileSync (node:fs:453:35)
      at Object.config (C:\Users\vxcbv\Desktop\voisascript-auth\node_modules\dotenv\lib\main.js:72:42)
      at Object.<anonymous> (C:\Users\vxcbv\Desktop\voisascript-auth\model\db.js:1:32)
      at Module._compile (node:internal/modules/cjs/loader:1105:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
      at Module.load (node:internal/modules/cjs/loader:981:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
      at node:internal/main/run_main_module:17:47 {
    errno: -4058,
    syscall: 'open',
    code: 'ENOENT',
    path: 'C:\\Users\\vxcbv\\Desktop\\voisascript-auth\\model\\.env'   } }

Emphasis on the Error: ENOENT: no such file or directory, open. To solve this, just navigate back to the root and run the file from there, but specify the full path of the file from the root, like node /<subfolder>/<file.js>

Jriffs
  • 125
  • 1
  • 8
4

I got a problem just now , and I use this solved it in webpack config

const plugins = [
    new webpack.NoEmitOnErrorsPlugin(),
    // after compile global will defined `process.env` this Object
    new webpack.DefinePlugin({
      BUILD_AT : Date.now().toString(32),
      DEBUG: process.env.NODE_ENV !== 'production',
          'process.env': {
              'NODE_ENV': JSON.stringify(process.env.NODE_ENV || "development"),
              'VARIABLE_NAME': JSON.stringify(process.env.VARIABLE_NAME)
     }
   })
]
kingzez
  • 41
  • 3
4

please check the dir of .env file, If it is in same file as your app.js or (abc.js) than move .env to one level up

sunilsalat
  • 154
  • 1
  • 11
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 08 '21 at 17:33
  • This was my exact problem. I had both the .env and my server root file in the same directory. Moved the .env file up to the parent directory and problem solved. Thank you! – Hard_Whey Aug 13 '23 at 01:03
4

For anyone stuck in React.

This article helped me to understand .env in React:

The variable must have a prefix of ‘‘REACT_APP_’’ otherwise the variable will not work properly.

In your .env file, it should look something like this:

REACT_APP_YOUR_VARIABLE_NAME=SOMETHING

And NOT this (what I had and gave undefined):

MY_VARIABLE_NAME=SOMETHING
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Thank you! I have a vue app in which the `VUE_APP_SOMEVARIABLE` variable got through, but the rest was omitted. I had completely forgotten about the `VUE_APP_` prefix requirement. – Kevin Driessen Apr 24 '23 at 18:14
2

I had the same issue. In my case the env file and db.js was inside a subfolder configs.

So, in index/server.js , while importing the dotven , I used

require('dotenv').config({path: './configs/.env'});

This way my env variables were being accessed.

Hope this example of mine helps you!

Suman Roy
  • 21
  • 4
1

Close the code Runner Or Ide environment once and reopen it. If you use VS code, close it completely. (Or CMD or Power Shell or ...)

Stefano Sansone
  • 2,377
  • 7
  • 20
  • 39
0

While accessing .env variables with dotenv.config(), The function which was accessing them was called before the dotenv.config().

Before ❌

const dotenv = require('dotenv');
authController.insertAdmin();
dotenv.config();

After ✅

const dotenv = require('dotenv');
dotenv.config();
authController.insertAdmin();
Gurkirat S
  • 41
  • 4