Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running an .env file and access them from Node

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.

like image 973
petur Avatar asked Nov 16 '25 15:11

petur


1 Answers

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)
like image 79
cephuo Avatar answered Nov 18 '25 06:11

cephuo