Skip to content
← Back to Community
Can someone explain me why .env variables are undefined when I print them?
Profile icon
misterybodon

Set up

npm i dotenv

In my javascript file

require("dotenv").config() console.log(process.env.MYVAR)

In my .env file

MYVAR=A

logs undefined. I just can't make sense of REPL

Voters
Profile icon
misterybodon
Comments
hotnewtop
Profile icon
TheBeast941

Just make a .replit file and add the run command into it, like so:
run = ""
After wasting hours trying to fix the same problem yesterday, that seemed to do the trick for me

Profile icon
Squirrel777

And you can just enter node index.js in the shell if you want

Profile icon
misterybodon

what's the point of that comment. yes, that's the only thing the shell does....
@Squirrel777

Profile icon
Coder100

well I would just like to say we already have that configured. You don't even need dotenv anymore!

console.log(process.env.MYVAR)

the reason is that dotenv can't actually read your .env files.

Profile icon
misterybodon

Hi. It would be nice to know how that is implemented. Also, think of it this way: I want to understand, don't want that level of abstraction that makes you useless. Why? this won't work if i implement locally, neither my local would work here. BUT i appreaciate the comment. @Coder100

Profile icon
Squirrel777

You dont need to require dotenv. Just like this:
.env:

MYVAR=A

index.js:

console.log(process.env.MYVAR)
Profile icon
SixBeeps

You shouldn't need the dotenv package.
I created a Repl just now and pasted what you had (minus the require() call) in their respective files, and it worked.

Profile icon
misterybodon

The problem is the damn run button + something that REPL does in the background. Instead of running node server.js press Run. This doesn't make sense to me.
@SixBeeps