Node.js Setting NODE_ENV="production"


Production deployments will vary in many ways, but a standard convention when deploying in production is to define an environment variable called NODE_ENV and set its value to "production".

Runtime flags

Any code running in your application (including external modules) can check the value of NODE_ENV:

if(process.env.NODE_ENV === 'production') {
    // We are running in production mode
} else {
   // We are running in development mode


When the NODE_ENV environment variable is set to 'production' all devDependencies in your package.json file will be completely ignored when running npm install. You can also enforce this with a --production flag:

npm install --production

For setting NODE_ENV you can use any of these methods

method 1: set NODE_ENV for all node apps

Windows :

set NODE_ENV=production

Linux or other unix based system :

export NODE_ENV=production

This sets NODE_ENV for current bash session thus any apps started after this statement will have NODE_ENV set to production.

method 2: set NODE_ENV for current app

NODE_ENV=production node app.js

This will set NODE_ENV for the current app only. This helps when we want to test our apps on different environments.

method 3: create .env file and use it

This uses the idea explained here. Refer this post for more detailed explanation.

Basically you create .env file and run some bash script to set them on environment.

To avoid writing a bash script, the env-cmd package can be used to load the environment variables defined in the .env file.

env-cmd .env node app.js

method 4: Use cross-env package

This package allows environment variables to be set in one way for every platform.

After installing it with npm, you can just add it to your deployment script in package.json as follows:

"build:deploy": "cross-env NODE_ENV=production webpack"