NODE_ENV is the standard environment variable that signals which environment your app is running in: development, test, or production. Use it to load different configuration values and control behaviour like logging level or debug output.
Node.js
Beginner
8 min read
Config Management and NODE_ENV
Example
// config/index.js — centralised config module
require('dotenv').config();
const config = {
development: {
port: process.env.PORT || 3000,
db: { host: 'localhost', port: 5432, name: 'myapp_dev' },
logLevel: 'debug',
debug: true,
},
test: {
port: process.env.PORT || 3001,
db: { host: 'localhost', port: 5432, name: 'myapp_test' },
logLevel: 'error',
debug: false,
},
production: {
port: process.env.PORT || 8080,
db: {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT, 10),
name: process.env.DB_NAME,
},
logLevel: 'warn',
debug: false,
},
};
const env = process.env.NODE_ENV || 'development';
if (!config[env]) {
throw new Error(`Unknown NODE_ENV: ${env}`);
}
module.exports = config[env];
// Usage in other files:
// const config = require('./config');
// console.log(config.db.host);
// console.log(config.port);