Keep files and secrets out of Git (.gitignore)
careful beginner #gitignore#env#secrets#node_modules
When to use this: You must not commit node_modules, .env, build output, or secrets, or you already did.
Be careful with this one. Anything pushed to GitHub, even briefly, must be treated as exposed. Rotate any leaked key.
Before you start
Steps
-
Add patterns to `.gitignore`
PowerShellGit BashAdd-Content .gitignore "node_modules/" Add-Content .gitignore ".env" Add-Content .gitignore "dist/"printf 'node_modules/\n.env\ndist/\n' >> .gitignoreOr edit the file by hand. Ignore rules only affect files Git is not tracking yet.
-
Check a file is ignored
terminalgit check-ignore -v .envPrints the rule that ignores it. No output means it is not ignored.
-
Stop tracking a file that was already committed
terminalgit rm -r --cached node_modules--cachedremoves it from Git only, and leaves your local copy. Commit and push the removal. -
Commit the change
terminalgit add .gitignore git commit -m "Stop tracking ignored files"From now on those paths stay out of Git.
How to verify it worked
git statusdoes not list the ignored paths.
How to undo it
To track a file again, delete its rule from .gitignore and run git add <file>.
Common errors and fixes
A secret was already pushed Step 1: revoke or rotate the key in the provider's dashboard (this is the only real fix). Step 2: remove it from the repo and future commits. Step 3: only if needed, scrub history with
git filter-repo, knowing the old value must be considered public. .gitignore does nothing for a file The file is already tracked. Run git rm --cached <file> once. Q&A
Where should secrets live for a Vercel site?
In Vercel's Environment Variables settings and a local .env.local that is gitignored. vercel env pull copies them to your PC.
Should package-lock.json be ignored?
No. Commit the lockfile so Vercel installs the same versions as your PC.