Environment Config
Adapt your app's behavior to development, test, and production.
Syntax
const isProd = process.env.NODE_ENV === 'production';Apps behave differently across environments. The convention is the NODE_ENV variable, usually set to development, test, or production.
Central config
A good pattern is one config module that reads process.env, applies defaults, and exports a clean settings object the rest of the app imports.
Example
// config.js
module.exports = {
port: Number(process.env.PORT) || 3000,
isProduction: process.env.NODE_ENV === 'production',
dbUrl: process.env.DATABASE_URL || 'localhost:5432'
};
// app.js
const config = require('./config');
console.log('Listening on', config.port);When to use it
- A twelve-factor app reads all configuration from environment variables so the same Docker image can run in dev, staging, and production without code changes.
- A staging environment overrides the `DATABASE_URL` environment variable to point to a shadow database, keeping production data isolated.
- A secrets manager (AWS SSM) injects credentials as environment variables into the ECS task so Node reads them via `process.env` with no secrets in code.
More examples
Centralize config in one module
Centralizes all config in one module that reads from environment variables with sensible defaults.
// config/index.js
require('dotenv').config();
module.exports = {
port: parseInt(process.env.PORT, 10) || 3000,
nodeEnv: process.env.NODE_ENV || 'development',
db: {
url: process.env.DATABASE_URL,
pool: parseInt(process.env.DB_POOL, 10) || 5,
},
};Environment-specific settings
Selects a configuration object keyed by `NODE_ENV` to apply different settings per environment.
const env = process.env.NODE_ENV || 'development';
const configs = {
development: { logLevel: 'debug', dbUrl: 'postgres://localhost/dev' },
test: { logLevel: 'silent', dbUrl: 'postgres://localhost/test' },
production: { logLevel: 'info', dbUrl: process.env.DATABASE_URL },
};
const config = configs[env] || configs.development;
console.log(config.logLevel);Validate required config at startup
Guards the startup sequence by checking all required environment variables and exiting early if any are absent.
const required = ['DATABASE_URL', 'JWT_SECRET', 'SMTP_HOST'];
const missing = required.filter(k => !process.env[k]);
if (missing.length) {
console.error(`Missing env vars: ${missing.join(', ')}`);
process.exit(1);
}
console.log('Config valid -- starting server');
Discussion