Environment & Configuration
process.env, dotenv, config modules, and NODE_ENV branching
Skills taught: node.process-env, node.dotenv, node.config-module, node.node-env
process.env and the config pattern
# .env — development only, NEVER commit this file
NODE_ENV=development
PORT=3000
DB_URL=postgres://user:password@localhost:5432/mydb
JWT_SECRET=super-secret-dev-key-change-in-production
ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
LOG_LEVEL=debug
// config.js — single source of truth for configuration
// Run: require('dotenv').config() before importing this
const config = {
env: process.env.NODE_ENV || 'development',
port: parseInt(process.env.PORT || '3000', 10),
db: {
url: process.env.DB_URL,
},
auth: {
jwtSecret: process.env.JWT_SECRET,
jwtExpiresIn: '7d',
},
cors: {
origins: (process.env.ALLOWED_ORIGINS || '').split(',').filter(Boolean),
},
log: {
level: process.env.LOG_LEVEL || 'info',
},
};
// Validate required variables in production
if (config.env === 'production') {
const required = ['DB_URL', 'JWT_SECRET'];
for (const key of required) {
if (!process.env[key]) throw new Error(`Missing required env var: ${key}`);
}
if (config.auth.jwtSecret === 'super-secret-dev-key-change-in-production') {
throw new Error('Change JWT_SECRET before deploying!');
}
}
module.exports = config;
// Usage in other files:
// const config = require('./config');
// app.listen(config.port);
Tip: Always add `.env` to your `.gitignore`. Instead, commit a `.env.example` file with all the variable names but no real values — it documents what config is needed without exposing secrets.
Frequently Asked Questions
How do I use dotenv in a Node.js project?
1. `npm install dotenv`. 2. Create `.env` with KEY=VALUE entries. 3. Add `.env` to `.gitignore`. 4. At the very top of your entry file (before any other requires): `require('dotenv').config()`. Now process.env has all the values from .env. In production, don't use dotenv — set env vars directly in your hosting platform (Render Config Vars, Railway Variables, AWS Parameter Store, etc.).