When you work on software projects, it's essential to deal with sensitive data like API keys. Making these keys invisible is crucial to avoid security breaches. You might initially consider excluding the entire files that contain API keys by adding them to your .gitignore
file. However, this approach has its downsides, especially if those files contain non-sensitive code that you want to remain in your repository. This article will guide you on how to hide API keys properly without excluding the entire file and removing them from the commit history if sensitive data has been already pushed.
Why Hide API Keys?
API keys grant access to services and data. Exposing them publicly can lead to the following:
- Unauthorized access to your account.
- Potential misuse of your quotas or sensitive services.
- Financial losses if the APIs involve paid services.
Step-by-Step Guide to Hide API Keys
Step 1) Move API Keys to an Environment File
Instead of hardcoding API keys in your secure files, create .env
file and store the keys in it like this:
# .env file
API_KEY=your_api_key
Step 2) Add .env
to .gitignore
To ensure the .env
file which contains your API keys is not pushed to GitHub, add it to your .gitignore
file:
# Environment variables
.env
This will prevent Git from tracking the .env
file.
Step 3) Installation and Configuration
Install dependencies
npm install dotenv --save -dev @type/node
Configure vite.config.ts
import dotenv from "dotenv";
dotenv.config(); // Load .env file
export default defineConfig({
plugins: [react()],
// Add this
define: {
"process.env": process.env,
},
});
Step 4) Update Your Code to Import Environment Variables
Your existing code may be like this:
import axios from "axios
const your_api_variable = "your_api_key";
export const function = async () => {
try {
const response = await axios.get(`https://api.random_api.net/example_api_key=${your_api_variable}`);
return response.data.status === "valid";
} catch (error) {
console.error("Invalid", error);
}
};
Updated version: Refactor your code to fetch the API key from environment variables of .env
file using process.env.
prefix like this:
import axios from "axios
// Get API key from environment variables of .env file
const your_api_variable = process.env.API_KEY;
export const function = async () => {
try {
const response = await axios.get(`https://api.random_api.net/example_api_key=${your_api_variable}`);
return response.data.status === "valid";
} catch (error) {
console.error("Invalid", error);
}
};
Replacing your API key with process.env.API_KEY
lets your code import the API key as an environment variable from the .env
file.
Step 5) Push Your Changes to GitHub
Since your sensitive data is no longer hardcoded in the source files, you can safely push your files to GitHub without exposing your API keys. Ensure the .env
file remains untracked.
Step 6) Remove Sensitive Data from Commit History
If your API keys were already committed to GitHub, you must remove them from the commit history. Here's how to do it using git filter-repo
command:
Install git filter-repo
pip install git-filter-repo
Remove Sensitive Files From Commit History
Run the following command to rewrite your repository's history and remove sensitive files:
git filter-repo --path src/api/your_file_with_sensitive_data.ts --invert-paths
Try adding --force
at the end if this way doesn't work. This command will remove the specified files from the commit history.
Force Push to Update Remote Repository
After rewriting history, you need to force-push your changes:
git push origin main --force
Warning:
- This operation rewrites your repo's history. Ensure you communicate this with your team and back up your repository beforehand.
- If you accidentally expose your API keys, revoke them immediately and generate new ones.
- Use tools like GitHub Dependabot or git-secrets to monitor your repositories for sensitive information.
Conclusion
By removing API keys to environment variables, ignoring the .env
file, and cleaning up commit history, you can ensure that your sensitive data remains secure while maintaining the ability to push your source code to GitHub. This approach strikes the right balance between security and collaboration.
If you found this guide helpful, feel free to share this article or leave a comment below with your thoughts or additional tips!
Top comments (0)