← Back to Backend, page 3

backend-0050 · Easy fresher

How should a backend service manage secrets (API keys, database passwords, signing keys): where to store them, how to keep them out of code and logs, and how to rotate them?

Keep secrets out of source code and images. Inject them at runtime from environment variables or, better, a secrets manager (a cloud secret store, Vault, Kubernetes secrets with encryption) with access control and audit logs. Give each environment and service its own secrets with the least privilege, never log them (redact), scan repositories for leaks, and rotate regularly and immediately after exposure. Design for rotation by allowing two valid secrets during the change.

Full answer

Storage and delivery

  • Never commit secrets, including in .env files, test fixtures, Docker layers, and CI logs. Use .gitignore and pre-commit and CI secret scanning.
  • Load from the environment or from a secrets manager at start-up (or on demand with caching). The manager gives encryption at rest, fine-grained access, audit trails and versioning. Prefer short-lived credentials (workload identity, database IAM auth) over long-lived passwords.
  • Separate secrets per environment and per service. Production secrets should not be readable from developer laptops or staging.

Handling

  • Validate that required secrets exist on start-up and fail fast with a message that does not print the value.
  • Do not log secrets or whole config objects and request headers. Redact known keys (authorization, password, token, cookie) in logs, errors and traces.
  • Do not pass secrets in URLs or command-line arguments (they appear in process lists and logs).

Rotation

  • Rotate on a schedule and on any suspicion of exposure. Support two active secrets at once (old and new) so that clients and servers can switch without downtime, then retire the old one. Automate it.
  • If a secret leaks to a repository, revoking it is the fix. Removing it from the git history is not enough.
javascript
// 1. Load required secrets at start-up and fail fast without printing values.
function loadConfig(env) {
  const required = ['DATABASE_URL', 'JWT_SIGNING_KEY'];
  const missing = required.filter((name) => !env[name]);
  if (missing.length) throw new Error('missing required secrets: ' + missing.join(', '));
  return { databaseUrl: env.DATABASE_URL, jwtKey: env.JWT_SIGNING_KEY };
}
try { loadConfig({ DATABASE_URL: 'postgres://app:pw@db/app' }); } catch (err) { console.log('1. start-up check      :', err.message); }

// 2. Redact sensitive fields before logging.
const SENSITIVE = /^(authorization|password|token|secret|cookie|api[-_]?key)$/i;
const redact = (value) => Array.isArray(value) ? value.map(redact)
  : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SENSITIVE.test(k) ? '[redacted]' : redact(v)])) : value;
console.log('2. redacted log object :', JSON.stringify(redact({ user: 'asha', headers: { authorization: 'Bearer abc', 'content-type': 'json' }, body: { password: 'hunter2', note: 'hi' } })));

// 3. A simple scanner for secrets that were committed by mistake (patterns for well known example keys).
const patterns = { 'AWS access key id': /\bAKIA[0-9A-Z]{16}\b/, 'private key block': /-----BEGIN (RSA |EC )?PRIVATE KEY-----/, 'password in URL': /:\/\/[^\s:@]+:[^\s@]+@/ };
const sampleFile = 'const key = "AKIAIOSFODNN7EXAMPLE";\nconst url = "postgres://app:s3cret@db.internal/app";\nconst ok = process.env.API_KEY;';
sampleFile.split('\n').forEach((line, i) => { for (const [name, re] of Object.entries(patterns)) if (re.test(line)) console.log(`3. scanner, line ${i + 1}      : ${name}`); });

// 4. Rotation: accept the new and the previous secret during the change.
const crypto = require('node:crypto');
const sign = (secret, data) => crypto.createHmac('sha256', secret).update(data).digest('hex');
const accepted = ['new-secret', 'old-secret'];
const verify = (data, signature) => accepted.some((s) => crypto.timingSafeEqual(Buffer.from(sign(s, data)), Buffer.from(signature)));
const oldSig = sign('old-secret', 'payload'), newSig = sign('new-secret', 'payload');
console.log('4. during rotation     : old signature valid =', verify('payload', oldSig), '| new signature valid =', verify('payload', newSig));
accepted.pop();
console.log('   after retiring old  : old signature valid =', verify('payload', oldSig), '| new signature valid =', verify('payload', newSig));

The example key in the scanner is the well-known fake value from AWS documentation. Each numbered line shows one practice in plain Node. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. start-up check : missing required secrets: JWT_SIGNING_KEY 2. redacted log object : {"user":"asha","headers":{"authorization":"[redacted]","content-type":"json"},"body":{"password":"[redacted]","note":"hi"}} 3. scanner, line 1 : AWS access key id 3. scanner, line 2 : password in URL 4. during rotation : old signature valid = true | new signature valid = true after retiring old : old signature valid = false | new signature valid = true

Key points

  • Do not keep secrets in code, images or logs.
  • Use a secrets manager and least-privilege access.
  • Prefer short-lived credentials.
  • Redact sensitive fields and fail fast on missing config.
  • Rotate regularly with two active secrets during the change.

Common mistakes

  • Committing a .env file or a key to a repository.
  • Logging request headers or the whole config object.
  • One shared secret for every environment.
  • Rotating only after an incident, with no automated process.
  • Putting secrets in build arguments and image layers.

Follow-ups

  • How do you handle a secret that was committed by mistake?
  • What is workload identity and why is it better than a stored key?
  • How does Vault issue dynamic database credentials?

Tips

  • Say 'not in code, not in logs, rotated'.
  • Mention a secrets manager.
  • Describe dual-secret rotation.