Last modified: Jul 16, 2025 By Alexander Williams
How to Install Dotenv in Node.js
The dotenv module helps manage environment variables in Node.js. It loads variables from a .env
file into process.env
. This keeps sensitive data secure.
Table Of Contents
Why Use Dotenv?
Storing credentials in code is unsafe. Dotenv lets you keep secrets in a separate file. This file is ignored by Git. It prevents accidental exposure of API keys or passwords.
If you work with APIs, check our guide on installing Axios in Node.js. It pairs well with dotenv.
Prerequisites
Before installing dotenv, ensure you have:
- Node.js installed on your system
- npm (comes with Node.js)
- A Node.js project setup
Install Dotenv
Open your terminal in the project folder. Run this command:
npm install dotenv
This adds dotenv to your node_modules
folder. It also updates package.json
.
Basic Usage
Create a .env
file in your project root. Add your variables like this:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
In your Node.js file, require and configure dotenv:
require('dotenv').config();
console.log(process.env.DB_HOST); // Output: localhost
localhost
Advanced Configuration
You can specify a custom path for your .env
file:
require('dotenv').config({ path: '/custom/path/.env' });
For larger apps, consider using Express with dotenv. They work well together.
Common Errors
If you see "Cannot find module", check our guide on fixing missing modules.
Ensure your .env
file is in the root directory. Node.js looks for it there by default.
Best Practices
Follow these tips for better security:
- Add
.env
to your.gitignore
file - Never commit sensitive data to version control
- Use different
.env
files for development and production
Conclusion
Dotenv simplifies environment management in Node.js. It keeps your credentials secure and separate from code. The setup is quick and improves project security.
For more Node.js tips, explore our other tutorials. Learn to handle modules and errors like a pro.