Skip to Content

How Do You Protect Your OpenAI API Key from Public GitHub Leaks?

Why You Should Always Secure API Keys with Environment Variables

Learn how to securely store your OpenAI API keys and prevent costly unauthorized charges. Discover why using environment variables protects your credentials from accidental public exposure on GitHub repositories.

Question

During setup, a developer accidentally commits their OpenAI API key to a public repository. Later, they find unexpected usage on their account. What step would have prevented this?

A. Hardcoding the API key for convenience.
B. Running the model offline to avoid exposure.
C. Adding longer prompts to the workflow.
D. Storing API credentials securely using environment variables.

Answer

D. Storing API credentials securely using environment variables.

Explanation

When a developer accidentally uploads an API key to a public repository (like GitHub), automated scrapers quickly find it, leading to unauthorized usage and unexpected account charges. This critical security failure happens because the developer “hardcoded” the sensitive key directly into the application’s source code. To prevent this, developers should store API credentials in hidden environment variables (such as a .env file) and explicitly exclude that file from version control using a .gitignore list. This practice ensures the source code can be safely shared publicly without exposing the private credentials.