Node.jsdotenvError Fix2026 Updated

dotenv Not Working in Node.js— process.env undefined Fixed [2026]

Also covers: process.env undefined · Node.js environment variable not loading

January 20266 min readNode.js · All OS

⚡ Most Common Fix

Move require('dotenv').config() to line 1 — before everything else:

server.js — line 1
require('dotenv').config()   // ← MUST be first

const express = require('express')
const mongoose = require('mongoose')
// now process.env.DATABASE_URL etc. are available

Why Is dotenv Not Working?

Output
// All of these print undefined:
console.log(process.env.DATABASE_URL)  // undefined
console.log(process.env.PORT)          // undefined
console.log(process.env.SECRET_KEY)    // undefined

dotenv 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.

SymptomCauseFix
All env vars undefinedconfig() called too lateJump →
Some vars undefinedWrong order / imported after useJump →
.env exists but vars missingWrong .env file locationJump →
Vars have wrong values.env format error (spaces)Jump →
Works locally not in productionProduction doesn't use .env filesJump →
1

Call config() Before Everything Else

Most common fix — call order matters
1 min

dotenv 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.

server.js
// ❌ 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.

2

Fix .env File Location

.env must be in project root
1 min

By 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
Custom .env path if needed
// .env in different location
require('dotenv').config({ path: './.env.local' })
require('dotenv').config({ path: require('path').join(__dirname, '../.env') })
3

Fix .env File Format

Wrong format causes undefined or wrong values
1 min

The .env file format is strict: one variable per line, no spaces around the = sign.

.env — correct format
# ✅ 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/mydb

When 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.

4

dotenv with ES Modules

Using import syntax — type: module
2 min

If your project uses ES Modules ("type": "module" in package.json), require() is not available. Use the ES Module import syntax instead.

server.js (ES Module)
// ✅ 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.js
5

Node.js 20.6+ Built-in Env Loading

Skip dotenv entirely on Node 20.6+
1 min

Node.js 20.6 added native .env file support. No dotenv package needed.

terminal
# Load .env automatically
node --env-file=.env server.js

# Load multiple files
node --env-file=.env --env-file=.env.local server.js
package.json
{
  "scripts": {
    "start": "node --env-file=.env server.js",
    "dev": "node --env-file=.env --watch server.js"
  }
}
6

Environment Variables in Production

Works locally but undefined in production
3 min

Production platforms do NOT use .env files. They have their own environment variable system. Your .env file should be in .gitignore and never deployed.

Heroku

terminal
heroku config:set DATABASE_URL=mongodb+srv://...
heroku config:set SESSION_SECRET=mysecret
heroku config    # list all vars

Vercel

terminal
vercel env add DATABASE_URL production
# Or in Vercel dashboard: Project → Settings → Environment Variables

Railway / Render

# Dashboard → your project → Variables tab
# Add each variable manually

AWS EC2 / Ubuntu VPS

terminal
# 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) }

7

process.env in Next.js

Next.js has different env variable rules
2 min

Next.js has its own environment variable system with different prefixes for different contexts:

.env.local (Next.js)
# 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_...
Next.js — accessing env vars
// 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_URL

Do not add dotenv to a Next.js project — Next.js loads .env files automatically. Adding dotenv can conflict.

Debug — Print All Loaded Variables

server.js — debug dotenv
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

Frequently Asked Questions

Why is dotenv not working in Node.js?+
The three most common causes: 1) require('dotenv').config() is called after code that reads process.env — move it to the very first line, 2) .env file is not in your project root alongside package.json, 3) .env file format has spaces around = signs (KEY = value should be KEY=value).
Why is process.env undefined in Node.js?+
process.env is always an object, never undefined — but specific variables within it will be undefined if dotenv has not loaded them. Check: is dotenv installed, is config() called first, is the .env file in the right location.
How do I use dotenv with ES modules?+
Replace require('dotenv').config() with import 'dotenv/config' as the first import in your entry file. Or on Node 20.6+, use the built-in flag: node --env-file=.env server.js
dotenv works locally but variables are undefined in production?+
Production environments (Heroku, Vercel, Railway, AWS) use their own environment variable system — not .env files. Set variables in your platform's dashboard or CLI. The .env file should be in .gitignore and never deployed.
Can I have multiple .env files?+
Yes. dotenv loads one file at a time: require('dotenv').config({ path: '.env.local' }). You can call config() multiple times with different paths. Common pattern: .env for defaults, .env.local for personal overrides (both in .gitignore).
How do I validate required environment variables?+
Check for required variables at startup and exit if missing: const required = ['DATABASE_URL', 'SESSION_SECRET']; required.forEach(key => { if (!process.env[key]) { console.error(`Missing: ${key}`); process.exit(1) } })

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