Intermediate·16 min read·Updated 2026-10-15

Secrets Management for Web Apps: Keys, Env Vars & Rotation

Original WeSecureX guide for authorized testing of sites you own. Linked Sources are citations for verification - not copied articles. Ads are not served on this page.

Application secrets - including database passwords, API integration tokens, JWT signing keys, and TLS private certificates - represent the keys to your enterprise infrastructure. Inadvertently hardcoding secrets inside source code repositories or baking them into client-side browser bundles is a leading cause of catastrophic cloud account takeovers. Effective Secrets Management requires establishing operational safeguards across the entire developer workflow: from local development and git commits to CI/CD pipelines and cloud production deployments. This guide details secret storage patterns, zero-trust injection, automated pre-commit scanning, and key rotation workflows integrated with the [WeSecureX Surface Engine](/surface) and [Automated Vulnerability Scanner](/scanner). Read our blog on [The Anatomy of a Data Breach](/blog/the-anatomy-of-a-data-breach-how-attackers-find-and-exploit-vulnerabilities).

Quick Answer

Never commit secrets to version control or expose them in browser bundles. Use cloud secret managers (AWS Secrets Manager, HashiCorp Vault) for production runtime injection, enforce git pre-commit scanning with TruffleHog, mandate OIDC short-lived credentials in CI/CD pipelines, and implement automated key rotation.

Key Takeaways
  • Secrets in git history remain vulnerable until revoked and rotated.
  • Frontend JavaScript bundles are public; server credentials must remain strictly backend-only.
  • Use OIDC role assumption in CI pipelines instead of static AWS access keys.
  • Implement dual-key signing rotation to update credentials without dropping active user sessions.
Visual Diagram · Zero-Trust Cloud Secrets Injection & Lifecycle Pipeline
1

1. Pre-Commit Guard

Git hook scans code changes for API keys and entropy patterns before commits enter local version control.

2

2. OIDC Authentication

CI/CD build pipeline authenticates to Cloud IAM using short-lived OIDC tokens (no long-lived AWS keys).

3

3. KMS Secret Injection

Production container fetches encrypted secrets directly into process RAM at container boot time.

4

4. Automated Rotation

Cloud KMS rotates database credentials and signing keys on a 30-day automated schedule without downtime.

ShareShare on XLinkedIn

1. Categorizing Sensitive Application Credentials

WeSecureX Free Tools Directory showing security diagnostic utilities
WeSecureX Free Tools Directory showing security diagnostic utilitiesWeSecureX Platform View

Engineering teams must establish rigorous data classification standards that clearly differentiate between public application configuration parameters and sensitive cryptographic credentials. A frequent point of failure occurs in modern JavaScript frameworks (like Next.js, Nuxt, or Vite) that bundle environment variables during client builds.

Variables prefixed for client exposure (such as NEXT_PUBLIC_STRIPE_KEY or VITE_FIREBASE_KEY) are baked directly into minified JavaScript bundles delivered to visitor web browsers. If a developer accidentally prefixes a private database connection string or private Stripe secret key with NEXT_PUBLIC_, that credential is fundamentally compromised the moment code is deployed to production. Server-side secrets must remain strictly un-prefixed, ensuring they are compiled exclusively for server execution environments.

In addition, master credentials like AWS Root Account keys or production database passwords must never reside in local .env files on developer laptops. Local development should utilize scoped, temporary test credentials or local containerized mock services. Audit your external attack surface for exposed environment variables using WeSecureX Surface Recon and learn how credential leaks escalate into data breaches in our Data Breach Anatomy Guide.

Credential CategoryExample PrimitiveExposure ImpactMandatory Storage Location
Server Master SecretsDatabase passwords, AWS Root Keys, Private SSH keysComplete cloud account takeoverHashiCorp Vault / AWS Secrets Manager
Application Auth KeysJWT Private Signing Keys, Session Encryption KeysSession forgery & user impersonationCloud KMS / Sealed Environment Vars
Third-Party API TokensStripe Secret Key, SendGrid API Key, Twilio TokenUnauthorized financial charges & data theftManaged Secret Store (Server-Only)
Public Client KeysStripe Publishable Key, Firebase API KeyPublic client interactionFrontend bundle (Domain Restricted)

2. Runtime Injection & Secret Manager Architecture

WeSecureX Scanner detecting exposed secrets, environment variables, and git leaks
WeSecureX Scanner detecting exposed secrets, environment variables, and git leaksWeSecureX Platform View

Storing secrets in plain text inside version control or baking .env files into Docker images represents a critical security antipattern. Even if a file is deleted in a subsequent Docker build step or git commit, intermediate container layers and git history retain the secret indefinitely, allowing anyone with pull access to extract credentials.

