Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. Using command line: You can specify the NODE_ENV variable on the command line when starting your application, like this:
NODE_ENV=production node app.js
  1. Using a configuration file: You can create a configuration file (.env or .json) and set the NODE_ENV variable there:
// .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'
  1. Using a package manager: Some package managers, such as npm and yarn, allow you to specify the NODE_ENV variable in scripts in your package.json file:
// 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.