This feels a bit embarrassing since I've been a Linux user for 10+ years. However, I've ran into a problem which I can't understand.
Lets assume I want to expose an environment variable, SECRET, that I can access from node with
process.env.SECRET
I would just write this is the same terminal that I start the app with
# Linux bash
$ export SECRET=Ultr4Secr3t
$ echo $SECRET
$ > Ultr4Secr3t
Then run node app nodejs app.js
// app.js
console.log(process.env.SECRET)
> Ultr4Secr3t
Everything is fine!
But I would really like to have an .env file in the repo instead.
Example .env file
SECRET=Ultr4Secr3t
# Linux bash
$ . .env # On Mac we had to do ". ./.env"
$ echo $SECRET
$ Ultr4Secr3t
Now the weird thing happens when I run the app
Then run node app nodejs app.js
// app.js
console.log(process.env.SECRET)
> undefined
Why is it undefined? I'd rather not have to use the dotenv package.
Some solutions posted before, are working, but you normally don't want to expose/polute the CLI history with some of the variables. Therefore, an .env file with restricted permissions might be one way to solve the problem.
To make all .env variables available inside node app.js, instead of:
. .env # or
source .env
use this:
export $(cat .env | xargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With