Adding an .env file to React Project
So I'm myself new to React and I found a way to do it.
This solution does not require any extra packages.
Step 1 ReactDocs
In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file
1.1 create Root/.env
#.env file
REACT_APP_SECRET_NAME=secretvaluehere123
Important notes it MUST start with REACT_APP_
1.2 Access ENV variable
#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>
handleFetchData() { // access in API call
fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
.then((res) => res.json())
.then((data) => console.log(data))
}
1.3 Build Env Issue
So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.
4 steps
npm install dotenv --save
Next add the following line to your app.
require('dotenv').config()
Then create a
.env
file at the root directory of your application and add the variables to it.
// contents of .env
REACT_APP_API_KEY = 'my-secret-api-key'
- Finally, add
.env
to your.gitignore
file so that Git ignores it and it never ends up on GitHub.
If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_
for it to work.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/
NOTE - Need to restart application after adding variable in .env file.
Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f
Today there is a simpler way to do that.
Just create the .env.local file in your root directory and set the variables there. In your case:
REACT_APP_API_KEY = 'my-secret-api-key'
Then you call it in your js file in the following way:
process.env.REACT_APP_API_KEY
React supports environment variables since [email protected] .You don't need external package to do that.
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#adding-development-environment-variables-in-env
*note: I propose .env.local instead of .env because create-react-app add this file to gitignore when create the project.
Files priority:
npm start: .env.development.local, .env.development, .env.local, .env
npm run build: .env.production.local, .env.production, .env.local, .env
npm test: .env.test.local, .env.test, .env (note .env.local is missing)
More info: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables