NODE_ENV Variables and How to Use Them ?
Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicates whether the server is running on development or production mode. The express framework checks the flag value in the runtime and sets value depending on the environment.
Setting NODE_ENV Variable: Setting up the NODE_ENV variable depends on the operating system and also on the user’s setup.
To set the environment variable globally to some value, we can run the code from the command line.
For Linux and Mac Operating System:
export NODE_ENV = production
For Windows Operating System
$env:NODE_ENV = 'production'
We can also apply the environment variable in the application initialization command using the code below assuming we are running a script called app.js.
NODE_ENV = production node app.js
In Windows, the code is different. We use the code below:
set NODE_ENV=production&&node app.js
Because different operating systems require different command, there is a package available called cross-env which makes the command cross-platform.
npx cross-env NODE_ENV=production node app.js
The above code will work on any platform where the cross-env package is installed as a developer dependency.
If we are using express, we can provide environment-specific settings that are automatically called based on the environment we are working on.
Suppose our database server is the localhost when we are working on development mode and we’ll be using https://production-server.com for production. The code can be set accordingly.
The above code will check the environment and will set it’s server accordingly.
Conclusion: Use of the production environment is a good practice because in the production environment, usually logging is kept minimum also more caching levels take place for optimized performance. So, it is always a good practice to set up the environment variable to production mode whenever we are deploying our app to the production server.
Please Login to comment...