What is NODE_ENV and How to Use it in Express?

Use NODE_ENV to control Express behavior like logging, error handling, and caching based on dev or prod. Set it via environment variables or cross-env in npm scripts.

Summarize with AI

Not enough time? get the key points instantly.

Problem

You’re building an Express app and want to apply different configs like error handling, caching, logging based on the environment (dev, prod, test). You need a way to know which mode the app is running in.

Solution

By convention, Express and other frameworks read the NODE_ENV environment variable to determine runtime behavior. When not set, process.env.NODE_ENV is undefined, so it’s safer to default to prod logic.

const env = process.env.NODE_ENV;const isDev = env === ‘development’;

if (isDev) {

app.use(require(‘morgan’)(‘dev’));

console.log(‘Running in dev mode’);

}

Alternatively, Express’s built-in method app.get(‘env’) returns the environment (defaulting to ‘development’ if unset). But it’s recommended to use process.env.NODE_ENV directly to avoid silent fallbacks.

Setting NODE_ENV:

Unix/macOS:

export NODE_ENV=production
node app.js

Windows (CMD):

set NODE_ENV=production && node app.js

Also Read:

Cross-platform npm script using cross-env:

npm install cross-env

json

“scripts”: {“start”: “cross-env NODE_ENV=production node app.js”

}

Conclusion

Use process.env.NODE_ENV (or app.get(‘env’) if needed) to know your current environment. This allows different behaviors, optimizations and error handling based on prod or dev modes. Always set the environment explicitly to avoid ambiguity.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…