I made a weather app in create-react-app. How do I hide the API key so that I can commit to GitHub?
Right now the key is in App.js: const API_KEY = "123456";
I made a weather app in create-react-app. How do I hide the API key so that I can commit to GitHub?
Right now the key is in App.js: const API_KEY = "123456";
Hope it's not late so here's how I did it. on root folder, if you are using react prepend you environment variable with
REACT_APP_
so goes like this.REACT_APP_API_KEY=<keye here>
you don't. React environment will look at the.env
checks if you prependREACT_APP_
then you can use it.that will get you you're variables.
if you are using node then you need a package https://www.npmjs.com/package/dotenv
thats it. enjoy :)
Create a config_keys.js file with keys in it. Export them as default
Then import them in your app.js or target .js file
and then add config_keys.js to .gitignore
To elaborate Arup Rakshit's comment,
First, you should make .env file outside of your src folder.
Then, add
Before commit, you should exclude this .env file so find .gitignore file and add .env.
Now you're free to go.
Don't forget to add .env in .gitignore file.
Added:
const API_KEY = process.env.REACT_APP_WEATHER_API_KEY;
In order to read env variables, you should restart your server.
You can create a separate file with all credentials and declaring your keys there. And add this file to
.gitignore
Here's what worked for me:
I created the
.env
in the root folder. Within that folder I added my key:Then i went to
.gitignore
|| or create a .gitignore in your root directory if you don't have it. Within .gitignore I added .envThen I went back to the root of my app js file. For me that was index.js for other it is probably App.js There I created a const API_KEY
I checked if it was working by console logging it.
I was getting
undefined
. I stopped the server (Control + C
) and restarted the server. Afterwards I was able to see the key.As it turns out, create-react-app has some built-in functionality to help you with that. Thank you George Karametas for this insight. To access that functionality, you need to:
1. Create a file called
.env
in the root of your project's directory.2. Inside the
.env
file, prependREACT_APP_
to your API key name of choice and assign it.The
create-react-app
tool usesREACT_APP_
to identify these variables. If you don't start your API key name with it,create-react-app
won't see it.3. Add the
.env
file to your.gitignore
file.After you add the line below, save the
.gitignore
file and do agit status
to make sure your.env
file does not appear as a new file in git.4. Access the API key via the
process.env
object.To check that you can access your API key, go to your
App.js
file and add aconsole.log
at the top below therequire
statements. After saving the file and reloading the page, if the console log does not show your API key, try restarting the react server. Be sure to remove the console log line before committing your code.