Environment Variables — Complete Guide
Environment Variables — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Node.js Tutorial on Toolliyo Academy.
On this page
Environment Variables
This lesson covers Environment Variables. Think of this lesson as a short workshop you can run on your laptop.
What you will learn
- What environment variables means — in normal words, not textbook words
- How it works step by step
- Code you can run today on your laptop
- Where teams use this in real projects
Before you start
- Software: Node.js LTS from nodejs.org, VS Code, and a terminal
- Knowledge: Lessons 1–9 in this course
- Previous lesson: Process Object — Complete Guide
Explain it simply
Environment variables store settings outside your code — database URLs, API keys, port numbers.
Why developers use this
- Keep secrets out of git
- Change config per machine without editing code
- Standard practice in Docker and cloud
How it works (step by step)
- You write JavaScript in a
.jsfile about Environment Variables. - You run it with
node filename.jsin the terminal. - Node prints output or starts a server depending on the lesson.
- You change one line, run again, and see what changed — that is how you learn.
Code example — type this yourself
require('dotenv').config();
const port = process.env.PORT || 3000;
console.log('Listening on', port);
Create a .env file with PORT=4000. dotenv loads it into process.env. Never commit .env to git.
What each part does
require('dotenv').config();— Loads a built-in module or package you installed with npm.const port = process.env.PORT || 3000;— Reads config from environment variables — safe place for secrets.console.log('Listening on', port);— Prints to the terminal — great for learning; use proper logging in production.
Real life: where Environment Variables shows up
A startup team uses Environment Variables when they bootstrap their first API. The developer runs a small script on a laptop, stores config in .env, and splits code into modules before the app grows. Start small: one feature working beats a perfect architecture on paper.
Try it yourself — hands-on
- npm install dotenv
- Create .env with PORT=4000
- Run your script and confirm the port logs
Common mistakes (avoid these)
- Pushing API keys to GitHub — rotate them immediately if that happens.
Interview note
Interviewers often ask: “What is Environment Variables?” Answer in one sentence, then give a tiny example you actually ran.
Summary
- Store secrets in .env, not in source code
- Use process.env.PORT with a default
- Add .env to .gitignore
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!