← Back to Node.js Course | Chapter 10: Deployment & Best Practices | Lesson 1 of 7

Environment variables

Environment variables are named settings the operating system passes to your program.

In this page:

  1. Environment variables
Syntax
javascript
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

javascript
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
  1. Hard-coding secrets
  2. Forgetting values are strings
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.