Is there a way to inject environment variables, e.g. REACT_APP_MY_API
into the index.html
file?
According to this, it can be done, but I can't seem to get it to work.
REACT_APP_MY_API=https://something.com
<script type="text/javascript"> console.log("%REACT_APP_MY_API%") // undefined console.log("%NODE_ENV%") // development </script>
For all custom environment variables in apps created via create-react-app, we need to use REACT_APP_ prefix in env var names - it's a requirement, if we don't follow the convention, variables will not be accessible in our application! Also, remember that all the values are accessible on the client-side (browser).
Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, as described here. Alternatively you can rebuild the app on the server anytime you change them.
By default, we will have NODE_ENV and any other env variables within React App will start with the prefix REACT_APP_ Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology. [1]
This environment variable is part of Create React App, as stated in the official documentation. “ […] a built-in environment variable called NODE_ENV. You can read it from process.env.NODE_ENV.
I just tried with an (almost) new CRA setup and it works.
<head> <title>React App</title> <script type="text/javascript"> console.log("%REACT_APP_TEST%") // OK console.log("%NODE_ENV%") // development </script> </head>
Did you try restarting the server? I just tried changing the test variable with your example and it works if you restart the development server.
As someone pointed out in the comments, the official documentation of CRA has a section about that.
Make sure you restart your create-react-app when adding variables into the .env file
Also make sure you have >= [email protected]
I use .env variables for the meta title of a site with various language versions of the build:
<title>%REACT_APP_SITE_TITLE%</title>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With