🟢 Node.js Q37 / 118

What is environment variable in Node.js?

AI-Powered Answer ✓ Answered

Environment variables are a crucial aspect of configuring and securing Node.js applications. They provide a way to inject configuration settings into an application from the environment in which it runs, rather than hardcoding them within the application's source code. This approach is fundamental for building twelve-factor apps and handling different deployment environments.

What are Environment Variables?

Environment variables are dynamic named values that can affect the way running processes will behave on a computer. They are part of the operating system's environment and can be accessed by any application or process running within that environment. In the context of Node.js, they are typically used for configuration settings that vary between environments (e.g., development, testing, production) or for storing sensitive information like API keys and database credentials.

The primary benefits of using environment variables include increased security (by keeping sensitive data out of source code), flexibility (easily changing configuration without modifying code), and adherence to modern application development practices.

Accessing Environment Variables in Node.js

Node.js provides built-in support for accessing environment variables through the process.env global object. This object is a dictionary (JavaScript object) where keys are the names of the environment variables and values are their corresponding string values.

javascript
const port = process.env.PORT || 3000;
const dbUser = process.env.DB_USER;
const apiKey = process.env.API_KEY;

console.log(`Application running on port: ${port}`);
console.log(`Database User: ${dbUser}`);

if (apiKey) {
  console.log('API Key is set.');
} else {
  console.log('API Key is NOT set.');
}

It's common practice to provide a fallback value (e.g., using the || operator) for non-critical environment variables, ensuring your application can still run if a specific variable isn't set.

Setting Environment Variables

Temporarily (Shell)

You can set environment variables directly in your shell before running your Node.js application. These variables will only be available to processes launched from that shell session.

bash
# Linux / macOS
PORT=4000 DB_USER=myuser node app.js

# Windows (Command Prompt)
set PORT=4000
set DB_USER=myuser
node app.js

# Windows (PowerShell)
$env:PORT=4000
$env:DB_USER='myuser'
node app.js

Using a .env file (Recommended for Development)

For local development, managing numerous environment variables through the command line can be cumbersome. The dotenv package allows you to load environment variables from a .env file into process.env.

bash
npm install dotenv

Create a file named .env in the root of your project:

plaintext
PORT=5000
DB_USER=dev_user
DB_PASS=dev_password
API_KEY=my_secret_dev_key

Then, at the very top of your main application file (e.g., app.js or server.js), require and configure dotenv:

javascript
require('dotenv').config();

const port = process.env.PORT;
const dbUser = process.env.DB_USER;

console.log(`Server running on port: ${port}`);
console.log(`Database User: ${dbUser}`);

Common Use Cases

  • Database Connection Strings: Storing URLs, usernames, and passwords for databases.
  • API Keys and Secrets: Safely managing credentials for third-party APIs.
  • Port Numbers: Specifying which port the server should listen on.
  • Application Environment: Differentiating between development, production, and test environments (e.g., NODE_ENV).
  • Feature Flags: Toggling application features on or off without redeploying code.
  • Third-Party Service URLs: URLs for external services that might differ per environment.

Best Practices

  • Never hardcode sensitive data: Always use environment variables for passwords, API keys, and other secrets.
  • Use .env for local development: It provides a convenient way to manage local configuration.
  • Do NOT commit .env to version control: Add .env to your .gitignore file to prevent exposing sensitive information.
  • Provide clear variable names: Use descriptive and consistent naming conventions (e.g., DB_HOST, API_KEY).
  • Use production-grade solutions for deployment: On production servers, leverage your hosting provider's mechanisms for managing environment variables (e.g., Heroku Config Vars, AWS Secrets Manager, Kubernetes Secrets) instead of .env files.
  • Validate environment variables: Ensure critical environment variables are set at startup and provide meaningful error messages if they are missing.