Node.js Environment Variables

Keep secrets and settings out of your code.

✍️ 2 exercises in this lesson

Configuration such as ports, database URLs and API keys belongs in environment variables, not in your source code.

  • Read them with process.env.PORT.
  • Store local values in a .env file and load it with node --env-file=.env app.js (Node 20+) or the dotenv package.
  • Never commit .env; add it to .gitignore and share a .env.example without real secrets.

Key Takeaways: Node.js Environment Variables

Mastering Node.js Environment Variables helps you write clean and reliable Node.js code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Node.js Environment Variables Code Example

Node.js
// .env
// PORT=4000
// DB_URL=mysql://root@localhost/shop

// server.js  →  node --env-file=.env server.js
const port = Number(process.env.PORT) || 3000;
const dbUrl = process.env.DB_URL ?? "not configured";

console.log("Port:", port);
console.log("Database:", dbUrl);
Output
Port: 4000
Database: mysql://root@localhost/shop
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Node.js Environment Variables Practice Exercises

Check what you learned in “Node.js Environment Variables”.

/ 2 solved
Fill in the blank

Read the PORT environment variable.

const port = .PORT || 3000;
✓ Correct! Not quite. Try again.
Multiple choice

Should .env files be committed to Git?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services