If you used create-react-app
then some of the magic below would have already been done for you.
- Install
dotenv
1 | npm install dotenv --save |
- Next add the following line to your app.
1 | require('dotenv').config() |
- Then create a .env file at the root directory of your application and add the variables to it. Variables needs to start with
REACT_APP_
for it to work.
1 | REACT_APP_API_KEY = 'my-secret-api-key' |
- To access
1 | <pre>{process.env.REACT_APP_API_URL}</pre> |
This did work for a project that was created with.
Instead I had to access the env data as const url = process.env.REACT_APP_API_URL;
- Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.
Built in magic
1 | process.env.NODE_ENV |