Understanding Environment Variables in Node.js
SkillVeris Team
Engineering Team

Environment variables are external key-value settings that Node.js reads through process.env, keeping configuration and secrets out of your source code.
In this guide, you'll learn:
- They let one codebase behave differently across development, staging, and production without changing a line of code.
- A .env file stores local variables, and the dotenv package loads them into process.env when the app starts.
- Never commit .env files or secrets to Git — add them to .gitignore and provide a safe .env.example instead.
- All process.env values are strings, so you must convert numbers and booleans yourself.
1What Are Environment Variables?
Environment variables are configuration values that live outside your code, in the environment the process runs in. In Node.js you read them through the process.env object, so a database URL or API key becomes process.env.DATABASE_URL rather than a hardcoded string in a source file.
They exist to separate configuration from code. The same application can point at a local database in development and a managed one in production simply by changing the environment it runs in — no code edits, no rebuilds, and no secrets baked into the repository.
2Why Use Environment Variables?
Beyond secrets, environment variables solve the general problem of things that differ between machines and stages of deployment.
- Security: keep API keys, tokens, and passwords out of source control.
- Portability: the same code runs unchanged across dev, staging, and production.
- Flexibility: toggle features or switch endpoints without a redeploy of code.
- Collaboration: teammates supply their own local values without sharing real secrets.
🔑Config Belongs in the Environment
A widely followed principle is to store anything that varies between deploys — credentials, hostnames, ports — in the environment, not in the code.
3Reading process.env
Node.js exposes every environment variable on the global process.env object. Reading one is as simple as accessing a property, and it is good practice to provide a fallback for optional values so the app still starts if a variable is missing.
- const port = process.env.PORT || 3000
- const dbUrl = process.env.DATABASE_URL
- const isProd = process.env.NODE_ENV === 'production'
- console.log(`Running on port ${port}`)
4Using .env Files with dotenv
Setting variables by hand on every run is tedious, so most projects keep local configuration in a .env file and load it with the dotenv package. Calling dotenv.config() early in your entry file reads the file and populates process.env before the rest of your code runs.
- npm install dotenv
- require('dotenv').config() // load .env at startup
- # .env file contents:
- PORT=4000
- DATABASE_URL=postgres://localhost/mydb
- API_KEY=sk-local-example-key
Load It First
Call dotenv.config() at the very top of your application, before any module that reads process.env. If you load it too late, those modules see undefined values because the file had not been parsed yet.
5Keeping Secrets Out of Git
The whole point of a .env file is defeated if you commit it. Add .env to .gitignore so it never enters version control, and commit a .env.example listing the required keys with placeholder values so teammates know what to provide.
- # .gitignore
- .env
- .env.local
- # .env.example (safe to commit)
- PORT=3000
- DATABASE_URL=
- API_KEY=
⚠️A Committed Secret Is a Leaked Secret
Once a key lands in Git history it is exposed even after you delete it, because the history retains it. If it happens, rotate the credential immediately rather than just removing the file.
6Types and Validation
Every value in process.env is a string, always. If you read a port or a feature flag, you must convert it yourself, and it pays to validate that required variables exist at startup so the app fails fast with a clear message rather than crashing mysteriously later.
- const port = Number(process.env.PORT) // string to number
- const debug = process.env.DEBUG === 'true' // string to boolean
- if (!process.env.DATABASE_URL) {
- throw new Error('DATABASE_URL is required')
- }
7Environment Variables in Production
In production you generally do not ship a .env file. Instead, the hosting platform, container orchestrator, or CI system injects variables directly into the process environment. Docker, cloud platforms, and Kubernetes all provide their own mechanisms for supplying secrets securely.
This keeps production credentials separate from your codebase and from developer machines. A managed secrets store or the platform's environment settings becomes the single place real keys live, and dotenv is used only for local development convenience.
8Best Practices
A short checklist keeps environment configuration safe and maintainable.
- Always add .env to .gitignore and commit a .env.example instead.
- Validate required variables at startup so misconfiguration fails loudly.
- Convert strings to the types you need rather than using them raw.
- Use uppercase, underscore-separated names by convention (DATABASE_URL).
- Inject production secrets through the host or a secrets manager, not a file.
9Key Takeaways
Environment variables are the standard way to configure Node.js apps.
- process.env exposes every environment variable to your code.
- A .env file plus dotenv loads local configuration at startup.
- Never commit .env; use .gitignore and a .env.example template.
- All values are strings, so convert and validate them.
- Supply production secrets through the platform, not a shipped file.
10Frequently Asked Questions
Q: What is process.env in Node.js? A: process.env is a global object that holds all environment variables available to the running process as key-value pairs. You read configuration and secrets from it, for example process.env.PORT, and every value it returns is a string.
Q: Do I need the dotenv package? A: Not strictly — you can set variables in your shell or through your hosting platform. dotenv is a convenience for local development that loads a .env file into process.env so you do not have to export each variable manually.
Q: Why should I not commit my .env file? A: It usually contains secrets like API keys and database passwords. Committing it exposes them to anyone with repository access and leaves them in Git history even after deletion. Add .env to .gitignore and rotate any key that slips through.
Q: Why are my numeric environment variables behaving like strings? A: Because every process.env value is a string. Reading process.env.PORT gives '3000', not 3000, so you must convert it with Number() or parseInt() before doing arithmetic or comparisons.
Related Reading
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Engineering Team
Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.