NODE_ENV is an environment variable that is commonly used in Node.js applications, including those built with the Express framework. It helps you determine the current environment in which your application is running, such as development, production, or testing. It’s used to configure your application’s behavior based on the environment, allowing you to have different settings, behavior, and optimizations for different stages of development and deployment.

Here’s how to use NODE_ENV in Express in a step-by-step manner with an example:

Step 1: Set NODE_ENV

Open a terminal.

Set the NODE_ENV environment variable to a specific value, such as “development” or “production”.

For Unix-like systems (Linux, macOS):

export NODE_ENV=development

For Windows:

set NODE_ENV=development

Step 2: Create an Express Application

Install Express if you haven’t already:

npm install express
Create a file named app.js (or any other name you prefer).

Import and create an Express application in the file:

const express = require('express');
const app = express();

Step 3: Configure Environment-Specific Behavior

Based on the value of NODE_ENV, configure different behaviors for different environments. Commonly, you’d set up database connections, logging, error handling, etc.

For example, configure a database connection differently in different environments:

if (process.env.NODE_ENV === 'production') {
  // Configure production database connection
} else {
  // Configure development/testing database connection
Use environment-specific middleware or settings, such as logging or error handling:

if (process.env.NODE_ENV === 'production') {
  // Enable production logging settings
} else {
  // Enable development logging settings

Step 4: Start the Express Application

Add route handlers and application logic as needed for your project.

Start the Express server:

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port} in ${process.env.NODE_ENV} mode`);

Step 5: Run the Application

Start your Express application:

node app.js

Open a web browser and navigate to http://localhost:3000 (or the port you’ve specified).

Step 6: Changing Environment

If you want to switch to a different environment, modify the NODE_ENV environment variable and restart the server.

For example, if you set NODE_ENV=production, the server will run in production mode and use the appropriate configurations and optimizations.

Using NODE_ENV helps you create flexible, maintainable, and optimized Express applications that adapt to different environments. Remember that the steps above provide a general guideline for using NODE_ENV in Express applications. The exact configuration and behaviors may vary based on your specific project requirements.

You can also use other different .env variables by creating a .env file and can use a package like ‘dotenv’ to read those files in your node.js application.

Support On Demand!