KKAIROSافتح التطبيق
Practical guideTested1 min read

Keeping API keys out of a Git repository from day one

Most key leaks happen in the very first commit, before anyone thinks about ignore rules. Set up three files before your first commit: the real values in .env, a .gitignore that lists it, and a .env.example with empty values for teammates.

Published:

Advertisement

Scope: prevention in a new repository. A file that is already tracked is page 13, and a key that is already committed is pages 15 and 16.

How do I keep API keys out of a Git repository from the first commit?

Put the real values in .env, add it with printf ".env\n" >> .gitignore, and commit only an empty .env.example.

How do I check that .env will not be committed?

This is a check, not a fix: git ls-files lists only tracked files, so .env must be missing from that list. Run it before the first push.

Tested commands and output

Command: printf ".env\n" >> .gitignore; git ls-files

$ echo API_KEY=sk-test-FAKE123 > .env
$ printf ".env\n" >> .gitignore
$ echo API_KEY= > .env.example
$ git add -A
$ git commit -qm init
$ git ls-files
.env.example
.gitignore
$ git check-ignore -v .env
.gitignore:1:.env	.env

Note

Add the .env line to .gitignore before git add, or the file is staged anyway.

Source: https://stackoverflow.com/questions/21774844/proper-way-to-hide-api-keys-in-git (Stack Overflow question this page answers) Source: https://git-scm.com/docs/gitignore (gitignore docs) Source: https://stackoverflow.com/questions/44342276/how-to-push-code-to-github-hiding-the-api-keys (Related Stack Overflow question)

Full kit: Secrets Safety Kit