bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Node.js Deployment
Node.js•Node.js Deployment

Node.js Environment Variables

What are Environment Variables?

Environment variables are dynamic named values that can affect how running processes behave on a computer. They are part of the environment in which a process runs and are used to configure applications without changing the code.

Key Benefits:

Store configuration separate from code

Keep sensitive information out of version control

Configure applications differently across environments

Change application behavior without code changes

Common Use Cases

Environment Configuration

Database connection strings

API keys and secrets

External service URLs

Feature flags

Runtime Behavior

Logging verbosity

Port numbers

Timeouts and limits

Environment-specific settings

Accessing Environment Variables in Node.js Node.js provides the process.env object to access environment variables. This object contains all the environment variables available to the current process.

Basic Usage

// Access a single environment variable const nodeEnv = process.env.NODE_ENV || 'development';
console.log(`Running in ${nodeEnv} mode`);
// Access multiple variables with destructuring const { PORT = 3000, HOST = 'localhost' } = process.env;
console.log(`Server running at http://${HOST}:${PORT}`);
// Check if running in production if (process.env.NODE_ENV === 'production') {
console.log('Production optimizations enabled');

// Enable production features

}

Common Built-in Environment Variables

Variable

Description

Example

NODE_ENV Current environment (development, test, production) production

Port

Port number for the server to listen on 3000

Path

Next

Node.js: Development vs Production