DevAcademy
LearnNode.jsEnvironment Variables
IntermediateNode.js

Environment Variables

Keep configuration and secrets out of your code using environment variables and .env files.

Reading Time

10 min

Lesson

Lesson 23 of 34

Why Not Hardcode Config?

A database URL or API key hardcoded directly in your source code means every environment (local, staging, production) needs a different copy of the code — and worse, secrets end up committed to version control. Environment variables solve both problems.

Reading Environment Variables

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Using dotenv for Local Development

npm install dotenv

Loading a .env File

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Where Variables Come From, by Environment

EnvironmentTypical Source
Local developmentA .env file, loaded by dotenv
CI/CD pipelineSecrets configured in the CI provider's settings
Production (containers)Injected by the orchestrator (Docker, Kubernetes) at runtime

Never Commit .env to Version Control

A .env file containing real secrets should always be listed in .gitignore. Commit a .env.example instead, listing the variable names (with placeholder or no values) so teammates know what to configure.

Best Practice

Validate required environment variables at startup (throw early if something critical is missing) rather than discovering a missing DATABASE_URL only when the first database query fails at runtime.

Interview Questions

Quick Quiz

1. Why avoid hardcoding secrets directly in source code?

2. What does the dotenv package do?

3. Should a .env file containing real secrets be committed to version control?