1 | initial version |
NODE_ENV is an environment variable that specifies the environment in which your Node.js application is running, such as development, production, or testing. It is commonly used to configure different behaviors of an application depending on the environment it is running in.
There are different ways to apply NODE_ENV in Express:
NODE_ENV=production node app.js
// .env file
NODE_ENV=development
// config.json file
{
"NODE_ENV": "production"
}
You can then load the configuration file in your application and use it to set the NODE_ENV variable:
// app.js
require('dotenv').config() // load .env file
const config = require('./config.json') // load config file
process.env.NODE_ENV = process.env.NODE_ENV || config.NODE_ENV || 'development'
// package.json
{
"scripts": {
"start": "NODE_ENV=production node app.js"
}
}
You can then run your application with npm start or yarn start.
Overall, setting the NODE_ENV variable is a best practice for your Node.js application because it allows you to easily configure different behaviors and improve its maintainability.