I have API keys and database passwords in a .env file, and once I almost committed it. What is the right way to manage secrets across local, staging and production?
DEV3 Developer Forum
How should I handle secrets and API keys in a web project?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
General IT0 views
dev3 ·
0
1 reply
dev3 ·
Short answer: keep secrets out of the repository, give each environment its own values, restrict who can read them, and assume that anything leaked must be rotated.
Basics
- Never commit secrets. Add
.envto.gitignoreand commit an.env.examplewith placeholder values and no real keys. - Use environment variables or a secrets manager. Read them at runtime; do not hard-code them.
- Separate environments. Development, staging and production use different keys and databases, so a leaked development key cannot touch production.
- Least privilege. Create keys with only the permissions the app needs, such as a database user without admin rights.
Where to store them
- Local:
.envfiles that stay on your machine. - CI/CD: the secret store of your CI provider.
- Production: the host's environment configuration or a dedicated secrets manager, with access limited to people and services that need it.
Prevent accidents
.env
.env.*
!.env.example
Add a pre-commit hook or a secret-scanning tool in CI to catch committed keys.
Client-side exposure
Anything shipped to the browser is public. Public variable prefixes in front-end frameworks expose values to users, so use them only for non-secret values. Call third-party APIs that need secret keys from your server.
If a secret leaks
- Rotate it immediately (revoke and create a new one).
- Check logs for misuse.
- Remove it from the code. Rewriting Git history helps but does not undo exposure, so rotation is the real fix.
- Find out how it leaked and fix the process.
Pitfalls
- Sharing secrets in chat or email.
- One shared admin key for everything.
- Logging request headers or full configuration objects.
Rotate keys on a schedule and when people leave the team.
0