Loading lesson path
Concept visual
This page covers the key differences between development and production environments in Node.js applications and best practices for managing both effectively.
The NODE_ENV Environment Variable In Node.js, the NODE_ENV environment variable is a convention used to determine the environment in which an application is running. It's commonly set to either 'development' or 'production', though other values like 'test' or 'staging' are also used.
Many Node.js frameworks and libraries (like Express, React, Vue, etc.) use NODE_ENV to enable or disable certain features and optimizations. Setting NODE_ENV
Formula
# Windows Command Prompt set NODE_ENV = production node app.js# Windows PowerShell $env:NODE_ENV="production" node app.js
Formula
# Linux/macOS
export NODE_ENV = production node app.js package.json Scripts{
"scripts": {Formula
"start": "NODE_ENV = production node app.js",
"dev": "NODE_ENV = development nodemon app.js",
"test": "NODE_ENV = test jest"}
}Formula
Using cross - env (cross - platform)
npm install -- save - dev cross - env{
"scripts": {Formula
"start": "cross - env NODE_ENV = production node app.js"}
}Using NODE_ENV in Your Application
// Simple environment check const isProduction = process.env.NODE_ENV === 'production';
const isDevelopment = !isProduction;
// Environment-specific configuration const config = {
port: process.env.PORT || 3000, db: {Formula
host: isProduction ? 'prod - db.example.com' : 'localhost', name: isProduction ? 'myapp_prod' : 'myapp_dev'}, logging: {
level: isProduction ? 'warn' : 'debug', prettyPrint: !isProduction
}
};
// Express.js example const express = require('express');
const app = express();NODE_ENV=production can improve application performance by up to 35%, as some packages apply optimizations based on this setting.
Different environments typically require different configurations for databases, APIs, logging, and other services.
// Install dotenv: npm install dotenv require('dotenv').config(); // Loads .env file contents into process.env
// config.js module.exports = {
development: {
port: 8080, database: 'mongodb://localhost:27017/myapp_dev', logLevel: 'debug', apiKeys: {thirdPartyService: process.env.DEV_API_KEY
}
}, test: {
port: 3001, database: 'mongodb://localhost:27017/myapp_test', logLevel: 'info', apiKeys: {thirdPartyService: process.env.TEST_API_KEY
}
}, production: {
port: process.env.PORT || 8080, database: process.env.DATABASE_URL, logLevel: 'error', apiKeys: {thirdPartyService: process.env.PROD_API_KEY
}
}
};
const env = process.env.NODE_ENV || 'development';
module.exports.current = module.exports[env];Common approaches to configuration management include:
Using.env files with the dotenv package