Environment Variables with process.env
You'll learn how to read configuration and secrets from process.env to keep sensitive data out of your source code.
What Are Environment Variables?
Environment variables are key-value pairs set outside your code—typically in your operating system or hosting platform. They're perfect for storing configuration that changes between environments (development, staging, production) or sensitive data like API keys and database passwords that you don't want committed to version control.
Accessing Environment Variables
In Node.js, process.env is a plain JavaScript object containing all environment variables available to your running process:
// Reading environment variables
console.log(process.env.NODE_ENV); // 'development', 'production', etc.
console.log(process.env.DATABASE_URL); // Connection string
console.log(process.env.API_KEY); // Secret API key
If a variable isn't set, accessing it returns undefined:
const port = process.env.PORT || 3000; // Default to 3000 if PORT not set
Setting Environment Variables
You can set them when running your script:
PORT=8080 NODE_ENV=production node app.js
Or create a .env file (using tools like dotenv, which we'll cover later):
PORT=8080
API_KEY=secret_key_here
NODE_ENV=development
Why This Matters
Think of environment variables as labeled knobs on your application—you can adjust settings without changing the code itself. This keeps your repository clean and secure while allowing each deployment environment to configure itself appropriately.
Key Takeaway: Use process.env to read runtime configuration from environment variables, keeping secrets and environment-specific settings out of your codebase and version control.