Node js, process.env not reading enviroment variables
Asked Answered
L

1

8

Even though I can see that an environment variable was created on windows, process.env always returns undefined. I did set all my variables, and when I check them manually, they all appear in the prompt, but the process.env always stays undefined.

P.S. I don't have admin privileges, except when I check the process.env.NODE_ENV.

enter image description here

Leasia answered 23/5, 2021 at 15:48 Comment(0)
L
9

You need to read them first.

Use the dotenv package.

Install:

npm install dotenv

In you project code:

require('dotenv').config()

Add .env file in you project folder like this:

DB_HOST=localhost
DB_USER=root
DB_PASS=*be sure there is strong pass*

Try get env var like this:

const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

By the way, it is not enough to write them to a file in order for them to become environment variables. You need to write them in the console and then they become environment variables. The .env file method lets you write them to a file and read them from there through the donenv package.

Landes answered 23/5, 2021 at 16:45 Comment(3)
In fact, I'm not sure why it doesn't work to read environment variables that have already been created. But in this case, just use the .env file.Landes
Well, i am embarrassed to say that it was all a typo, you see I am dyslexic and I wrote EVN instead of ENV. That's why i couldn't figure out the issue i keep staring at the problem but i didn't realize that i made a typo. I did set the variables properly I even check in the H_KEY_LOCAL_MACHINE. thank you for your quick answer,Leasia
@DardanGjoka Interesting. Well, if you think about it that way, I'm dyslexic, too, for I can be inattentive sometimes and I can get things mixed up that way, too. Have a good day!Landes

© 2022 - 2025 — McMap. All rights reserved.