how NODE_ENV variable works
process.env.NODE_ENV
is an environment variable used in Node.js and various JavaScript environments to indicate the current execution environment of the application. It is commonly used to differentiate between various stages of the development lifecycle, such as development, testing, and production.
Purpose of process.env.NODE_ENV
-
Environment-Specific Configuration:
- Allows you to configure your application differently based on whether it’s running in development, testing, or production. For example, you might use a different API endpoint or database configuration depending on the environment.
-
Optimization:
- Many tools and frameworks use
NODE_ENV
to enable or disable certain features or optimizations. For example, in React, whenNODE_ENV
is set to"production"
, it will enable production optimizations and disable development features.
- Many tools and frameworks use
-
Conditional Code Execution:
- You can write conditional code that only runs in specific environments. This is useful for logging, debugging, or enabling specific features.
Common Values
"development"
: Used during development when debugging and development-specific tools are enabled."production"
: Used in the production environment where the application is deployed for end-users, often with optimizations and minimized code."test"
: Used during testing phases, where you might need specific configurations or test-specific data.
Setting process.env.NODE_ENV
-
In Node.js Applications: You can set
NODE_ENV
in your command line or script when starting the application.Example:
NODE_ENV=production node app.js
-
In Scripts: When running scripts in
package.json
, you can setNODE_ENV
inline.Example:
"scripts": { "start": "NODE_ENV=production node app.js", "dev": "NODE_ENV=development node app.js" }
-
In CI/CD Pipelines: You can configure
NODE_ENV
through environment settings in your CI/CD platform.Example for GitHub Actions:
jobs: build: runs-on: ubuntu-latest env: NODE_ENV: production steps: - name: Checkout code uses: actions/checkout@v2 - name: Install dependencies run: npm install - name: Build run: npm run build
Using NODE_ENV
in Your Code
You can access process.env.NODE_ENV
in your Node.js application to conditionally execute code based on the environment:
Example in JavaScript/Node.js:
if (process.env.NODE_ENV === 'production') {
// Production-specific code
console.log('Running in production mode');
} else if (process.env.NODE_ENV === 'development') {
// Development-specific code
console.log('Running in development mode');
} else if (process.env.NODE_ENV === 'test') {
// Test-specific code
console.log('Running in test mode');
}
In Frontend Development
For frontend frameworks like React, NODE_ENV
is used to conditionally include or exclude development features:
React Example:
if (process.env.NODE_ENV === 'development') {
// Code or debugging tools only for development
console.log('Development mode');
}