axiac@web

How to Use `NODE_ENV` Correctly

What is NODE_ENV?

The NODE_ENV environment variable became popular early in Node.js development as a convention to distinguish between runtime environments like development, testing, and production. It is now widely used and supported across many tools and frameworks in the Node.js ecosystem, allowing developers to implement environment-specific configurations and optimizations.

Unfortunatley, many developers don’t grasp its purpose and use it incorrectly.

Countless projects incorrectly use the environment variable NODE_ENV to specify the name of their environment (like dev, stg, prd, etc.) but the purpose of NODE_ENV is to specify the type of the environment, not its name.
The expected values of NODE_ENV are development, test and production.

Various tools and libraries change their behaviour based on the value of NODE_ENV:

  • when NODE_ENV is set to development, some tools may load additional code to show useful warnings, enable hot reloading and skip optimizations that are not necessary when you are developing the app;
  • when NODE_ENV is set to test, you may want to instrument your code for code coverage;
  • when NODE_ENV is set to production, certain tools may optimize code execution paths, eliminate unused code, and apply optimizations as needed to enhance performance.

How to use NODE_ENV in applications?

The applications should not know in what environment they run. The environment variables should be used to set the configuration values that vary across environments. When behaviour needs to differ across environments, the best way is to use the Strategy design pattern; implement the behaviour that varies in several components that implement the same interface and decide at runtime which of them to use based on the value of a configuration entry (provided as an environment variable). Use different values for the variable based on the environment (or environment type) where the application runs.

As an exception to the rule above, use the value of NODE_ENV in applications to implement optimisations (or skip some costly verifications) when the code run in production and provide better support for developers (in the development mode.)

Comments