Have you ever create an application with React, in this application you use external API’s and you pushed these API keys on GitHub ?
Oh no bad practice now everybody can use your API key.
We will see how we can avoid this and hide your API’s keys on Github, you need .env file.
How to setup .env file inside React app ?
You don’t need to install env package, this feature is available with email@example.com and higher.
Make a file called .env in your project root
Inside the env file, add your variables and API keys value like this :
REACT_APP_GITHUB_API_KEY=Hello world 12345 REACT_APP_MOOVIE_API=0123456789
You should prefix all your variables name by REACT_APP if not it will be ignored
Now you need to restart your React server with npm start to access these variables
Inside your React application, you can now access these variables in using this syntax :
Now you have zero excuse to push your API key in your React application.
Here you have the React documentation about using environment variables
Top comments (5)
I would say if an api key is needed, it should be in the backend logic and not in the frontend. Also use a secret management platform like doppler.com or vault etc. so you have no .env file in your repo.
Hmm, I would also say, that it's not good idea to add any secret API key into your production build. So when your GITHUB_API_KEY (whatever it is) is in the .env while build it is present in the production build and readable. Maybe it's better to use .env.development.local and think twice which is public API key and which is not.
Yes, the example with the API key is exactly contrary to what the linked article has as an example: process.env.REACT_APP_NOT_SECRET_CODE
Having your secret API key in a build on a publicly available URL is a bigger security issue than having it on github. At least github notifies you by scanning repositories for things like that
Wouldn't the end-point address be exposed anyways even if you use. env or not if you push it to production server?
That's why you should use .env.development.local :) Those variables are not part of production build.