Borislav Hadzhiev
Sat Mar 26 2022·2 min read
Photo by Clay Banks
To solve the error "Cannot find module 'dotenv'", make sure to install the
dotenv
package by opening your terminal in your project's root directory and
running the following command: npm install dotenv
and restart your IDE and
development server.
Here is an example of how the error occurs.
// ⛔️ Error: Cannot find module 'dotenv' // Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'dotenv' // imported from bobbyhadz-js/index.js require('dotenv').config(); // 👇️ if you use ES6 you only need this line to import // import 'dotenv/config' console.log(process.env.DB_USER); console.log(process.env.ENV); console.log(process.env.DB_PORT);
Open your terminal in your project's root directory (where your package.json
file is located) and run the following command:
npm install dotenv
dotenv
package to the dependencies of your project.If the error is not resolved, try restarting your IDE and your development server.
If you still get the error, try to delete your node_modules
and
package-lock.json
(not package.json
) files, re-run npm install
and restart
your IDE.
# 👇️ delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json # 👇️ clean npm cache npm cache clean --force npm install npm install dotenv@latest
Now create a .env
file in the root directory of your project.
DB_PORT=1234 DB_USER=james_doe ENV=dev
.env
file to your .gitignore
, especially if you work on a public repository.In your index.js
file, before importing anything else, import and initialize
the dotenv
package.
require('dotenv').config(); // 👇️ if you use ES6 you only need this line to import // import 'dotenv/config' console.log(process.env.DB_USER); // 👉️ "james_doe" console.log(process.env.ENV); // 👉️ "dev" console.log(process.env.DB_PORT); // 👉️ "1234"
index.js
file, especially if you have other files that need to access the environment variables.If you import another file before initializing dotenv
, you end up running the
files before the properties are set on the process.env
object.
Now restart your development server and you should see the properties on the
process.env
object print out the specified values.
Note that the DB_PORT
property has a value of type string
, even though we
set it as a number in the .env
file.