How to safely store API Keys
Last Updated: 2022-03-22
API Key is a secret that you should properly protect. More specifically:
- API Keys should NOT be checked into code repository, especially public repos in GitHub
- API Keys should NOT be included in your client code, which is readable by public
Create-react-app has such a warning:
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.
Since create-react-app generates a site that totally runs on client side, whichever way you choose, the API key will be exposed.
One solution is to serve that app with a backend (e.g. Express), as long as you do not enable Cross-Origin Resource Sharing (CORS) on the backend, only the frontend app can communicate to the backend; then use API Key in backend to talk to an internal API/API Gateway, or 3rd party APIs.