When you’re working on a software project, handling sensitive data such as API keys is crucial. Protecting these keys is critical to avoiding security breaches. You might initially consider adding the entire file containing the API key to your .gitignore
document. However, this approach has its drawbacks, especially if these files contain non-sensitive code that you want to keep in the repository. This article will guide you on how to properly hide API keys without excluding the entire file and removing it from your commit history (if sensitive material has been pushed).
Why protect API keys?
API keys grant access to services and data. Exposing them publicly may result in the following consequences:
- Unauthorized access to your account.
- Possible misuse of your quota or sensitive services.
- If the API involves paid services, it will cause economic losses.
Step-by-step guide to hiding API keys
Step 1) Move the API key to the environment file
Do not hardcode API keys into security files, instead store them in .env
The file should be located in the root directory of the project. For example:
# .env file
API_KEY=your_api_key
If your project is built using React or Vite, REACT_
or VITE_
The prefix is necessary because it requires this prefix to expose environment variables to clients.
# .env file
REACT_API_KEY=your_api_key
# .env file
VITE_API_KEY=your_api_key
Step 2) Update code to import environment variables
Your code might look like this:
import axios from "axios
const API_KEY = "your_api_key";
export const your_api_variable = 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 obtain these keys from environment variables. For example:
import axios from "axios
// Get API key from environment variables of .env file
const API_KEY = import.meta.env.VITE_API_KEY;
export const your_api_variable = 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);
}
};
Replace your API key with import.meta.env.VITE_API_KEY
Let your code import the saved API key as an environment variable .env
document.
Step 3) Add .env
arrive .gitignore
To ensure .env
The file containing your API key has not been pushed to GitHub. Please add it to your .gitignore
document:
# Environment variables
.env
This will prevent Git from tracking .env
document.
Step 4) Push your changes to GitHub
Because your sensitive data is no longer hardcoded in the source archive, you can securely push archives to GitHub without exposing your API key. make sure .env
The documents remain untracked.
Step 5) Remove sensitive data from commit history
If your API keys have been committed to GitHub, they must be removed from the commit record. Here’s how to use git filter-repo
Order:
Install git filter-repo
pip install git-filter-repo
Remove sensitive files from commit history
Execute the following commands to overwrite the repository’s history and delete sensitive archives:
git filter-repo --path src/api/your_file_with_sensitive_data.ts --invert-paths
Try to add --force
Finally if this approach doesn’t work. This command will delete the specified archive from the commit history.
Force push update to remote repository
After rewriting history, you need to force push the changes:
git push origin main --force
warn:
- This action will overwrite your repository’s history. Make sure you communicate with your team and back up your repository ahead of time.
- If you accidentally expose your API keys, revoke them immediately and generate new ones.
- Use tools like GitHub relies on bots or git secret Monitor your repositories for sensitive information.
in conclusion
By deleting the API key in the environment variable, ignore .env
Files and clean commit history, you can ensure sensitive data remains secure while maintaining the ability to push source code to GitHub. This approach strikes the right balance between security and collaboration.
If you found this guide helpful, please feel free to share this post or leave a comment below with your thoughts or other tips!