React JS App-env

If you used create-react-app then some of the magic below would have already been done for you.

  1. Install dotenv
1
npm install dotenv --save
  1. Next add the following line to your app.
1
require('dotenv').config()
  1. 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'
  1. To access
1
2
3
<pre>{process.env.REACT_APP_API_URL}</pre>

const { REACT_APP_API_URL } = process.env;

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;

  1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

Built in magic

1
2
3
4
5
process.env.NODE_ENV

npm start = development
npm run build = production
npm test = test

References