Error: Cannot find module 'dotenv'— Fixed [Complete Guide 2026]
⚡ Quickest Fix — 60 seconds
Navigate to your project folder and install dotenv:
cd your-project-folder
npm install dotenvThen add this as the very first line of your entry file:
require('dotenv').config()Still failing? Check Fix 3 — you may be in the wrong directory.
What Causes Cannot find module 'dotenv'?
Error: Cannot find module 'dotenv'
Require stack:
- /Users/you/projects/myapp/server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object.<anonymous> (/Users/you/projects/myapp/server.js:1:1)dotenv is not a built-in Node.js module — it is an npm package that must be installed as a project dependency. This error means Node.js cannot find it in your node_modules folder. The three most common causes:
| Cause | Fix |
|---|---|
| dotenv was never installed | Fix 1 — npm install dotenv |
| Wrong directory — node_modules is elsewhere | Fix 3 — check pwd |
| Git clone — node_modules not committed | Fix 3 — run npm install |
| ES Modules — require() not available | Fix 5 — use import syntax |
Install dotenv
Most common fixdotenv must be installed in your project. Run this from your project root — the same folder that contains package.json:
npm install dotenvVerify it installed correctly
ls node_modules | grep dotenv
# Should output: dotenvCheck package.json has dotenv listed
{
"dependencies": {
"dotenv": "^16.4.5" // ← should appear here after install
}
}npm install dotenv automatically adds it to package.json. You do not need to add --save explicitly since npm 5.
Call config() Correctly in Your Code
Installed but still getting errorAfter installing dotenv, you must call config() to load the .env file. The most common mistake is either forgetting to call it or calling it too late — after code that reads process.env.
CommonJS — correct usage
// ✅ CORRECT — first line of your entry file
require('dotenv').config()
// Now process.env is populated
const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000
const DB_URL = process.env.DATABASE_URL // available now
app.listen(PORT)Wrong — calling config() too late
// ❌ WRONG — reading process.env BEFORE calling config()
const PORT = process.env.PORT // undefined!
require('dotenv').config() // too late — PORT already read
app.listen(PORT || 3000)Always call require('dotenv').config() before ANY other code that uses process.env. It must be the very first require in your entry file.
Wrong Directory or Missing node_modules
After git clone or in wrong folderIf you are in a different directory than your project, or if you just cloned a repository without running npm install, node_modules will not exist and dotenv will not be found.
# Check where you are
pwd
# Is package.json here?
ls package.json
# Does node_modules exist?
ls node_modules
# Navigate to project and install
cd ~/projects/my-app
npm install # recreates node_modules
node server.jsAfter cloning any repository, always run npm install before starting the app. node_modules is never committed to git.
Fix .env File Placement
dotenv installed but variables undefinedEven after dotenv is installed and config() is called, you may still get issues if your .env file is in the wrong location. dotenv looks for .env in your current working directory — the folder you run node from.
Correct project structure
my-project/
.env ← must be here (project root)
package.json
server.js
node_modules/Check .env file exists
# macOS / Linux
ls -la | grep .env
# Windows
dir /a | findstr .envUsing a custom path for .env
// Default: looks for .env in current working directory
require('dotenv').config()
// Custom path — if your .env is in a different location
require('dotenv').config({ path: './.env.local' })
require('dotenv').config({ path: '/absolute/path/to/.env' })
require('dotenv').config({ path: require('path').join(__dirname, '.env') })Never commit .env to git — it contains secrets. Add .env to .gitignore. Create a .env.example with the same keys but empty values for your teammates.
Fix for ES Modules (import/export)
Using type: module in package.jsonIf your project uses ES Modules — either because you have "type": "module" in package.json or because you use .mjs files — require() is not available and you need a different syntax.
Option A — import dotenv/config (simplest)
// Import this FIRST — before anything that uses process.env
import 'dotenv/config'
import express from 'express'
const app = express()
const PORT = process.env.PORT || 3000
app.listen(PORT)Option B — import and call config()
import dotenv from 'dotenv'
dotenv.config()
import express from 'express'Option C — Node 20.6+ built-in (no dotenv needed)
node --env-file=.env server.js
# Or in package.json scripts:
# "start": "node --env-file=.env server.js"On Node 20.6 and higher, you do not need dotenv at all. The built-in --env-file flag loads your .env automatically.
Node.js 20.6+ Built-in .env Loading
Skip dotenv entirelyNode.js 20.6 added native .env file support. If you are on Node 20.6 or higher, you can load environment variables without installing dotenv at all.
# Check your Node version
node --version
# If 20.6+, run with built-in env loading
node --env-file=.env server.js
# Load multiple .env 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"
}
}Using the built-in flag removes a dependency from your project. If you are on Node 20.6+, consider migrating away from dotenv to the native solution.
dotenv Installed But Variables Still Undefined?
If dotenv is installed and not throwing an error but your process.env variables are still undefined, the problem is configuration — not the module. Check all of these:
| Check | Common mistake |
|---|---|
| .env file format | KEY = value (spaces) — should be KEY=value (no spaces) |
| config() called first | process.env read before require('dotenv').config() |
| .env location | .env is not in the same folder you run node from |
| Variable name typo | process.env.DATABASE_URL vs process.env.DATABASEURL |
| Quotes in .env | KEY="value" — quotes are included in the value string |
Debug dotenv — print all loaded variables
const result = require('dotenv').config()
if (result.error) {
console.error('dotenv error:', result.error)
} else {
console.log('dotenv loaded:', result.parsed) // shows all loaded variables
}How to Prevent This Error
- Add dotenv to package.json with npm install dotenv
- Call require('dotenv').config() as the very first line of your entry file
- Place .env in the project root alongside package.json
- Add .env to .gitignore — never commit secrets
- Create .env.example with keys but empty values for teammates
- Commit package.json and package-lock.json so npm install recreates everything
- Consider Node 20.6+ built-in --env-file flag to eliminate the dotenv dependency
Quick Diagnosis — Work Through in Order
- 1
Are you in your project directory?
cd into your project root
- 2
Run: ls node_modules | grep dotenv
If missing — npm install dotenv
- 3
Is require('dotenv').config() the first line?
Move it to line 1 of your entry file
- 4
Is .env in the project root?
Move .env next to package.json
- 5
Using ES modules?
Use: import 'dotenv/config' instead
- 6
On Node 20.6+?
Use: node --env-file=.env server.js
Frequently Asked Questions
How do I install dotenv in Node.js?+−
Where should the .env file be placed in Node.js?+−
dotenv is installed but process.env variables are still undefined?+−
Can I use dotenv with ES modules (import/export)?+−
Should I commit .env to git?+−
Cannot find module dotenv after npm install — why?+−
Need Expert Help?
We Build Production-Grade Node.js Apps
Softplix is a full-stack development agency. Struggling with Node.js environment configuration in production? We can help.
Talk to an Engineer