Environment variables
Environment variables are named settings the operating system passes to your program.
In this page:
Syntax
KEY=value node app.js
const value = process.env.KEY || 'default';
Environment variables
Configuration that changes between machines, such as ports, URLs and secrets, belongs in environment variables rather than code. Read them from process.env, provide defaults, and validate at start-up so the app fails fast when something is missing.
Note:
Fail fast at start-up if required variables are missing.
Example: Environment variables
process.env.APP_PORT = "8080";
const config = {
port: Number(process.env.APP_PORT || 3000),
debug: process.env.DEBUG === "true",
mode: process.env.NODE_ENV || "development",
};
console.log(config);
const required = ["DATABASE_URL"];
console.log("missing:", required.filter((k) => !process.env[k]));
// Output:
// { port: 8080, debug: false, mode: 'development' }
// missing: [ 'DATABASE_URL' ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Hard-coding secrets
- Forgetting values are strings
- Not validating at start
Chapter Summary
- Config comes from the environment
- Read via process.env
- Provide defaults
- Validate on start-up
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: