Reputation: 4668
create-react-app is supposed to inject your .env
variables into your React app. I have used the REACT_APP_
prefix with my variables in my .env
and .env.development
.
However, when debugging the code I've found that process
itself is undefined. So when trying to access an environment variable with process.env.REACT_APP_SOMETHING_URL
, the root process
variable is undefined.
Upvotes: 10
Views: 14129
Reputation: 8418
For those who are using docusaurus
and getting this issue while they trying to access env variable in there react component, you fix this issue by
installing docusaurus-plugin-dotenv
and add this configuration to your daucusaurus.config.js
file
plugins:
[
...
[
'docusaurus-plugin-dotenv',
{
path: "./.env",
systemvars: true,
}
]
....
]
Now you can access the env variable in your application without a problem
...
const DOMAIN = process.env.REACT_APP_AUTH0_DOMAIN;
....
Upvotes: 1
Reputation: 41
The react-app-env package suggested on another post on this page is deprecated, as described in its repo: https://github.com/tuchk4/react-app-env
I recommend using dotenv instead.
Upvotes: 0
Reputation:
well let me begin by saying process
is an eventEmitter what lives in the nodejs world if you log it in a browser, no matter if it is angular, CRA, Vue, jquery all of them will print undefined because in the context of a browser it does not exist.
now on a CRA you is able to use process.env.YOW_VAR
, basically bcuz CRA creates an Obj call process.env
that is the reason behind why you need to add a prefix to them env vars which I think is REACT_APP.
const YOW_VARS = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[ key ] = process.env[ key ];
return env;
},
{
NODE_ENV: process.env.NODE_ENV || 'development',
}
);
const s = {
'process.env': Object.keys(YOW_VARS).reduce((env, key) => {
env[ key ] = JSON.stringify(YOW_VARS[ key ]);
return env;
}, {}),
};
more or less they have something like that
Upvotes: 0
Reputation: 51
$ yarn add --dev react-app-env
or
$ npm install react-app-env --save-dev
Upvotes: 5
Reputation: 4668
So at the time I misunderstood how process.env
works in create-react-app
. I expected this to be available at runtime. However, because React is a frontend library and process
is a Node backend entity you cannot directly access process.env
while executing code in the browser.
This makes sense because in-browser executed Javascript doesn't know about Node; therefore, process.env
isn't available.
What happens instead is that during a webpack build, webpack will inject the corresponding environment variables into your frontend asset code. So if you have a production .env
file, those variables are provided during the build.
Upvotes: 14