DEV Community

Cover image for How to Hide Only API Keys Instead of Entire Files on GitHub and From Its Commit History
Ryoichi Homma
Ryoichi Homma

Posted on

How to Hide Only API Keys Instead of Entire Files on GitHub and From Its Commit History

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, store them in a .env file that should be located at the root of your project. For example:

# .env file
API_KEY=your_api_key
Enter fullscreen mode Exit fullscreen mode

If your project is built with React or Vite, the REACT_ or VITE_ prefix is necessary because it requires this prefix to expose environment variables to the client-side.

  • React:
# .env file
REACT_API_KEY=your_api_key
Enter fullscreen mode Exit fullscreen mode
  • Vite:
# .env file
VITE_API_KEY=your_api_key
Enter fullscreen mode Exit fullscreen mode

Step 2) Update Your Code to Import Environment Variables

Your code may be like:

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);
  }
};
Enter fullscreen mode Exit fullscreen mode

Updated version: Refactor your code to fetch 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);
  }
};
Enter fullscreen mode Exit fullscreen mode

Replacing your API key with import.meta.env.VITE_API_KEY lets your code import the saved API key as an environment variable from the .env file.

Step 3) 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
Enter fullscreen mode Exit fullscreen mode

This will prevent Git from tracking the .env file.

Step 4) 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 5) 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)