Node.jsdotenvError Fix2026 Updated

Error: Cannot find module 'dotenv'— Fixed [Complete Guide 2026]

January 20265 min readNode.js · All OS

⚡ Quickest Fix — 60 seconds

Navigate to your project folder and install dotenv:

cd your-project-folder
npm install dotenv

Then add this as the very first line of your entry file:

server.js / index.js — line 1
require('dotenv').config()

Still failing? Check Fix 3 — you may be in the wrong directory.

What Causes Cannot find module 'dotenv'?

Terminal Error
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:

CauseFix
dotenv was never installedFix 1 — npm install dotenv
Wrong directory — node_modules is elsewhereFix 3 — check pwd
Git clone — node_modules not committedFix 3 — run npm install
ES Modules — require() not availableFix 5 — use import syntax
1

Install dotenv

Most common fix
1 min

dotenv must be installed in your project. Run this from your project root — the same folder that contains package.json:

terminal
npm install dotenv

Verify it installed correctly

terminal
ls node_modules | grep dotenv
# Should output: dotenv

Check package.json has dotenv listed

package.json
{
  "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.

2

Call config() Correctly in Your Code

Installed but still getting error
1 min

After 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

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

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

3

Wrong Directory or Missing node_modules

After git clone or in wrong folder
1 min

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

terminal
# 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.js

After cloning any repository, always run npm install before starting the app. node_modules is never committed to git.

4

Fix .env File Placement

dotenv installed but variables undefined
1 min

Even 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

terminal
# macOS / Linux
ls -la | grep .env

# Windows
dir /a | findstr .env

Using a custom path for .env

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

5

Fix for ES Modules (import/export)

Using type: module in package.json
2 min

If 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)

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

server.js (ES Module)
import dotenv from 'dotenv'
dotenv.config()

import express from 'express'

Option C — Node 20.6+ built-in (no dotenv needed)

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

6

Node.js 20.6+ Built-in .env Loading

Skip dotenv entirely
1 min

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

terminal
# 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
package.json
{
  "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:

CheckCommon mistake
.env file formatKEY = value (spaces) — should be KEY=value (no spaces)
config() called firstprocess.env read before require('dotenv').config()
.env location.env is not in the same folder you run node from
Variable name typoprocess.env.DATABASE_URL vs process.env.DATABASEURL
Quotes in .envKEY="value" — quotes are included in the value string

Debug dotenv — print all loaded variables

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

Quick Diagnosis — Work Through in Order

  1. 1

    Are you in your project directory?

    cd into your project root

  2. 2

    Run: ls node_modules | grep dotenv

    If missing — npm install dotenv

  3. 3

    Is require('dotenv').config() the first line?

    Move it to line 1 of your entry file

  4. 4

    Is .env in the project root?

    Move .env next to package.json

  5. 5

    Using ES modules?

    Use: import 'dotenv/config' instead

  6. 6

    On Node 20.6+?

    Use: node --env-file=.env server.js

Frequently Asked Questions

How do I install dotenv in Node.js?+
Run npm install dotenv in your project directory. Then add require('dotenv').config() at the very first line of your entry file — before any other code that reads process.env.
Where should the .env file be placed in Node.js?+
The .env file must be in your project root — the same directory as your package.json file. If it is in a subdirectory, dotenv will not find it automatically unless you pass the path: require('dotenv').config({ path: './.env.local' }).
dotenv is installed but process.env variables are still undefined?+
Make sure require('dotenv').config() is called BEFORE any code that reads process.env. Also check that your .env file uses KEY=value format with no spaces around the equals sign.
Can I use dotenv with ES modules (import/export)?+
Yes. With ES modules use: import 'dotenv/config' instead of require('dotenv').config(). Or use the Node.js built-in --env-file flag on Node 20.6+: node --env-file=.env server.js
Should I commit .env to git?+
Never. Add .env to your .gitignore. Instead commit a .env.example file with the same keys but empty values — this documents what variables teammates need without exposing real secrets.
Cannot find module dotenv after npm install — why?+
Check you are running node from the correct directory. The node_modules folder must be in the same directory you are running node from. Run: ls node_modules | grep dotenv to verify it installed.

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