How to Remove Secrets from Environment Variables and Git History

Quick answer: To remove secrets from environment variables, you must rotate compromised credentials immediately and use tools like git filter-repo or BFG Repo-Cleaner to scrub them from Git history. Simply deleting the file is insufficient. Migrate to a dedicated secret manager to prevent plain-text exposure in .env files or system process lists.

By Paula C · Kraftwire Software

· 10 min read

To remove secrets from environment variables, you must immediately rotate the compromised credentials and use specialized tools like git filter-repo or BFG Repo-Cleaner to scrub the sensitive strings from your entire Git history. Simply deleting the .env file or reverting a commit is insufficient because the plain-text secret remains in the Git object database. For a complete cleanup, you must force-push the rewritten history and migrate to a dedicated secret manager to prevent future exposure in process lists or logs.

When building with "vibe-coding" tools like Lovable, Bolt.new, or Cursor, the speed of development often leads to accidental commits of sensitive configuration. This guide provides a technical deep dive into purging those secrets and securing your architecture.

Why Is It Critical To Remove Secrets From Environment Variables?

Environment variables (env vars) are a standard way to pass configuration to applications, but they are not a security feature. When secrets like database passwords, Stripe keys, or AWS credentials live in environment variables, they are vulnerable to several attack vectors.

1. Process List Visibility

On Unix-like systems, any user with access to the machine can often view the environment variables of running processes. Running a command like ps auxww or inspecting /proc/[pid]/environ can reveal every secret passed to the application. This is why no secrets in env vars is a core tenet of the 12-Factor App methodology.

2. Log and Crash Report Leakage

Many monitoring tools and crash reporters (like Sentry or LogRocket) automatically capture the environment state when an error occurs. If a secret is stored in a standard env var, it may be transmitted to a third-party logging service in plain text.

3. Git History Persistence

The most common leak occurs when a .env file is accidentally committed. Even if you delete the file in the next commit, the secret remains in the .git directory. Anyone who clones the repository can use git checkout on an older commit or use git cat-file to extract the sensitive string.

How To Remove Secrets From Git History Permanently

If you have committed a secret, you must treat it as compromised. However, you still need to clean the repository to prevent future developers or automated tools from finding it.

1. Using Git Filter-Repo (Recommended)

The modern standard for scrubbing history is git filter-repo. It is significantly faster and safer than the legacy git filter-branch.

  • Installation: Most developers install it via python's pip: pip install git-filter-repo.
  • Execution: To replace a specific secret across all commits, create a text file (e.g., expressions.txt) containing the string to be replaced:
  • Run the command:

This command rewrites every commit in your history, replacing the leaked key with the redacted placeholder.

2. Using BFG Repo-Cleaner

BFG Repo-Cleaner is a Java-based tool designed specifically for this task. It is often faster than Git's internal tools for large repositories.

  • Create a passwords file: List your secrets in passwords.txt.
  • Run BFG:
  • Cleanup: After BFG finishes, you must run Git's garbage collector to prune the old objects:

3. The Force Push

After rewriting history locally, your local branch will have diverged from the remote. You must use git push origin --force --all to overwrite the history on the server. Warning: This will break the local clones of every other developer on the team. Coordinate this action carefully.

How To Avoid Secrets In .env Files During Development

Prevention is more efficient than remediation. For vibe-coded apps, where AI agents often generate .env files automatically, you need strict guardrails.

Use .gitignore Properly

Before your first commit, ensure your .gitignore includes patterns for all environment files. Using a gitignore generator is the best way to ensure you don't miss framework-specific files like .env.local or .env.development.local.

Implement Env File Linters

Automated linting can catch secrets before they are committed. An env file linter can check for common mistakes, such as using production keys in a development environment or forgetting to add a file to the ignore list.

Use Template Files

Always provide a .env.example file. This file should contain the keys (e.g., STRIPE_API_KEY=) but leave the values empty. This allows the AI or other developers to know what variables are required without seeing the actual secrets.

How To Prevent Secrets In Process List Visibility

If you must use environment variables in production, you should minimize their exposure to the system's process list.

  • Avoid CLI Arguments: Never pass secrets as flags (e.g., --api-key=123). These are globally visible in ps.
  • Use Filesystem Permissions: Store secrets in a file with 600 permissions (read/write for owner only). You can use a chmod calculator to verify your permission strings.
  • Use Docker/Kubernetes Secrets: These platforms mount secrets into a tmpfs (in-memory filesystem) at a path like /run/secrets/. The application reads the secret from a file rather than an environment variable, keeping it out of the global env list.

