Topic 31 of 55
Environment Access
Overview
Environment variables allow you to configure your application differently across environments (development, testing, production) without changing the code. In Node.js, they are accessed via `process.env`.
Syntax
javascript
// In your terminal:
// PORT=8080 node server.js
// In server.js
const port = process.env.PORT || 3000;
console.log(`Starting server on port ${port}`);
// Outputs: Starting server on port 8080
// Standard convention for environment checks
if (process.env.NODE_ENV === 'production') {
console.log("Running in production mode: Caching enabled.");
} else {
console.log("Running in development mode: Verbose logging enabled.");
}Common Pitfalls
- Remember that all values in `process.env` are strings. `process.env.IS_ADMIN === true` will always be false. You must check `process.env.IS_ADMIN === 'true'`.
- NEVER commit your `.env` files to Git. They contain sensitive secrets. Commit a `.env.example` file instead.
Real-World Example
Using the 'dotenv' package to load variables from a .env file:
example
javascript
// .env file
// DB_HOST=localhost
// DB_USER=root
// DB_PASS=s3cr3t
// app.js
require('dotenv').config(); // Automatically loads .env into process.env
const dbConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS
};
console.log(`Connecting to ${dbConfig.host} as ${dbConfig.user}`);
// Note: Node v20.6+ has built-in support!
// Run with: node --env-file=.env app.js