How to Remove Sensitive or Large Files From Your Git Repository



This content originally appeared on DEV Community and was authored by Sospeter Mong’are

Accidentally pushing sensitive files like .env or large folders like node_modules to your remote repository is a common mistake. This guide explains how to clean up your Git history and properly ignore these files in future commits.

🔍 Why This Happens

When you initialize a Git repository using git init, Git starts tracking all files by default. If you didn’t set up a .gitignore before your first commit, sensitive files or large folders can get pushed to GitHub or other remote repositories.

This is problematic because:

  • Sensitive files (like .env) may contain API keys or database credentials.
  • Large folders (like node_modules) slow down your repository and make cloning harder.

✅ Step 1: Create a .gitignore

Add a .gitignore file in your project root:

touch .gitignore

Add the following content for a Node.js project:

node_modules/
.env
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.DS_Store
uploads/

This tells Git to stop tracking these files in future commits.

✅ Step 2: Remove Tracked Files

If you already committed these files, removing them from .gitignore alone isn’t enough. You must untrack them:

# Remove from Git index but keep locally
git rm -r --cached node_modules
git rm --cached .env

# Commit changes
git commit -m "Remove node_modules and .env from repository"

# Push changes
git push origin main

This deletes the files from your remote repository but keeps them on your machine.

✅ Step 3: (Optional) Rewrite History to Purge Sensitive Files

If you pushed secrets and need to fully remove them from your repo’s history:

# Install BFG Repo Cleaner
brew install bfg

# Clone your repo
git clone --mirror https://github.com/your-username/your-repo.git
cd your-repo.git

# Remove all .env files from history
bfg --delete-files .env

# Clean and push changes
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --force

Alternatively, use git filter-repo:

pip install git-filter-repo
git filter-repo --path .env --invert-paths

🔒 Best Practices

  • Always create a .gitignore before your first commit.
  • Store sensitive values in a .env file and use environment variables.
  • Consider using GitHub Secrets or similar solutions for CI/CD pipelines.
  • Run git status before committing to verify which files will be pushed.


This content originally appeared on DEV Community and was authored by Sospeter Mong’are