</>
Skip to content
Node.js lessons (24/44)

Node.js — Environment Variables

Accessing Environment Variables

console.log(process.env.NODE_ENV);
console.log(process.env.PORT);
console.log(process.env.DATABASE_URL);

Setting Environment Variables

# In terminal
export NODE_ENV=production
export PORT=3000

# Inline
PORT=3000 node app.js

# Windows
set NODE_ENV=production

dotenv Package

npm install dotenv
// Load at top of app
require('dotenv').config();

// Use variables
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;

.env File

NODE_ENV=development
PORT=3000
DATABASE_URL=postgres://localhost/mydb
API_KEY=your-secret-key

.env.example

NODE_ENV=
PORT=
DATABASE_URL=
API_KEY=

Best Practices

PracticeDescription
Never commit .envAdd to .gitignore
Use .env.exampleDocument required vars
Validate on startupCheck required vars exist
Provide defaultsFallback values

Mini Practice

  1. Set environment variables
  2. Use dotenv package
  3. Create .env file
  4. Validate environment on startup

Up Next

Continue with Error Handling — handling errors gracefully.

Related Topics

Frequently Asked Questions about Environment Variables

What is Environment Variables in Node.js?

Environment Variables is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Environment Variables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Environment Variables.

Why is Environment Variables important in Node.js?

Environment Variables is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.