What Are The Best Practices For Rotating Compromised Keys?

Once a secret is exposed in Git or a public environment variable, it is compromised forever. Scrubbing the history does not "un-leak" the key.

  • Invalidate Immediately: Revoke the key in the provider's dashboard (AWS, OpenAI, Supabase).
  • Audit Logs: Check the provider's access logs for any unauthorized usage during the window of exposure.
  • Generate High-Entropy Replacements: Use an api key generator or a password generator to create new credentials. Do not reuse old passwords or slightly modified versions of the leaked key.
  • Update CI/CD: Ensure the new keys are updated in your GitHub Actions, Vercel, or Netlify environment settings.

How To Transition To A Dedicated Secret Manager

The ultimate goal for any professional application is to move away from .env files entirely.

Cloud-Native Managers

Services like AWS Secrets Manager, Azure Key Vault, and Google Secret Manager allow your application to fetch credentials at runtime. The application authenticates via its IAM role (identity-based) rather than using a "master secret" to get other secrets.

HashiCorp Vault

For platform-agnostic needs, HashiCorp Vault is the gold standard. It supports dynamic secrets, where it can generate a unique, short-lived database credential for every application instance, automatically revoking it when the instance shuts down.

Vibe-Coding Specific Risks

If you are using Lovable, Bolt, or v0, ensure you are using their native "Secrets" or "Environment Variables" UI rather than letting the AI write secrets into the code.

How To Audit Your App For Exposed Secrets Automatically

Manual checking is insufficient for modern development speeds. You need automated layers of defense.

Pre-commit Hooks

Install tools like trufflehog or gitleaks as pre-commit hooks. These tools scan your staged changes for high-entropy strings or known API key patterns and will block the git commit command if a secret is detected.

External Scanning with SimplyScan

While pre-commit hooks catch leaks *before* they happen, an external scan catches what actually reached the web. SimplyScan's security scanner performs 51+ automated checks in ~30 seconds. It specifically looks for:

  • Exposed .env or .git directories.
  • API keys leaked in frontend JavaScript bundles.
  • Missing security headers that could lead to credential theft via XSS.

For developers using Cursor or Windsurf, SimplyScan provides a "hacker's eye view" that identifies if the AI accidentally bundled a SUPABASE_SERVICE_ROLE_KEY into your production build · a critical error that grants full database bypass.

How To Verify Your Environment Is Clean

After the cleanup, use these tools to ensure no remnants remain:

  • Exposed Files Check: Use an exposed files tool to verify that your .env file is not accessible via https://yourdomain.com/.env.
  • Email Security: Ensure your domain's SPF/DKIM/DMARC records are set up so that attackers cannot spoof your domain to phish for new secrets.
  • Uptime and Monitoring: Set up uptime monitoring to ensure that your history-rewriting didn't break your CI/CD pipeline or production deployment.

---

Summary of Remediation Steps:

  • Rotate: Revoke the old key and generate a new one using an api key generator.
  • Scrub: Use git filter-repo to purge the string from all branches and tags.
  • Protect: Update your .gitignore using a generator.
  • Migrate: Move to a managed secret service to achieve no secrets in env vars.
  • Scan: Run a SimplyScan report to confirm your production site is clean.

By following this rigorous process, you ensure that your "vibe-coded" application is not just fast to build, but secure to scale. Whether you are deploying on Vercel or Netlify, keeping secrets out of Git and environment variables is the first step toward professional-grade security.

---

FAQ

How do I know if my .env file was pushed to GitHub?

You can check your repository's file list on GitHub, but more importantly, check the commit history. Even if the file isn't in the latest version, it might be in an older commit. Use a secret scanner or search the repository's history for the filename. If found, you must rotate all keys contained in that file immediately because GitHub's public events are indexed by attackers in real-time.

Can I just delete the commit that contained the secret?

No, simply deleting a commit or "reverting" it creates a new commit that undoes the changes, but the original commit with the secret still exists in the Git database. You must use a tool like BFG Repo-Cleaner or git filter-repo to rewrite the history and physically remove the data from the repository's objects. This is the only way to ensure the data is gone.

Is it safe to use environment variables on Vercel or Netlify?

Platforms like Vercel and Netlify provide a "Settings" UI to input environment variables. This is significantly safer than committing a .env file because the values are encrypted at rest and only injected into the build process. However, you should still ensure these variables aren't accidentally leaked to the frontend code during the build, which is a common issue in React or Next.js apps.

