Last modified: Jun 24, 2025 By Alexander Williams
Fix Error: Cannot find module 'dotenv'
If you see the error Error: Cannot find module 'dotenv', don't worry. This guide will help you fix it quickly.
Table Of Contents
What Causes the Error?
The error occurs when Node.js cannot locate the dotenv
module. This usually happens if the module is not installed.
It may also appear if the module is installed in the wrong directory or if there are permission issues.
How to Fix the Error
Follow these steps to resolve the issue.
1. Install dotenv
First, ensure the dotenv
module is installed. Run this command in your terminal:
npm install dotenv
If you're using Yarn, run:
yarn add dotenv
2. Check node_modules
Verify that dotenv
is in your node_modules
folder. If not, reinstall it.
Delete node_modules
and package-lock.json
, then run npm install
again.
3. Verify require Statement
Ensure you are requiring dotenv
correctly in your code:
require('dotenv').config(); // Correct usage
A typo in the module name will cause the error.
4. Check File Permissions
If you still face issues, check file permissions. Ensure your project has read/write access.
Example Code
Here’s a simple example using dotenv
:
// Load environment variables
require('dotenv').config();
// Access a variable
console.log(process.env.DB_HOST);
If configured correctly, this will log your database host from the .env
file.
Common Mistakes
Some common mistakes include:
- Misspelling
dotenv
in the require statement. - Not having a
.env
file in the project root. - Forgetting to call
.config()
after requiringdotenv
.
Alternative Solutions
If the issue persists, try these:
- Reinstall Node.js and npm.
- Clear npm cache using
npm cache clean --force
. - Check for similar errors like Cannot find module 'axios' or Cannot find module 'express'.
Conclusion
The Cannot find module 'dotenv' error is easy to fix. Install the module, check your code, and verify permissions.
For more help, see our guide on Node.js module errors.