Backend

Secret Management Explained for Backend Developers

Learn secret management for backend apps, including environment variables, secret stores, rotation, least privilege, logging risks, and deployment workflows.

Secret management is the practice of safely creating, storing, using, rotating, and revoking sensitive values that backend systems need to run.

Secrets are easy to scatter across code, logs, dashboards, local machines, CI jobs, and production settings. A good backend design treats them as operational assets, not random strings copied between tools.

Quick answer

Backend secrets should live outside source code, be scoped to the smallest practical permission set, be available only to the services that need them, and be rotated when risk changes.

Common backend secrets include:

  • Database passwords.
  • API keys.
  • OAuth client secrets.
  • JWT signing keys.
  • Webhook secrets.
  • Encryption keys.
  • Cloud provider credentials.
  • SMTP credentials.
  • Third-party payment or analytics tokens.
  • Password hashing peppers.

For small projects, environment variables can be a reasonable starting point. For larger systems, use a managed secret store or cloud secret manager with access controls, audit logs, versioning, and rotation workflows.

What counts as a secret?

A secret is any value that grants access or proves trust.

Examples:

DATABASE_URL=postgres://app:password@db.example.com/app
STRIPE_SECRET_KEY=sk_live_...
JWT_SIGNING_KEY=...
WEBHOOK_SECRET=whsec_...
OAUTH_CLIENT_SECRET=...

Some identifiers look sensitive but are not secrets by themselves. A public client ID, project ID, or API key prefix may be safe to display. The secret portion is what must be protected.

When in doubt, ask: could someone use this value to access data, impersonate a service, sign a token, decrypt data, or change production behavior? If yes, handle it as a secret.

Read API Key Design Best Practices for the difference between visible key identifiers and secret key material.

Where secrets should not live

Do not store production secrets in:

  • Source code.
  • Public repositories.
  • Frontend JavaScript.
  • Static site files.
  • Mobile app bundles when the value must remain secret.
  • Screenshots or docs.
  • Issue trackers.
  • Chat messages.
  • Analytics events.
  • Error messages.
  • Unredacted request logs.

Frontend code cannot keep a secret. Anything shipped to a browser can be inspected by the user. If a credential must remain private, it belongs on the server side.

This is why static tool pages should not contain API credentials. Local browser tools can format JSON, decode JWT payloads, or convert timestamps, but they should not expose private production tokens.

Environment variables vs secret stores

Environment variables are common because they are simple and supported by most hosting platforms.

They work well when:

  • The project is small.
  • The number of secrets is limited.
  • Deployment access is restricted.
  • Rotation is manual but manageable.
  • The platform protects environment configuration.

Secret stores become more useful when:

  • Many services need different secrets.
  • Rotation must be coordinated.
  • Access should be granted per service or role.
  • Audit trails matter.
  • Secrets need versioning.
  • Operators need emergency revocation.

Examples of secret-store capabilities include encrypted storage, access policies, secret versions, audit logs, and integration with cloud identity.

For a Cloudflare Pages or Workers project, keep runtime secrets in platform environment variables or bindings. Do not commit them into the Astro source tree.

Scope secrets with least privilege

A secret should not grant more access than the service actually needs.

Examples:

  • A read-only reporting job should not use a database admin password.
  • A webhook receiver should know only its provider’s webhook secret.
  • A staging app should not use production API credentials.
  • A background worker should not reuse a human administrator token.
  • A public API integration should have route-level or scope-level limits.

Least privilege reduces blast radius. If one service leaks, the attacker should not automatically gain access to every database, queue, bucket, and admin API.

Read Least Privilege Explained for the broader access-control principle.

Rotation and versioning

Secret rotation means replacing an old secret with a new one.

Rotation is needed when:

  • A secret may have leaked.
  • An employee or contractor leaves.
  • A dependency was compromised.
  • A key is old and policy requires renewal.
  • A customer rotates integration credentials.
  • You are moving from test to production.

Rotation is easiest when systems support two active versions during a migration window.

Example webhook rotation:

1. Generate new webhook secret.
2. Configure receiver to accept old and new secrets.
3. Update provider to send signatures with the new secret.
4. Confirm new deliveries verify.
5. Remove the old secret.

Read Webhook Signature Verification for a concrete example of secret rotation around signed events.

Secrets in logs and errors

Secret leaks often happen through observability tools.

Be careful with:

  • Request headers such as Authorization.
  • Query strings that contain tokens.
  • Form bodies.
  • Stack traces.
  • Debug dumps.
  • CI output.
  • Failed validation messages.
  • Third-party error reporting.

Add redaction for common secret fields:

authorization
x-api-key
access_token
refresh_token
client_secret
password
webhook_secret

Logs should preserve useful context without exposing credentials. For example, store an API key ID or prefix, not the full key.

Read Audit Logs Explained for how to keep investigation evidence without turning logs into a secret dump.

Local development and CI

Local development needs secrets too, but the rules should remain boring and predictable.

Use a local .env file only if it is ignored by version control. Keep an example file such as .env.example with placeholder names but no real values.

For CI and deployment:

  • Store secrets in the CI provider’s secret settings.
  • Restrict which branches and jobs can access production secrets.
  • Avoid printing secrets in command output.
  • Use separate staging and production credentials.
  • Rotate secrets when a runner or pipeline is compromised.

Do not give every preview deployment full production access. Preview builds often run untrusted branches, experimental code, or third-party integrations.

Common mistakes

The first mistake is committing secrets to a repository and only deleting them from the latest commit. Once a secret is committed, assume it may have leaked and rotate it.

The second mistake is sharing one broad credential across every service. That makes incident response harder.

The third mistake is using production secrets in local development by default.

The fourth mistake is logging full request headers or environment dumps.

The fifth mistake is exposing “server” secrets to the browser through build-time variables.

The sixth mistake is having no rotation procedure. A secret that cannot be rotated safely becomes operational debt.

Practical recommendation

For a small backend project, start with this baseline:

  • Keep secrets out of source code.
  • Use platform environment variables for deployment.
  • Use .env.example for names only.
  • Separate development, staging, and production secrets.
  • Scope credentials narrowly.
  • Redact secrets from logs and error reports.
  • Record secret lifecycle events in audit logs.
  • Practice rotation before an emergency.

Secret management does not need to be dramatic. It needs to be consistent. Most failures come from copying values into the wrong place and forgetting where they went.

Read Least Privilege Explained for narrowing what each credential can do, Service Accounts Explained for service-owned credentials, and Audit Logs Explained for recording secret lifecycle events safely.

For related backend security topics, read Security Event Logging Explained, API Authentication Best Practices, OAuth Client Credentials Flow Explained, API Key Design Best Practices, Password Hashing Explained, and Webhook Signature Verification. For the full sequence, browse the Backend Security Learning Path and the Topics map.