Can't read my environment variable in my Node.js app
Solution 1
You need to export
shell variables in order to make them available to processes you execute in your shell.
Compare the output of this command:
FOO=bar; bash -c 'echo $FOO'
with the output of this:
export FOO=bar; bash -c 'echo $FOO'
Solution 2
I found my way here from something really silly.
I had just added the new exported variables, but my node process still wasn't seeing them. Then I realized it wasn't enough to restart the node process—I had to open a new terminal (ie. bash instance) too. Once I did this, it worked fine :)
Solution 3
If you are using dotenv
make sure to configure before you access the variables in your environment. The order of your code is mattered in js.
Chev
I'm a passionate developer and I love to learn. I also love to share my knowledge with others. Both of those are the primary reasons why I'm here on Stack Overflow :)
Updated on October 11, 2021Comments
-
Chev over 2 years
I am on Ubuntu 12.04 and I'm just learning about environment variables. I am trying to read a custom variable from within my application but it always shows up as
undefined
. Here is the code of my test app:// app.js console.log('Value: ' + process.env.NODE_ENV);
If I run the following commands you will see that the variable has a value:
$ NODE_ENV=production $ echo $NODE_ENV production
I can
echo $NODE_ENV
all day and it will continue to show me "production", but when I doprocess.env.NODE_ENV
in my Node application it always displays "undefined".$ node app.js Value: undefined
Here is the odd part though, if I display another environment variable that I know already exists, say
process.env.PATH
, then it works.$ node app.js Value: /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
Another quirk is that the command
printenv list
doesn't appear to contain my custom variableNODE_ENV
despite the fact thatecho $NODE_ENV
shows me the correct value.printenv NODE_ENV
shows nothing as well, butprintenv PATH
shows the proper value just as it did when I accessedPATH
in my node application. -
user2768479 about 4 yearsThank you, it's working! I got really frustrated why it was 'undefined', all I had to do was exit bash instance and open a new one.
-
vagifm about 3 yearsThe strange this is that even if I can see variable value using
echo $FOO
I can't see it usingprocess.env.FOO
anyway...