What is the difference between a secret and an environment variable?

Environment variables are a mechanism for passing configuration to a program. Secrets are a specific type of configuration that must remain private, such as passwords or keys. While all secrets can be environment variables, not all environment variables (like LOG_LEVEL or PORT) are secrets. The goal is to handle secrets with more care than standard configuration strings.

Does SimplyScan detect secrets in my frontend code?

Yes, SimplyScan's automated engine performs checks for exposed API keys and sensitive strings that may have been accidentally bundled into your frontend JavaScript. This is a common issue in AI-built apps where the LLM might hardcode a Supabase service role key or an OpenAI key directly into a component. SimplyScan identifies these in ~30 seconds without requiring a signup.

Should I use a .env file for production?

It is generally discouraged to use .env files in production. Most production environments should use a Secret Manager or inject variables directly into the process manager (like systemd or Kubernetes). If you must use a .env file, ensure it is located outside the web root and has restricted filesystem permissions (e.g., chmod 600). Use a chmod calculator to verify.

Frequently asked questions

How do I know if my .env file was pushed to GitHub?

You can check your repository's file list on GitHub, but more importantly, check the commit history. Even if the file isn't in the latest version, it might be in an older commit. Use a secret scanner or search the repository's history for the filename. If found, you must rotate all keys contained in that file immediately because GitHub's public events are indexed by attackers in real-time.

Can I just delete the commit that contained the secret?

No, simply deleting a commit or "reverting" it creates a new commit that undoes the changes, but the original commit with the secret still exists in the Git database. You must use a tool like BFG Repo-Cleaner or git filter-repo to rewrite the history and physically remove the data from the repository's objects. This is the only way to ensure the data is gone.

Is it safe to use environment variables on Vercel or Netlify?

Platforms like Vercel and Netlify provide a "Settings" UI to input environment variables. This is significantly safer than committing a .env file because the values are encrypted at rest and only injected into the build process. However, you should still ensure these variables aren't accidentally leaked to the frontend code during the build, which is a common issue in React or Next.js apps.

What is the difference between a secret and an environment variable?

Environment variables are a mechanism for passing configuration to a program. Secrets are a specific type of configuration that must remain private, such as passwords or keys. While all secrets can be environment variables, not all environment variables (like LOG_LEVEL or PORT) are secrets. The goal is to handle secrets with more care than standard configuration strings.

Does SimplyScan detect secrets in my frontend code?

Yes, SimplyScan's automated engine performs checks for exposed API keys and sensitive strings that may have been accidentally bundled into your frontend JavaScript. This is a common issue in AI-built apps where the LLM might hardcode a Supabase service role key or an OpenAI key directly into a component. SimplyScan identifies these in ~30 seconds without requiring a signup.

Should I use a .env file for production?

It is generally discouraged to use .env files in production. Most production environments should use a Secret Manager or inject variables directly into the process manager (like systemd or Kubernetes). If you must use a .env file, ensure it is located outside the web root and has restricted filesystem permissions (e.g., chmod 600). Use a chmod calculator to verify.

Related guides

  • Environment Variables Security: Stop Leaking Secrets to Production · Environment variables only protect secrets when used correctly. Any variable prefixed VITE_, NEXT_PUBLIC_, or REACT_APP_ is embedded in your JavaScript bundle and readable by every visitor. Keep API keys, service role keys, and database URLs server-side without a public prefix and verify your bundle contains no secrets.
  • How to Find Exposed Secrets in Your Code Before They Ship · Exposed secrets hide in three predictable places: frontend bundles, git history, and misprefixed .env files. Grep your code and built output for known prefixes like sk_live_, AKIA, and ghp_, then use an automated secret scanner to catch high-entropy leaks. If you find one, rotate the key immediately to end the exposure.
  • Managing Your Cursor Library: How to Index Code Without Leaking Secrets · Manage your Cursor library by enabling Privacy Mode and using a .cursorignore file to exclude sensitive data. While indexing improves AI context, it can leak secrets if hardcoded keys are included. Use SimplyScan to detect exposed credentials before they are indexed into the LLM context window.
  • 60 Free Security & Developer Tools Every Vibe Coder Should Bookmark · Sixty free, no-signup tools cover the security and visibility gaps AI app generators leave behind. These include live checks for SSL, security headers, and exposed .env files, plus browser-local utilities like JWT debuggers and secret scanners. Run these checks after every deploy to ensure your vibe-coded app is production-ready.

All security guides · Free security tools · Platform scanners · Security checklist