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: Node JS Best Practices to Adhere for Enhanced Performance & Security

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.