Ask coding questions

← Back to all posts
Can someone explain me why .env variables are undefined when I print them?
misterybodon (1)

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

Comments
hotnewtop
TheBeast941 (0)

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

Squirrel777 (138)

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

misterybodon (1)

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

Coder100 (17045)

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.

misterybodon (1)

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

Squirrel777 (138)

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

MYVAR=A

index.js:

console.log(process.env.MYVAR)
SixBeeps (5055)

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.

misterybodon (1)

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