Environment Configuration
๐ Covered in this chapter:
process.env ยท .env Files ยท --env-file ยท Config Validation ยท Never Hard-Coding Secrets
Manage configuration and secrets across development and production using environment variables and .env files.
1Environment Configuration โ What You'll Learn
Manage configuration and secrets across development and production using environment variables and .env files.
Here's everything this chapter covers, in the order you'll learn it:
- What environment variables are
- process.env
- .env files for local development
- Node's native --env-file flag
- Development vs production variables
- Managing secrets safely
- Validating required environment variables at startup
- Environment-specific configuration
- Why you should never hard-code secrets in source code
2Working Example
๐ป Example: Environment Configuration
Terminal
โถ Run in Compiler
node --env-file=.env app.js
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Node.js LTS supports the --env-file flag and process.loadEnvFile() natively โ you often don't need the dotenv package anymore.
- Always validate that critical environment variables (DATABASE_URL, JWT_SECRET, etc.) exist at startup, and crash loudly if they're missing rather than failing silently later.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about environment configuration?
Focus on: process.env ยท .env Files ยท --env-file ยท Config Validation ยท Never Hard-Coding Secrets. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for environment configuration?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.