In modern cloud-native architectures, production containers retrieve credentials dynamically at boot time from centralized Key Management Services (such as AWS Secrets Manager, Google Cloud Secret Manager, or HashiCorp Vault). The application reads secrets directly from in-memory environment variables (process.env.DATABASE_URL), ensuring credentials never touch persistent disks.

Furthermore, implement pre-commit hooks on developer workstations using tools like TruffleHog or Gitleaks. These hooks evaluate regex patterns and Shannon entropy mathematics across staged code changes, blocking git commits that contain accidental private keys, AWS access tokens, or connection strings before they reach remote repositories. Check your repositories for exposed secrets using the WeSecureX Website Scanner.

bash
# Production TruffleHog Pre-Commit Scanning Script (.git/hooks/pre-commit)
#!/bin/bash
echo "Running automated pre-commit secret entropy scan..."

# Run TruffleHog binary on git staged changes
trufflehog git file://. --since-commit HEAD --only-verified --fail

if [ $? -ne 0 ]; then
  echo "CRITICAL ERROR: High-entropy secret detected in staged commit!"
  echo "Aborting commit. Please remove hardcoded credentials before pushing."
  exit 1
fi

3. Automated Secret Rotation & Incident Revocation

WeSecureX Surface Recon mapping exposed assets and infrastructure perimeters
WeSecureX Surface Recon mapping exposed assets and infrastructure perimetersWeSecureX Platform View

Static credentials left un-rotated for months or years eventually leak through developer workstation compromises, build logs, or employee offboarding. A mature security posture requires establishing automated credential rotation pipelines.

Dual-Key Signing Rotation: For JWT session signing keys, webhook secrets, or API tokens, maintain a dual-key configuration array ([currentKey, previousKey]). During a scheduled 7-day transition window, verification middleware accepts signatures signed by either key, while the authentication service issues all new tokens strictly with currentKey. This eliminates downtime and prevents active user sessions from being abruptly logged out.

Emergency Revocation Protocol: If a production secret is exposed in a public repository (e.g., via a GitHub Push Protection alert), treat the credential as immediately compromised. Automatically revoke the key via cloud provider APIs, trigger an emergency deployment with rotated credentials in AWS Secrets Manager, and audit cloud trail access logs for unauthorized API calls. Continuously monitor your external perimeter with the WeSecureX Surface Monitor.

Apply it with WeSecureX

Add a hostname you own or are allowed to test, run a scan, and open the findings for that target. A confirmed result includes the request WeSecureX sent and the response the site returned, so you can reproduce it, fix it in your own application, and rescan the same host to confirm the issue is gone. WeSecureX is automated testing, not a manual penetration test, and a clean report is not a promise that every weakness is gone.

Checks that belong with this topic

  • Enable TruffleHog or GitLeaks pre-commit secret scanning hooks.
  • Store production credentials inside AWS Secrets Manager or HashiCorp Vault.
  • Use OIDC short-lived credentials for CI/CD cloud deployments.
  • Ensure NEXT_PUBLIC_ frontend environment variables contain zero server secrets.
  • Automate 30-day rotation schedules for database passwords and API keys.
  • Audit environment integrations inside [WeSecureX Surface Recon](/surface).

Actionable Checklist

WeSecureX Platform · Surface Monitor

Application Attack Surface Analyzer

Inspect open ports, TLS certificate chains, HTTP headers, and API endpoint security posture.

Includes: TLS/SSL cipher suite & expiration monitoring · Security header verification (CSP, HSTS) · Subdomain asset discovery

Frequently Asked Questions

Revoke and rotate the secret immediately in your provider dashboard. Simply deleting the file in a new commit does NOT remove it from git history; attackers scan public commits in real time.

Environment variables separate code from deployment configuration. This allows the exact same compiled container binary to run in dev, staging, and production environments with different credentials injected at runtime.

OpenID Connect (OIDC) allows your CI/CD runner (e.g., GitHub Actions) to authenticate directly to AWS or GCP by exchanging a short-lived JSON Web Token, eliminating the need to store long-lived AWS Access Key IDs in repository secrets.

Dual-key rotation allows the backend server to accept signatures signed by either the old key or the new key during a transition window, granting users time to receive newly signed tokens seamlessly.

Scanners analyze code syntax, regular expressions, and Shannon entropy math to identify high-entropy strings matching known key patterns (e.g., `sk_live_...`, `AKIA...`). Audit your repositories with the [WeSecureX Scanner](/scanner).

Authoritative Sources & References

  • OWASP Secrets Management Cheat SheetOWASP (official)
    View Source
  • NIST SP 800-57: Recommendation for Key ManagementNIST (official)
    View Source

Continue exploring related technical architecture and defensive guides

Security Research & Engineering Articles

All articles