Secrets management
- Node.js course
- Advanced
- Lesson 71/83
- 5 min
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.
Practice Read the API_KEY
Enable dotenv. Read the API key with const apiKey = process.env.API_KEY. Print apiKey with console.log.
Starter code
// Enable dotenv
// write here
// Read the API_KEY variable
// write here
// Print apiKey
// write hereSample solution
require("dotenv").config();
const apiKey = process.env.API_KEY;
console.log(apiKey);Expected output
test-key
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the .gitignore line
____
.env
Explanation: .env is added to .gitignore.
2 Match each tool to its role
| Term | Meaning |
|---|---|
AWS Secrets Manager |
AWS secrets tool |
HashiCorp Vault |
Open-source secrets tool |
.env + .gitignore |
Development method |
process.env.API_KEY |
Access from code |
3 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 Correct answer
- In log files
Explanation: A password is kept in an env variable or a secrets tool.