Reputation: 103
I am trying to access an environment variable through process.env in my React/Typescript code, but it's returning undefined. I am able to access NODE_ENV
though.
console.log(process.env.CURRENT_URL) // prints "undefined" on browser
console.log(process.env.NODE_ENV) // prints "development" on browser
CURRENT_URL
is present in windows environment variable.
Why is process.env.NODE_ENV
is accessible but not the other variable?
Upvotes: 7
Views: 19399
Reputation: 1
I had the same problem also but when I restart(with npm start
) my project it works!
Try restarting your application:
npm start
Upvotes: 0
Reputation: 2010
As you are on a react
project, you would have to prepend the env variables with REACT_APP_
.
You can follow those steps:
REACT_APP_
(e.g: REACT_APP_MY_VAR
).process.env.REACT_APP_MY_VAR
).Example:
Define the variables in .env
file
REACT_APP_PASSWORD=1234
REACT_APP_LANGUAGE=english
How to use the environment variables
?
console.log(process.env.REACT_APP_LANGUAGE);
// output: english
Don't forget to restart the application when you add a new environment variable.
Upvotes: 4
Reputation: 2502
This is your answer, from the official create-react-app docs.
Summary:
By default you will have NODE_ENV
defined for you, and any other environment variables starting with REACT_APP_
.
So prepend REACT_APP_
to all your env variables e.g. REACT_APP_CURRENT_URL
.
That should work!
Upvotes: 10
Reputation: 103
The issue was being caused by backstage software configuration, which was blocking the frontend plugin from accessing variables. I had to explicitly expose the variables to my frontend plugin using - backstage visibility keyword
Upvotes: 0