How to Use dotenv in Node.js for Environment Variables
Use the
dotenv package in Node.js by installing it with npm install dotenv, creating a .env file with your variables, and loading them at the start of your app with require('dotenv').config(). This makes environment variables accessible via process.env in your code.Syntax
To use dotenv, first import and configure it at the very top of your main JavaScript file. This loads variables from a .env file into process.env.
require('dotenv').config(): Loads the environment variables..envfile: Stores key-value pairs likeKEY=value.process.env.KEY: Accesses the variable in your code.
javascript
require('dotenv').config(); console.log(process.env.MY_VARIABLE);
Output
value_of_MY_VARIABLE
Example
This example shows how to create a .env file, load it with dotenv, and use the variables in your Node.js app.
javascript
// 1. Create a .env file in your project root with: // PORT=3000 // SECRET_KEY=mysecret // 2. Create index.js with: require('dotenv').config(); const port = process.env.PORT; const secret = process.env.SECRET_KEY; console.log(`Server will run on port: ${port}`); console.log(`Secret key is: ${secret}`);
Output
Server will run on port: 3000
Secret key is: mysecret
Common Pitfalls
Common mistakes when using dotenv include:
- Not calling
require('dotenv').config()before accessingprocess.env. - Placing the
.envfile in the wrong directory (it should be in the project root). - Committing
.envto version control, which can expose secrets. - Forgetting to restart the Node.js app after changing
.env.
javascript
// Wrong: Accessing process.env before loading dotenv console.log(process.env.PORT); // undefined require('dotenv').config(); // Right: Load dotenv first require('dotenv').config(); console.log(process.env.PORT); // '3000' if set in .env
Output
undefined
3000
Quick Reference
| Step | Command / Action | Description |
|---|---|---|
| 1 | npm install dotenv | Install dotenv package |
| 2 | Create .env file | Add key=value pairs for environment variables |
| 3 | require('dotenv').config() | Load variables at app start |
| 4 | process.env.KEY | Access variables in code |
| 5 | Add .env to .gitignore | Prevent secrets from being committed |
Key Takeaways
Always call require('dotenv').config() before using process.env variables.
Store environment variables in a .env file at your project root.
Never commit your .env file to version control to keep secrets safe.
Restart your Node.js app after changing environment variables.
Access variables in code using process.env.VARIABLE_NAME.