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.
for those who are not able to access env variables and process.env.APIKEY shows undefined. You need to know this :
if your project has a similar directory structure :
project
->client(This is your frontend)
->components
->SomeComponent.tsx ( and you need to access env variable in this file then .env should be in client directory not the main project directory)
I made a seperate .env for client and it solved my issue. I think it happens becuase you run "npm start" in client directory ( which is your frontend ) and it will only bundle files from client only.
Hope this helps.