Dotenv is commonly used (create-react-app uses it, so there) and will get the variables from our . env file and add them to the global process.
env file in our react js project. If you are using some external APIs for data you must use the . env file to store your sensitive credentials like API keys. Environment variables can also help us to store our API link in one location so that we don't have to change the link in each file manually.
With create react app, you need to prefix REACT_APP_
to the variable name. ex:
REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_CALLBACK_URL=http://localhost:3005/callback
CRA Docs on Adding Custom Environment Variables:
Note: You must create custom environment variables beginning with
REACT_APP_
. Any other variables exceptNODE_ENV
will be ignored to avoid accidentally exposing a private key on the machine that could have the same name
Make sure your .env file is in the root directory, not inside src folder.
Had this same problem! The solution was to close the connection to my node server (you can do this with CTRL + C). Then re-start your server with 'npm run start' and .env should work properly.
Source: Github
If you want to use multiple environment like .env.development
.env.production
use dotenv-cli package
add .env.development
and .env.production
in project root folder
and your package.json
"scripts": {
"start": "react-app-rewired start",
"build-dev": "dotenv -e .env.development react-app-rewired build",
"build-prod": "dotenv -e .env.production react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
then build according to environment like
npm run-script build-dev
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