The issue with process.env
variable being empty in browser is because browser doesn’t have real access to the process
of the node.js
. It’s run inside the browser though.
Usage of process.env.ANYTHING
is usually achieved by plugins like https://webpack.js.org/plugins/define-plugin/ which just simply replace
any occurrence of process.env.ANYTINHG
with env variable during BUILD time. It really does just simple str.replace(/process.env.ANYTING/value/)
this needs to be done during build time as once you output dist bundle.js
you don’t have access to the ENV
variables.
Replacing during build time
Therefore you need to be sure that when you are producing production build e.g with yarn build
you are using webpack.DefinePlugin
and replacing those process.env
calls with current ENV values. They can’t be injected in runtime.
Injecting in runtime
When you need to access env variables in runtime it’s basically impossible in JavaScript in browser. There are some sort of hacks for example for NGINX which can serialize current env variables to the window.ENV
variable and in your app you will not use process.env
but window.ENV
. So you need to either have ENV variables available while you are building the application or build mechanism which will dynamically output current ENV as json to window and access with react. If you are using docker
it can be done with ENTRYPOINT
otherwise you need some bash script which will always output current ENV variables as JSON
to the index.html
of your app