Storing secrets like database credentials and JWT secrets securely is essential to keeping your Node.js web application safe. Here’s a best-practices approach to storing and managing such secrets:
✅ 1. Use Environment Variables
The most common and secure way to store secrets is via environment variables. These can be loaded in different ways based on your deployment strategy.
# Example .env file (NEVER commit this file to version control)
DB_HOST=localhost
DB_USER=mydbuser
DB_PASSWORD=s3cr3t
JWT_SECRET=supersecretjwtkey
In your Node.js app, use a library like dotenv to load them:
npm install dotenv
In your app:
require('dotenv').config();
const dbHost = process.env.DB_HOST;
const jwtSecret = process.env.JWT_SECRET;
🔐 Security Tips:
- Never commit
.env files to source control (Git). Add them to .gitignore.
- Use different
.env files for development, staging, and production.
- Use secret managers in production environments.
✅ 2. Use a Secret Manager for Production
Instead of (or in addition to) .env files in production, use a managed secret store like:
These services allow you to:
- Rotate secrets automatically.
- Control access using IAM roles.
- Audit access logs.
Use the respective SDK to fetch the secret at runtime or preload them into environment variables during container/image boot time.
✅ 3. Docker & Kubernetes Secrets (For Containerized Apps)
If you're using Docker:
# Dockerfile
ENV DB_USER=myuser
ENV DB_PASSWORD=${MY_DB_PASSWORD}
Run container with secrets:
docker run -e MY_DB_PASSWORD=supersecret myapp
In Kubernetes, use Secrets:
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
DB_USER: bXl1c2Vy # base64 encoded
DB_PASSWORD: c3VwZXJzZWNyZXQ= # base64 encoded
Mount them as environment variables or files in your pod.
✅ 4. Version Control Considerations
- Always add
.env to .gitignore
- Consider having a
.env.example for reference (without secrets)
# .gitignore
.env
# .env.example
DB_HOST=
DB_USER=
DB_PASSWORD=
JWT_SECRET=
✅ 5. Bonus: Validate Required Secrets on Startup
Use a library like joi or custom logic to validate that all required secrets are loaded.
if (!process.env.JWT_SECRET) {
throw new Error('Missing JWT_SECRET environment variable!');
}
In Summary:
| Environment | Secret Storage Method |
|---|
| Local Dev | .env with dotenv (and in .gitignore) |
| Production | Environment variables via Secret Manager or orchestrator |
| Docker/K8s | Docker ENV / Kubernetes Secrets |
| CI/CD | Store secrets in CI/CD environment config (e.g., GitHub Actions, GitLab CI Variables) |
Let me know your deployment environment (e.g., local, Docker, AWS, etc.), and I can give more specific advice!