tezvyn:

NODE_ENV: Flipping the 'Production' Switch

AI-drafted, machine-checkedSource: expressjs.combeginner
NODE_ENV: Flipping the 'Production' Switch

Setting NODE_ENV=production is like telling your Node.js app it's showtime, not rehearsal. This triggers performance optimizations in frameworks like Express, such as view caching and less verbose errors.

WHY IT EXISTS: Node.js applications need a standard way to know whether they are running in a development, testing, or production environment. Different environments have different needs for logging, error handling, and performance. The NODE_ENV environment variable provides this universal, conventional signal.

THE MENTAL MODEL: Think of NODE_ENV as a mode selector on a camera. 'Development' mode gives you all the raw data, debug overlays, and settings to help you compose the shot. 'Production' mode hides the complexity, processes the image for the best final result, and is optimized for speed and quality. Setting NODE_ENV to 'production' tells your app to produce the best, most efficient final result for the end-user.

HOW IT WORKS: NODE_ENV is an environment variable that you set in the shell or configuration of the server where your app runs. Inside your Node.js code, it's accessible via process.env.NODE_ENV. Many popular libraries, including Express, automatically check this value and change their behavior. For example, if NODE_ENV is 'production', Express will cache compiled view templates and generate generic error pages. If it's undefined or set to 'development', it will recompile templates on every request and show detailed stack traces on errors.

WHEN TO USE IT: Always set NODE_ENV=production in any environment that serves live traffic to end-users. This is a non-negotiable best practice for performance and security in any Node.js application, especially those using frameworks like Express. It makes your app faster and prevents leaking sensitive stack traces to the public.

WHEN NOT TO USE IT: Do not set it to 'production' during local development or testing. In development, you want features like detailed error stack traces and disabled caching that production mode turns off. The default behavior (when NODE_ENV is not set to 'production') is what you want for writing and debugging code.

ONE CANONICAL EXAMPLE: To run your app in production mode from a Linux or macOS terminal, you set the environment variable before starting the process: NODE_ENV=production node app.js. In a Dockerfile, you would use the ENV instruction: ENV NODE_ENV production. Most cloud hosting providers like Heroku or Vercel set this for you automatically in your production environment.

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.