Secrets management basics
How to keep API keys, database credentials and tokens out of your code and out of attackers' hands.
Overview
A secret is any credential that grants access: API keys, database passwords, tokens, private keys. Leaked secrets are a leading cause of breaches. Good secrets management keeps them out of code and limits the damage if one leaks.
Core rules
- Never commit secrets to source control. Even in a private repo, they end up in history, forks and logs. Add secret files to
.gitignore. - Use environment variables or a secret manager. Load configuration from the environment at runtime; keep the values outside the codebase.
- Never hard-code secrets in client-side code. Anything shipped to a browser or app is public. Keep secret-using calls on the server.
- Don’t paste secrets into third-party tools unless required and disclosed.
Use a secret manager for production
Dedicated secret managers (cloud-native or self-hosted) provide encrypted storage, access control, audit logs and rotation. They’re worth adopting as you grow beyond a single .env file.
Rotate and scope
- Least privilege: each key should have only the permissions it needs.
- Separate keys per environment (dev/stage/prod) and per service.
- Rotate keys periodically and immediately if exposure is suspected.
- Revoke unused keys.
If a secret leaks
- Revoke or rotate it immediately.
- Check logs for misuse.
- Purge it from code/history and investigate how it leaked.
In code examples
All code examples on this site read secrets from environment variables, never literals — for example, reading OPENAI_API_KEY from the environment rather than embedding it. Follow the same habit in your own code.
Related
Last verified: August 2026. Technology and pricing change — always confirm current details with the vendor.