Node.js
Secrets management
Learn secrets management and secure storage.
Secrets
Secrets are sensitive data like passwords, API keys, certificates. They must never be embedded in code; they should always be read from environment variables or a secrets management tool. Leaking them into version control is a major security hole.
Example: const apiKey = process.env.API_KEY;. API_KEY is kept in a .env file; .env is added to .gitignore. In production, secrets are managed with tools like AWS Secrets Manager or HashiCorp Vault. The code never contains the password directly. If a password is accidentally embedded in code and committed, it stays in history; so the password must be rotated immediately. Secrets management is the foundation of secure app development.
Secrets management tools
In production, secrets are not in a .env file but in a central tool. Popular tools: AWS Secrets Manager, HashiCorp Vault, Google Secret Manager. The app pulls secrets from this tool at startup.
Example: pulling a secret from AWS Secrets Manager is usually const client = new AWS.SecretsManager(); const secret = await client.getSecretValue({ SecretId: "my-app" }).promise();. Vault has a similar API. These tools encrypt secrets, control access and make rotation easier. In systems with many services, each service has its own secret; central management makes this easy. .env is only used in development, never in production.
Exercise Read the API_KEY
Enable dotenv. Read the API key with const apiKey = process.env.API_KEY. Print apiKey with console.log.
Show example solution
require("dotenv").config();
const apiKey = process.env.API_KEY;
console.log(apiKey);
Test yourself
-
Complete the .gitignore line
____
Show answer
.env
-
Match each tool to its role
- AWS Secrets Manager
- AWS secrets tool
- HashiCorp Vault
- Open-source secrets tool
- .env + .gitignore
- Development method
- process.env.API_KEY
- Access from code
-
Where should a password be kept?
const apiKey = process.env.API_KEY
- In version control
- Directly in source code
- In an env variable or a secrets tool
- In log files
Show answer
In an env variable or a secrets tool — A password is kept in an env variable or a secrets tool.
Next lesson: Summary - Configuration