The .env file can hold global variables, also known as environment variables. These variables allow you to configure your React application without having to change the source code. Furthermore, a .env file in React is a simple and effective way to securely store sensitive data. The data does not then appear directly in the source code.
Projects that were created with create-react-app can already handle .env files
No import of an additional library is needed. However, the variables must begin with REACT_APP.
It is also important that the sensitive data from the .env file is not uploaded to public repositories like Github, Gitlab, etc. Therefore, the .env file should be included in the .gitignore of the project, then it will automatically be excluded from the upload to the repository.
Basically, the .env file is a simple text file that contains variables that can then be used in the project. The structure of the file can look something like this:
Within your React project, you access the variables via the process.env object. As mentioned, no
import of a component is necessary if you have created the React project via
So, if you want to create a link based on the
REACT_APP_URL variable, you would use the following code:
Please note that the .env file is only loaded when the project is loaded/started, such as during
npm start. So if you change values in the file, you must logically restart the project in node.js.
The .env file is also handy when it comes to switching between the development version (which usually works with localhost) and the production version. You simply create two variables and comment out the one currently not needed. Like this:
# dev variable REACT_APP_URL=http://localhost:5000 # prod variable # REACT_APP_URL=http://meinecooledomain:5000
The file must be placed in the main directory of the project for it to work. I have often enough created it in the
src folder and wondered why it wasn’t working. To avoid the same happening to you, here’s a screenshot 😀
Furthermore, you can find a complete description on the website of the