tezvyn:

How does NODE_ENV=production change Express behavior?

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

understanding environment-specific optimizations and conventions.

OUTLINE

NODE_ENV is a convention signal, production disables verbose logging and enables caching.

CONVENTION-DRIVEN BEHAVIOR

NODE_ENV is an environment variable that signals which environment the code is running in. The convention is 'development' for local, 'test' for testing, and 'production' for live. Express and many npm packages check process.env.NODE_ENV and adjust behavior accordingly. This is a convention, not a hard rule, but it is widely respected.

EXPRESS OPTIMIZATIONS

When NODE_ENV is set to 'production', Express automatically enables view caching, so templates are compiled once and reused. In development, templates are recompiled on every request to pick up changes, which is convenient but slow. Response compression is enabled by default in production. Stack traces in error responses are hidden in production, showing only error messages. In development, full stack traces are logged.

LOGGING REDUCTION

Many applications check NODE_ENV to adjust logging verbosity. In development, logs are verbose, showing request details, database queries, and debug info. In production, logs are minimal, focusing only on errors and critical events. This reduces log volume and improves performance.

DEPENDENCY BEHAVIOR

Libraries throughout the ecosystem (Morgan logging middleware, many caching libraries) check NODE_ENV. They often disable expensive debugging features in production. Some dependencies use NODE_ENV to skip assertions or remove stack traces entirely.

NEEDED SETUP

Before starting a production app, run: export NODE_ENV=production (Linux/Mac) or set NODE_ENV=production (Windows cmd) or in a systemd service file. Without this, the app thinks it is in development and misses all optimizations. A common mistake is to set NODE_ENV in application code like app.set('env', 'production'), which doesn't affect process.env and doesn't propagate to dependencies.

PERFORMANCE IMPACT

Setting NODE_ENV=production can improve throughput by 2-5x due to view caching and logging reduction alone. Compression adds more benefit. Missing this single environment variable is a surprising source of production performance issues.

Read the original → expressjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.