Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create React App: using environment variables in index.html

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.

.env

REACT_APP_MY_API=https://something.com 

index.html

<script type="text/javascript">   console.log("%REACT_APP_MY_API%") // undefined    console.log("%NODE_ENV%") // development </script> 
like image 594
Colin Ricardo Avatar asked Aug 08 '18 10:08

Colin Ricardo


People also ask

How to create custom environment variables in react-app?

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).

Can create react app read static elements at runtime?

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.

What is react_app_ dotenv?

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]

What is node_ENV in ReactJS?

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.


2 Answers

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.

like image 107
Clafou Avatar answered Oct 14 '22 22:10

Clafou


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>

like image 41
HAS-Jack Avatar answered Oct 14 '22 22:10

HAS-Jack