Node.js, a powerful JavaScript runtime, provides a feature called Environment Variables. These variables help manage configuration settings in different environments like development, testing, and production. In this tutorial, we'll explore the NODE_ENV variable, one of the most commonly used environment variables in Node.js.
š” Pro Tip: Environment variables are user-defined values that can be accessed across your entire application. They help separate configuration settings from your code.
The NODE_ENV variable is a built-in environment variable in Node.js. It's used to determine the current environment (development, testing, or production) and adjust the application's behavior accordingly.
You can set the NODE_ENV variable in three ways:
node app.js --env=productionNODE_ENV variable using process.env.// Set NODE_ENV
process.env.NODE_ENV = 'production';
// Access NODE_ENV
console.log(process.env.NODE_ENV);.env file to keep your code clean and separate configuration settings. To use this method, you'll need a package like dotenv.npm install dotenvIn your .env file:
NODE_ENV=production
In your Node.js application:
require('dotenv').config();
console.log(process.env.NODE_ENV);By default, the NODE_ENV variable is set to 'production'. However, it can take on several values:
development: The application is running in a development environment.test: The application is running in a testing environment.production: The application is running in a production environment.staging: The application is running in a staging environment.Now that you know how to set and access the NODE_ENV variable, let's see how it's used in different environments:
In development, you might want to enable more logging and use development-specific dependencies.
if (process.env.NODE_ENV === 'development') {
console.log('Running in development mode.');
}In production, you'll typically want to minimize logging, optimize your code, and use production-specific dependencies.
if (process.env.NODE_ENV === 'production') {
console.log('Running in production mode.');
}š Note: It's a best practice to keep sensitive information like API keys and database credentials out of your code and in environment variables.
What is the default value of the `NODE_ENV` variable in Node.js?
What are environment variables used for in Node.js?
With this lesson, you now have a good understanding of the NODE_ENV variable and its role in managing environment-specific settings in Node.js applications. Happy coding! š