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

  1. Add patterns to `.gitignore`

    PowerShellGit Bash
    Add-Content .gitignore "node_modules/"
    Add-Content .gitignore ".env"
    Add-Content .gitignore "dist/"printf 'node_modules/\n.env\ndist/\n' >> .gitignore

    Or edit the file by hand. Ignore rules only affect files Git is not tracking yet.

  2. Check a file is ignored

    terminal
    git check-ignore -v .env

    Prints the rule that ignores it. No output means it is not ignored.

  3. Stop tracking a file that was already committed

    terminal
    git rm -r --cached node_modules

    --cached removes it from Git only, and leaves your local copy. Commit and push the removal.

  4. Commit the change

    terminal
    git add .gitignore
    git commit -m "Stop tracking ignored files"

    From now on those paths stay out of Git.

How to verify it worked

  • git status does 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.

Practice these as flashcards →

Terms in this scenario

Related scenarios

My notes

Saved in this browser only.