World map

 

BM: Baca dalam Bahasa Melayu

World 8: Shields: Security

Never commit secrets

You will learn: how to keep keys and passwords out of your commits.

The problem

cat .env shows one line: API_KEY=fake_demo_key_123. Then git status -s lists two new files: .env and app.js. Terminal output: $ cat .env API_KEY=fake_demo_key_123 $ git status -s ?? .env ?? app.js

Your diary gets a weather widget. It needs a key, kept in .env. One careless git add ., and the key is in your history.

Watch

git add . sweeps both app.js and .env into the box. .env carries a not-ready warning tag.

A secret: A password, API key or token. Whoever has it can get in. is like a house key. API keys, passwords and tokens are all secrets. git add . grabs everything, secrets too.

Watch

The line .env is added to .gitignore. Now git status -s lists .gitignore and app.js. .env is gone from the list. Terminal output: $ echo ".env" >> .gitignore $ git status -s M .gitignore ?? app.js

Add one line to your .gitignore: A file that lists things Git should never save.. Now Git acts like .env isn’t there. Two arrows, >>, add a line and keep the old ones.

Try it

Secret, or safe to commit? Sort each one.

Drag a card into a box. Or tap the card, then tap the box.

      Try it

      Hide .env from Git. Then put everything else in the box.

      Working folder
      Staging area
      • Empty
      Repository
      • 3 save points
      • Ignore log files
      • Add day 1 page
      • Add README

      Files (5)
      • .env
      • .gitignore
      • README.md
      • app.js
      • index.html

      Predict

      .env is in .gitignore now. You type git add .env on purpose. What happens?

      Pick one answer.

      Check

      Secrets hide in code too, not only in .env. Good, or needs work? Swipe each one.

      Swipe right for good, left for needs work. Or use the buttons.

      1 / 4

      const key = process.env.API_KEY;

      `const key = process.env.API_KEY;`

      You did it!

      You can now keep secrets out of your commits.

      Go deeper (optional)

      A .env.example file lists the key names with empty values, like API_KEY=. Teammates copy it to .env and add their own keys. Ignore .env before your very first commit. Then a careless git add . can never grab it.

      After adding .env to .gitignore, it holds two lines: *.log and .env. git add . puts only .gitignore and app.js in the box. Terminal output: $ echo ".env" >> .gitignore $ cat .gitignore *.log .env $ git add . $ git status On branch main Changes to be committed: (use "git restore --staged <file>..." to unstage) modified: .gitignore new file: app.js