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.

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.
Related

How to Get the Project Root Path in Node.js When working with large Node.js projects, you often need to find the root directory at runtime…

15 Oct, 2025

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Writing to files is a common task in Node.js, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs…

07 Oct, 2025