Four steps
-
npm install dotenv --save -
Next, add the following line to your app.
require('dotenv').config() -
Then create a
.envfile 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
.envto your.gitignorefile so that Git ignores it and it never ends up on GitHub.
If you are using Create React App (create-react-app) then you only need step 3 and 4, but keep in mind a variable needs to start with REACT_APP_ for it to work.
Reference: Adding Custom Environment Variables
Note – You need to restart the application after adding a variable in the .env file.
Reference: Using the dotenv package to create environment variables