DEV3 Technologies home

DEV3 Developer Forum

How should I handle secrets and API keys in a web project?

General IT0 views
dev3 ·

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?

#security#secrets#devops

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 .env to .gitignore and commit an .env.example with 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: .env files 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

  1. Rotate it immediately (revoke and create a new one).
  2. Check logs for misuse.
  3. Remove it from the code. Rewriting Git history helps but does not undo exposure, so rotation is the real fix.
  4. 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

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.