Menu
×
   ❮     
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Node.js Tutorial

Node HOME Node Intro Node Get Started Node JS Requirements Node.js vs Browser Node Cmd Line Node V8 Engine Node Architecture Node Event Loop

Asynchronous

Node Async Node Promises Node Async/Await Node Errors Handling

Module Basics

Node Modules Node ES Modules Node NPM Node package.json Node NPM Scripts Node Manage Dep Node Publish Packages

Core Modules

HTTP Module HTTPS Module File System (fs) Path Module OS Module URL Module Events Module Stream Module Buffer Module Crypto Module Timers Module DNS Module Assert Module Util Module Readline Module

JS & TS Features

Node ES6+ Node Process Node TypeScript Node Adv. TypeScript Node Lint & Formatting

Building Applications

Node Frameworks Express.js Middleware Concept REST API Design API Authentication Node.js with Frontend

Database Integration

MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert Into MySQL Select From MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join
MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit MongoDB Join

Advanced Communication

GraphQL Socket.IO WebSockets

Testing & Debugging

Node Adv. Debugging Node Testing Apps Node Test Frameworks Node Test Runner

Node.js Deployment

Node Env Variables Node Dev vs Prod Node CI/CD Node Security Node Deployment

Perfomance & Scaling

Node Logging Node Monitoring Node Performance Child Process Module Cluster Module Worker Threads

Node.js Advanced

Microservices Node WebAssembly HTTP2 Module Perf_hooks Module VM Module TLS/SSL Module Net Module Zlib Module Real-World Examples

Hardware & IoT

RasPi Get Started RasPi GPIO Introduction RasPi Blinking LED RasPi LED & Pushbutton RasPi Flowing LEDs RasPi WebSocket RasPi RGB LED WebSocket RasPi Components

Node.js Reference

Built-in Modules EventEmitter (events) Worker (cluster) Cipher (crypto) Decipher (crypto) DiffieHellman (crypto) ECDH (crypto) Hash (crypto) Hmac (crypto) Sign (crypto) Verify (crypto) Socket (dgram, net, tls) ReadStream (fs, stream) WriteStream (fs, stream) Server (http, https, net, tls) Agent (http, https) Request (http) Response (http) Message (http) Interface (readline)

Resources & Tools

Node.js Compiler Node.js Server Node.js Quiz Node.js Exercises Node.js Syllabus Node.js Study Plan Node.js Certificate

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 System path for executable lookup /usr/local/bin:/usr/bin
HOME User's home directory /Users/username

Note: Always provide default values when accessing environment variables to prevent undefined values in your application.


Setting Environment Variables

There are several ways to set environment variables for your Node.js application, depending on your development workflow and deployment environment.

1. Command Line (Temporary)

Set variables directly in the command line when starting your application:

Windows (Command Prompt)

set PORT=3000
set NODE_ENV=development
set DB_HOST=localhost
node app.js

Windows (PowerShell)

$env:PORT=3000
$env:NODE_ENV="development"
node app.js

macOS/Linux (Bash/Zsh)

PORT=3000 NODE_ENV=development DB_HOST=localhost node app.js

macOS/Linux (Multiple Lines)

export PORT=3000
export NODE_ENV=development
node app.js

2. Using .env Files with dotenv

For development, use a .env file to store environment variables locally:

1. Install dotenv package

npm install dotenv

2. Create a .env file

# .env
PORT=3000
NODE_ENV=development
DB_HOST=localhost
DB_USER=admin
DB_PASS=your_secure_password
API_KEY=your_api_key_here

3. Load .env in your application

// Load environment variables from .env file
require('dotenv').config();

const port = process.env.PORT || 3000;
const dbConfig = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASS
};

console.log(`Server running on port ${port}`);

Important: Never commit .env files to version control. Add .env to your .gitignore file.

3. Production Environment Variables

In production, set environment variables using your hosting provider's configuration:

Heroku

heroku config:set NODE_ENV=production DATABASE_URL=your_database_url

Docker

docker run -e NODE_ENV=production -e PORT=3000 your-image

Linux/Systemd Service

# /etc/systemd/system/your-app.service
[Service]
Environment="NODE_ENV=production"
Environment="PORT=3000"

Using dotenv for Local Development

The dotenv package lets you load environment variables from a .env file:

# .env file
API_KEY=abcdef12345

Load the variables in your app:

require('dotenv').config();
console.log(process.env.API_KEY);

Install dotenv with:

npm install dotenv

Summary

Environment variables help you keep sensitive data and configuration out of your code.

Use process.env and tools like dotenv to manage them easily in Node.js.


Exercise?What is this?
Test your skills by answering a few questions about the topics of this page

Drag and drop the correct object name.
In Node.js, environment variables are accessed via .env
global
process
system
node




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.