DEV Community

Cover image for Stop pushing your React API Key on GitHub 😪
Mansour Mahamat
Mansour Mahamat

Posted on

Stop pushing your React API Key on GitHub 😪

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 react-scripts@0.2.3 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
Enter fullscreen mode Exit fullscreen mode

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 :

{process.env.REACT_APP_GITHUB_API_KEY}
{process.env.REACT_APP_MOOVIE_API}
Enter fullscreen mode Exit fullscreen mode

API Usage

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)

Collapse
 
gktim profile image
gkTim

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.

Collapse
 
jancizmar profile image
Jan Cizmar

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.

Collapse
 
shnydercom profile image
Jonathan Schneider

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

Collapse
 
koichadev profile image
Khoi Hoang • Edited

Wouldn't the end-point address be exposed anyways even if you use. env or not if you push it to production server?

Collapse
 
jancizmar profile image
Jan Cizmar

That's why you should use .env.development.local :) Those variables are not part of production build.