How to Hide an API Key in GitHub Repositories

Summarize this article with:
One exposed API key can drain your account in hours. Hackers run automated scripts scanning GitHub repositories for hardcoded secrets, and they find thousands daily.
Learning how to hide an API key in GitHub protects your credentials, your users, and your budget.
This guide covers four proven methods for keeping sensitive data out of your repository.
You will learn to create .env files, configure .gitignore properly, set up repository secrets, and use encrypted credentials in workflow files.
Each step includes exact paths, specific commands, and verification checks. No guesswork required.
How to Hide an API Key in GitHub

Hiding an API key in GitHub is the process of preventing sensitive credentials from being exposed in version control.
You do this using environment variables, configuration files excluded from commits, or encrypted repository secrets.
Developers need this when building applications that connect to third-party services.
It also matters when deploying code to a production environment or collaborating on public repositories.
This guide covers 4 methods requiring 10 to 15 minutes and basic familiarity with Git and terminal commands.
Prerequisites
Before you start, make sure you have these tools and access levels ready.
- Git version 2.30 or later installed on your machine
- A GitHub account with repository access
- Text editor such as VS Code or Sublime Text
- Terminal or command line access
- Basic understanding of version control and environment variables
- Node.js 18+ or Python 3.8+ if applicable to your project
Time estimate: 10-15 minutes for full setup.
Step One: How Do You Create a .env File for Your API Keys?
Create a .env file in your project root directory, add key-value pairs in the format APIKEY=youractualkey, and save without any file extension.
This file stores your secret key locally so your codebase stays clean.
Action
- Project root directory: Create new file named
.env - File format: Add
APIKEY=youractualkeyhere(one variable per line) - Result: File appears in project folder without .txt extension
Purpose
Separates sensitive credentials from source code files that get committed to source control.
Your access tokens and authentication credentials stay on your local machine only.
Step Two: How Do You Add .env to Your .gitignore File?
Open or create a .gitignore file in your project root, add .env on a new line, save, and verify Git stops tracking the environment file.
This prevents credential exposure in your commit history.
Action
- Project root directory: Open or create
.gitignore - New line entry: Add
.env(also add.env.local,.env.productionif used) - Result: Running
git statusno longer shows .env as untracked
Purpose
Prevents Git from including the file containing your API keys in any commits pushed to GitHub.
Protects sensitive data even when sharing code publicly.
Quick Verification
Run git status in terminal; .env should not appear in untracked files list.
Step Three: How Do You Access Environment Variables in Your Code?
Replace hardcoded API key strings with process.env in Node.js or os.environ in Python to read credentials at runtime.
Your application pulls the secret key value without exposing it in source files.
Action
- Node.js syntax:
const apiKey = process.env.APIKEY - Python syntax:
apikey = os.environ.get('APIKEY') - Result: Application reads key value at runtime from environment configuration
Purpose
Allows your application to use credentials stored outside the codebase during app deployment.
Node.js Setup
Install dotenv package: npm install dotenv
Add require('dotenv').config() at the top of your entry file before accessing process.env variables.
Python Setup
Install python-dotenv: pip install python-dotenv
Add from dotenv import loaddotenv then call loaddotenv() before accessing os.environ.
Step Four: How Do You Create a .env.example Template File?
Create a .env.example file with variable names but empty or placeholder values, then commit this file so collaborators know which environment variables they need.
Action
- Project root directory: Create
.env.example - File content: Add
APIKEY=yourkeyhere - Result: Template file commits to repository while actual keys stay local
Purpose
Documents required environment variables for other developers without exposing real credentials.
Critical for team collaboration and proper software documentation practices.
Step Five: How Do You Set Up GitHub Repository Secrets?
Navigate to Settings > Secrets and variables > Actions in your GitHub repository, click New repository secret, enter a name in uppercase, paste the key value, and save.
Secrets use Libsodium encryption before reaching GitHub servers.
Action
- Repository path: Settings > Secrets and variables > Actions
- Button click: New repository secret
- Input fields: Name (e.g.,
APIKEY), Value (paste actual key) - Result: Secret appears in list with masked value
Purpose
Stores encrypted secrets for use in GitHub Actions workflows during automated deployments.
Secret Naming Rules
- Alphanumeric characters and underscores only
- Cannot start with GITHUB prefix or numbers
- Case-insensitive; stored as uppercase
- 48 KB size limit per secret
Step Six: How Do You Use GitHub Secrets in a Workflow File?
Reference secrets in .github/workflows YAML files using the secrets context with double curly braces and the exact secret name you created.
Action
- Workflow file location:
.github/workflows/deploy.yml - Environment variable syntax:
env: APIKEY: ${{ secrets.APIKEY }} - Result: Workflow accesses encrypted secret during job execution
Purpose
Passes credentials securely to automated processes in your build pipeline without exposing them in workflow files.
Works with continuous integration and continuous deployment setups.
Verification
Confirm .gitignore Works
Run git status in terminal.
The .env file should not appear in untracked or modified files list.
Confirm Environment Variable Loads
Add console.log(process.env.APIKEY) temporarily.
Run your application; key value should print to terminal.
Confirm GitHub Secret Exists
Navigate to Settings > Secrets and variables > Actions.
Your secret name should appear in the repository secrets list.
Troubleshooting
Issue: .env File Still Shows in Git Status
Solution: File was tracked before adding to .gitignore.
Run git rm --cached .env to untrack it, then commit the change.
Issue: Environment Variable Returns Undefined in Node.js
Solution: Install dotenv package with npm install dotenv.
Add require('dotenv').config() at the top of your entry file before accessing process.env.
Issue: GitHub Action Fails With “Secret Not Found” Error
Solution: Check secret name matches exactly (case-sensitive).
Verify secret was created at repository level, not environment level, if your workflow does not specify an environment.
Issue: API Key Was Already Committed to Repository History
Solution: Revoke the exposed key immediately through your API provider.
Generate a new key, use git filter-repo or BFG Repo-Cleaner to remove from commit history, then force push.
Alternative Methods
Method A: .env File
- Setup time: 5 minutes
- Works with: Local development, most hosting platforms
- Best for: Solo developers, small teams, standard web apps
Method B: GitHub Repository Secrets
- Setup time: 3 minutes
- Works with: GitHub Actions workflows only
- Best for: CI/CD pipelines, automated deployments, public repositories
Method C: Config.js With .gitignore
- Setup time: 5 minutes
- Works with: Front-end JavaScript projects
- Best for: Browser-based applications without build tools
Which Method to Choose
Method A for local development.
Method B for automated workflows and DevOps pipelines.
Method C for client-side JavaScript projects.
Related Processes
- Setting up environment variables on Vercel or Netlify
- Using AWS Secrets Manager for cloud-based app deployments
- Rotating API keys after accidental exposure
- Setting up git-secrets pre-commit hooks
- Implementing token-based authentication for RESTful API access
- Managing secrets in containerization workflows with Docker
FAQ on How To Hide An API Key In Github
What happens if I accidentally push an API key to GitHub?
Your key becomes visible in the commit history permanently, even after deletion. Revoke the exposed key immediately through your provider, generate a new one, and use git filter-repo or BFG Repo-Cleaner to scrub the history before force pushing.
Can I hide API keys in a public repository?
Yes. Use .env files added to .gitignore for local development. For automated workflows, store credentials as repository secrets in Settings > Secrets and variables > Actions. Both methods keep sensitive data hidden from public view.
What is the difference between .env and GitHub Secrets?
A .env file stores environment variables locally on your machine for development. GitHub Secrets store encrypted credentials on GitHub servers for use in deployment pipelines. Use both together for complete protection.
How do I access GitHub Secrets in my workflow file?
Reference secrets using the syntax ${{ secrets.YOURSECRETNAME }} in your YAML workflow file. Set them as environment variables with env: APIKEY: ${{ secrets.APIKEY }}. The value stays masked in logs automatically.
Does .gitignore remove files already committed?
No. Adding a file to .gitignore only prevents future tracking. To remove an already-committed file, run git rm --cached filename first. Then commit the change and push. The file remains in prior commit history.
Can team members access my repository secrets?
Collaborators with write access can use secrets in workflows but cannot view the actual values. Only repository admins can create, update, or delete secrets. Organization secrets follow separate configuration management policies.
What is the best way to share API keys with my team?
Create a .env.example file with variable names but empty values and commit it. Share actual keys through a password manager or secure channel. Each developer creates their own local .env file from the template.
How do I use environment variables in Node.js?
Install the dotenv package with npm install dotenv. Add require('dotenv').config() at the top of your entry file. Access keys with process.env.APIKEY. This works for back-end development and server-side scripts.
Are GitHub Secrets safe from being leaked in logs?
GitHub automatically redacts secret values printed to workflow logs. However, transformed or split values may not be caught. Avoid echoing secrets directly. Use code review to catch accidental exposure before merging.
How many secrets can I store in a GitHub repository?
You can store up to 100 repository secrets and 100 environment secrets per repository. Each secret has a 48 KB size limit. Organization-level secrets allow sharing across multiple repositories with access policies.
Conclusion
Knowing how to hide an API key in GitHub is a basic but critical skill for any developer working with version control security.
The methods covered here, from .env files to encrypted workflow secrets, give you multiple layers of protection.
Pick the approach that fits your project. Local development needs .gitignore rules. Automated pipelines need source control management with proper secret handling.
The setup takes minutes. The protection lasts for the entire app lifecycle.
Review your existing repositories today. Check for exposed credentials in your commit history. Rotate any keys that may have been compromised.
Your API keys deserve the same care as your passwords. Treat them accordingly.
- What Is Agentic Coding? The Next AI Dev Workflow - April 10, 2026
- From Setup To Monitoring: Why A DMARC Service Matters - April 10, 2026
- 4 Scalable Hosting Providers for Growing Small Business Websites - April 9, 2026







