dotenv Not Working in Node.js— process.env undefined Fixed [2026]
Also covers: process.env undefined · Node.js environment variable not loading
⚡ Most Common Fix
Move require('dotenv').config() to line 1 — before everything else:
require('dotenv').config() // ← MUST be first
const express = require('express')
const mongoose = require('mongoose')
// now process.env.DATABASE_URL etc. are availableWhy Is dotenv Not Working?
// All of these print undefined:
console.log(process.env.DATABASE_URL) // undefined
console.log(process.env.PORT) // undefined
console.log(process.env.SECRET_KEY) // undefineddotenv loads variables from your .env file into process.envwhen you call require('dotenv').config(). If variables are undefined, one of three things is wrong: config() was called too late, the .env file is in the wrong location, or the .env file format is incorrect.
| Symptom | Cause | Fix |
|---|---|---|
| All env vars undefined | config() called too late | Jump → |
| Some vars undefined | Wrong order / imported after use | Jump → |
| .env exists but vars missing | Wrong .env file location | Jump → |
| Vars have wrong values | .env format error (spaces) | Jump → |
| Works locally not in production | Production doesn't use .env files | Jump → |
Call config() Before Everything Else
Most common fix — call order mattersdotenv only populates process.env when config() is called. Any code that reads process.env before that call sees undefined. Move config() to line 1 of your entry file.
// ❌ WRONG — dotenv called after process.env is already read
const mongoose = require('mongoose')
mongoose.connect(process.env.DATABASE_URL) // undefined!
require('dotenv').config() // too late
// ✅ CORRECT — dotenv on line 1
require('dotenv').config()
const mongoose = require('mongoose')
mongoose.connect(process.env.DATABASE_URL) // populated!Even if you import dotenv in one file and expect it to work in another, config() must still be called in the first file that runs — your app's entry point.
Fix .env File Location
.env must be in project rootBy default, dotenv looks for .env in your current working directory — wherever you run node from, not where your source file lives.
my-project/
.env ← correct location (project root)
package.json
src/
server.js ← your entry file
# Run from project root:
cd my-project
node src/server.js # ← .env found because cwd is my-project// .env in different location
require('dotenv').config({ path: './.env.local' })
require('dotenv').config({ path: require('path').join(__dirname, '../.env') })Fix .env File Format
Wrong format causes undefined or wrong valuesThe .env file format is strict: one variable per line, no spaces around the = sign.
# ✅ CORRECT
DATABASE_URL=mongodb://localhost:27017/mydb
PORT=3000
SECRET_KEY=abc123xyz
# ❌ WRONG — spaces around = sign
DATABASE_URL = mongodb://localhost:27017/mydb
# ✅ String values — quotes are optional but included in value
API_KEY="my-api-key" # value is: my-api-key (without quotes)
API_KEY=my-api-key # value is: my-api-key (same)
# ✅ Multi-word values — no quotes needed
APP_NAME=My Awesome App
# ✅ Comments work
# This is a comment
DATABASE_URL=mongodb://localhost:27017/mydbWhen you write API_KEY="value", dotenv strips the quotes — process.env.API_KEY will be value, not "value". But single-quoted and mismatched quotes can cause unexpected results.
dotenv with ES Modules
Using import syntax — type: moduleIf your project uses ES Modules ("type": "module" in package.json), require() is not available. Use the ES Module import syntax instead.
// ✅ Option 1 — import dotenv/config (simplest, must be first)
import 'dotenv/config'
import express from 'express'
import mongoose from 'mongoose'
// ✅ Option 2 — import and call manually
import dotenv from 'dotenv'
dotenv.config()
// ✅ Option 3 — Node 20.6+ built-in (no dotenv needed)
// node --env-file=.env server.jsNode.js 20.6+ Built-in Env Loading
Skip dotenv entirely on Node 20.6+Node.js 20.6 added native .env file support. No dotenv package needed.
# Load .env automatically
node --env-file=.env server.js
# Load multiple files
node --env-file=.env --env-file=.env.local server.js{
"scripts": {
"start": "node --env-file=.env server.js",
"dev": "node --env-file=.env --watch server.js"
}
}Environment Variables in Production
Works locally but undefined in productionProduction platforms do NOT use .env files. They have their own environment variable system. Your .env file should be in .gitignore and never deployed.
Heroku
heroku config:set DATABASE_URL=mongodb+srv://...
heroku config:set SESSION_SECRET=mysecret
heroku config # list all varsVercel
vercel env add DATABASE_URL production
# Or in Vercel dashboard: Project → Settings → Environment VariablesRailway / Render
# Dashboard → your project → Variables tab
# Add each variable manuallyAWS EC2 / Ubuntu VPS
# Add to /etc/environment or your app's systemd service file
# Or create .env manually on the server (not in git)
nano /home/ubuntu/myapp/.env
# Add: DATABASE_URL=mongodb+srv://...Always validate required environment variables at startup: if (!process.env.DATABASE_URL) { console.error('Missing DATABASE_URL'); process.exit(1) }
process.env in Next.js
Next.js has different env variable rulesNext.js has its own environment variable system with different prefixes for different contexts:
# Server-only (not exposed to browser)
DATABASE_URL=mongodb://localhost:27017/mydb
SESSION_SECRET=mysecret
# Exposed to browser (MUST have NEXT_PUBLIC_ prefix)
NEXT_PUBLIC_API_URL=http://localhost:5000
NEXT_PUBLIC_STRIPE_KEY=pk_test_...// Server component or API route — any variable works
const dbUrl = process.env.DATABASE_URL
// Client component — ONLY NEXT_PUBLIC_ vars work
const apiUrl = process.env.NEXT_PUBLIC_API_URLDo not add dotenv to a Next.js project — Next.js loads .env files automatically. Adding dotenv can conflict.
Debug — Print All Loaded Variables
const result = require('dotenv').config()
if (result.error) {
console.error('dotenv error:', result.error.message)
} else {
console.log('dotenv loaded:', Object.keys(result.parsed || {}))
// Prints: ['DATABASE_URL', 'PORT', 'SECRET_KEY']
}
// Check a specific variable
console.log('DATABASE_URL:', process.env.DATABASE_URL ?? 'NOT SET')How to Prevent env Variable Issues
- Call require('dotenv').config() as the very first line of your entry file
- Keep .env in project root alongside package.json
- Add .env to .gitignore — never commit secrets
- Create .env.example with same keys but empty values for teammates
- Validate required variables at startup and exit if any are missing
- Use platform environment variable UI (Heroku, Vercel) — never deploy .env to production
- Use NEXT_PUBLIC_ prefix only for variables safe to expose to the browser
Frequently Asked Questions
Why is dotenv not working in Node.js?+−
Why is process.env undefined in Node.js?+−
How do I use dotenv with ES modules?+−
dotenv works locally but variables are undefined in production?+−
Can I have multiple .env files?+−
How do I validate required environment variables?+−
Need Expert Help?
We Build Production-Grade Node.js Apps
Softplix builds full-stack applications. Struggling with Node.js configuration or environment setup? We can help.
Talk to an Engineer