How to Check and Set the NODE_ENV Environment Variable and Its Use in a Project

YuZou
2 min readMar 7, 2024

When developing web applications, adjusting the behavior of the application based on the environment it is running in (such as development, testing, or production) is a common practice. The NODE_ENV environment variable is widely used in Node.js applications to indicate the current running environment. This article will guide you on how to check and set the NODE_ENV environment variable and demonstrate its application in a project through a practical code example.

Example Code

Consider the following configuration code snippet in a Node.js project:

let API_URL;
if (process.env.NODE_ENV === 'development') {
// Development environment
API_URL = 'https://www.tgt8.xyz/boardrop';
} else if (process.env.NODE_ENV === 'production') {
// Production environment
API_URL = 'http://www.BoarDrop.com.cn/boardrop';
} else {
// Default or testing environment
API_URL = 'https://www.tgt8.xyz/boardrop';
}
export const config = {
API_URL,
};

In this example, based on the value of NODE_ENV, we decide which server the API URL will point to. This method allows for easy switching between configurations in different environments without altering the code.

Checking the Current Value of NODE_ENV

1. Checking in the Command Line

Unix-like Systems (Linux/macOS):

  • Open the terminal and input:
  • echo $NODE_ENV
  • This will display the current value of NODE_ENV. If it is not set, you may not see any output.

Windows Systems:

  • Open Command Prompt or PowerShell and input:echo %NODE_ENV%
  • This will display the value of NODE_ENV. If it is not set, it will show %NODE_ENV%.

2. Checking in a Node.js Application

Create a new JavaScript file (e.g., checkEnv.js) and add the following code:

console.log(process.env.NODE_ENV);

Run this script:

node checkEnv.js

This will output the current value of NODE_ENV to the console. If it is not set, the output will be undefined.

Setting the NODE_ENV Environment Variable

Temporary Setting

  • Unix-like Systems:
export NODE_ENV=development
  • Windows Systems:set NODE_ENV=development

Persistent Setting

  • Unix-like Systems: Add to ~/.bashrc, ~/.bash_profile, or ~/.profile file:export NODE_ENV=developmen
  • Save the file and execute source ~/.bashrc (or the respective file name) to apply the changes.
  • Windows Systems: Set through the Environment Variables setting in System Properties.

Conclusion

Through the steps described above, you can easily manage your environment variables to ensure your application runs in the correct environment. Additionally, you can see how to set different configurations in a project based on different environments. This is a very practical skill that can help developers better manage and maintain their applications.

--

--