Security and Best Practices
You'll learn how to safely handle command-line arguments and environment variables to avoid exposing sensitive information.
The Core Security Concerns
When working with process.argv and process.env, you're dealing with data that can be visible in unexpected places. Command-line arguments appear in process lists (visible to other users on a system), logs, and error messages. Environment variables are safer but still require care.
Never Expose Secrets in argv
Think of command-line arguments like shouting across a crowded room—anyone can hear them. Never pass passwords, API keys, or tokens as arguments:
// ❌ BAD: Visible in process list
// node app.js --apiKey=secret123
// ✅ GOOD: Use environment variables instead
const apiKey = process.env.API_KEY;
Always Sanitize Inputs
Any data from process.argv or process.env comes from outside your program and could be malicious. Validate and sanitize everything:
const port = parseInt(process.env.PORT, 10);
if (isNaN(port) || port < 1 || port > 65535) {
console.error('Invalid port number');
process.exit(1);
}
When to Use Environment Variables vs Arguments
- Environment variables: Secrets, configuration that changes per environment (development/production), sensitive credentials
- Arguments: User commands, file paths, flags that control behavior, non-sensitive options
Think of environment variables as your private notes and arguments as public instructions.
Additional Best Practices
- Never log sensitive environment variables
- Use libraries like
dotenvto load.envfiles (never commit.envto version control) - Validate argument types before using them
- Set sensible defaults for missing values
Key Takeaway: Keep secrets in environment variables, never in command-line arguments; always validate external input before trusting it in your code.