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”;
Unless you’re making tutorial apps, don’t put secrets such as API keys in client side source code (e.g. React app). From Create React App’s documentation:
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can view them by inspecting your app’s files.
First, create an .env file in the root of your project, i.e. where you would run
react-scripts start (or
yarn start) outside of your src folder.
Before commit, you should exclude this .env file so find .gitignore file and add .env.
The name of the variable needs to begin with
REACT_APP_ which protects you from accidentally including secrets with your build.
Don’t forget to add .env in .gitignore file.
To to use the env variables in your code:
const API_KEY = process.env.REACT_APP_WEATHER_API_KEY;
In order to read env variables after having added them to
.env, restart your server.