Environment Variables in Node.js

From the Express.js cheat sheet · Configuration · verified Jul 2026

Environment Variables

Manage configuration and secrets using environment variables

javascript
// Load environment variables
require('dotenv').config();

// Access variables
const PORT = process.env.PORT || 3000;
const DB_URL = process.env.DATABASE_URL;
const JWT_SECRET = process.env.JWT_SECRET;

// Check required variables
const requiredEnvVars = ['DATABASE_URL', 'JWT_SECRET'];
requiredEnvVars.forEach(varName => {
  if (!process.env[varName]) {
    console.error(`Missing required environment variable: ${varName}`);
    process.exit(1);
  }
});

// Start server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Environment: ${process.env.NODE_ENV}`);
});
💡 Never commit .env files to version control
🔒 Use different secrets for each environment
✅ Validate environment variables on startup
⚡ Use dotenv for local development
Back to the full Express.js cheat sheet