For a simple way to use environment variables in your react-create-app
project, follow these steps:
- Create a new file named
.env
in the root of your project. - In your new
.env
file, add a new key=value pair. For security reasons, you must prepend your key with REACT_APP, for exampleREACT_APP_API_KEY=abcdefg123456789
- Restart your server development server. In order for React to find and register your newly created environment variable you must restart your server. Do this every time you add or change a variable.
- Your new variables will now be available throughout your React app via the global
process.env
object. In our case, we could get our API key usingprocess.env.REACT_APP_API_KEY
.
- Since we commonly store secrets in
.env
you probably want to add it to.gitignore
. - You don't need to install the
dotenv
package or anything else for this to work.