Reputation: 2029
I have just come across the idea of using environment variables in a front end React codebase I am looking at. When I run the React app locally I can see that when I console.log process.env.VALUE, then this value will be logged out in the browser console.
However if I console.log(process.env)
I only see an empty object. I've seen other answers for this on Stack Overflow but I couldn't understand them. It doesn't make sense to me how I can access the properties on process.env but I can't log process.env out. Isn't it just an object which contains all the environment variables that are set?
Upvotes: 2
Views: 3710
Reputation: 2863
The reason for that is because React naturally uses webpack.DefinePlugin
when you are building your production build. That library basically makes your process.env
variable to essentially be 'placeholders' - meaning that all of the values are replaced during build time. That's why process.env
returns {}
, while process.env.NODE_ENV
returns the correct one for example.
Slightly off-topic, but in Next.js (a React framework), all environment variables are also replaced during build time (for security purposes). That means that process.env
is not a normal JavaScript object in Next.js. Internally, they use webpack.DefinePlugin
as well.
As an addition for the answer, the browser does not have access to process.env
. React is basically compiled to HTML/CSS/JS - that means the application is just a static site. process.env
is a Node.js thing.
Example:
FOO
with value BAR
in whatever environment you desire when you build your app.webpack.DefinePlugin
to transform your FOO
into process.env.FOO
. It is literally process.env.FOO
. The compiler does not create an object called process.env
with an attribute FOO
. Literally, the process.env.FOO
is attached in the window
object of your app.process.env.FOO
, and it does exist in your application during runtime.process.env
object (it is not and have never been an object) since the beginning of the compilation, and that's why it returns an empty object -- it simply is never an object to begin with for the reasons that I have explained in the above.References:
Upvotes: 2